---
id: 131
title: "P2915:「USACO08NOV」奶牛混合起来题解"
slug: p2915
lang: zh
date: 2018-11-05T15:34:43
date_gmt: 2018-11-05T07:34:43
modified: 2023-11-11T14:50:55
status: publish
password_protected: false
category: { name: Olympiad in Informatics, slug: oi }
tags: [OI, DP, 状压dp]
original_url: https://kalorona.com/oi/p2915/
archived: 2026-11-27
editor: gutenberg
media: []
archive_notes:
  - "Body headings were <h1> in the original; demoted to level 2 so the page title is the only h1."
  - "The final code block had Enlighter language null; tagged as cpp from its content."
  - "Dropped target=\"_blank\" and rel=\"noopener\" from the link to the 互不侵犯 post; href kept as-is."
comments: []
---

## 思路

这道题观察数据范围和题干，可以得知这是一道状压dp的题目。我们先来设计状态：在本题中，可以类比互不侵犯的那一题（[互不侵犯题解](../126-p1896/index.html)），设计成当前状态和上一状态**相关的元素**。可以想出，dp[当前牛的存在情况][当前加入的牛的编号] += dp[上一次加入后的状态][上一次加入的牛的编号];

基本上完成了思考，现在我们先来搞定预处理。我们把只有cowId在队列里的方案数初始化为1。

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

之后我们就可以进行dp了。详细见代码：

```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];
```

最后方案数叠加，在满员的状态下枚举最后一头牛的id。

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

## 代码

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