---
id: 131
lang: en
translation_of: index.md
source_sha256: 32e48d759daf19e94f5ac7128f2f0ec0389871eaf589017eca6912f12e75f4bd
title: "P2915: [USACO08NOV] Mixed Up Cows — Solution"
description: "Looking at the constraints and the problem statement, you can tell this is a bitmask DP problem."
tags: ["OI","DP","Bitmask DP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "奶牛混合起来 (problem name) rendered as “Mixed Up Cows”, the USACO English title."
  - "互不侵犯 (the SCOI2005 problem P1896) rendered as “Non-Aggression”."
---

## 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](../126-p1896/index.en.html)), 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.

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

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

```cpp
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.

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

## Code

```cpp
// 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;
}
```
