Olympiad in Informatics

P2915: [USACO08NOV] Mixed Up Cows — Solution

Approach

Looking at the constraints and the problem statement, you can tell this is a bitmask DP problem. Let's design the state first: in this problem, by analogy with the Non-Aggression problem (Non-Aggression solution), we design it as the related elements of the current state and the previous state. You can come up with: dp[which cows are currently present][index of the cow just added] += dp[state after the previous addition][index of the cow added last time];

The thinking is basically done, so now let's get the preprocessing out of the way first. We initialize the number of ways in which only cowId is in the queue to 1.

for (int cowId = 0; cowId < n; cowId++)
        dp[1 << cowId][cowId] = 1;

After that we can run the DP. See the code for details:

for (int lastState = 0; lastState < (1 << n); lastState++)
    for (int lastCow = 0; lastCow < n; lastCow++)
        if (lastState & (1 << lastCow))
            for (int nowCow = 0; nowCow < n; nowCow++)
                if (!(lastState & (1 << nowCow)) && abs(seq[nowCow] - seq[lastCow]) > k)
                    nowState = lastState | (1 << nowCow),
                    dp[nowState][nowCow] += dp[lastState][lastCow];

Finally, add up the counts: in the full state, enumerate the id of the last cow.

ll ans = 0;
for (int i = 0; i < n; i++)
    ans += dp[(1 << n) - 1][i];
cout << ans;

Code

// P2915.cpp
#include <iostream>
#include <cmath>
using namespace std;

#define ll unsigned long long
const int maxn = 16;
ll dp[1 << maxn][maxn];
int n, k, nowState;
int seq[maxn];

int main()
{
    cin >> n >> k;
    for (int i = 0; i < n; i++)
        cin >> seq[i];
    for (int cowId = 0; cowId < n; cowId++)
        dp[1 << cowId][cowId] = 1;
    for (int lastState = 0; lastState < (1 << n); lastState++)
        for (int lastCow = 0; lastCow < n; lastCow++)
            if (lastState & (1 << lastCow))
                for (int nowCow = 0; nowCow < n; nowCow++)
                    if (!(lastState & (1 << nowCow)) && abs(seq[nowCow] - seq[lastCow]) > k)
                        nowState = lastState | (1 << nowCow),
                        dp[nowState][nowCow] += dp[lastState][lastCow];
    ll ans = 0;
    for (int i = 0; i < n; i++)
        ans += dp[(1 << n) - 1][i];
    cout << ans;
    return 0;
}