bzoj1231 [Usaco2008 Nov] mixup2 混乱的奶牛

Description

Farmer John 的 \(N(4 \le N \le 16)\) 头奶牛中的每一头都有一个唯一的编号 \(S_i (1 \le S_i \le 25,000)\) . 奶牛为她们的编号感到骄傲, 所以每一头奶牛都把她的编号刻在一个金牌上, 并且把金牌挂在她们宽大的脖子上. 奶牛们对在挤奶的时候被排成一支"混乱"的队伍非常反感. 如果一个队伍里任意两头相邻的奶牛的编号相差超过 \(K (1 \le K \le 3400)\) , 它就被称为是混乱的. 比如说,当 \(N = 6, K = 1\) 时, \(1, 3, 5, 2, 6, 4\) 就是一支"混乱"的队伍, 但是 \(1, 3, 6, 5, 2, 4\) 不是(因为 \(5\)\(6\) 只相差 \(1\) ). 那么, 有多少种能够使奶牛排成"混乱"的队伍的方案呢?

Input

\(1\) 行: 用空格隔开的两个整数 \(N\)\(K\)

\(2\cdots N+1\) 行: 第 \(i+1\) 行包含了一个用来表示第i头奶牛的编号的整数: \(S_i\)

Output

\(1\) 行: 只有一个整数, 表示有多少种能够使奶牛排成"混乱"的队伍的方案. 答案保证是 一个在 \(64\) 位范围内的整数.

Sample Input

4 1
3
4
2
1

Sample Output

2

Solution

状压 dp 。 \(f[i][j]\) 表示以奶牛 \(i\) 结尾,选取状态为 \(j\) 的方案数。答案是 $$\sum_{i=1}^n f[i][(1<<n)-1]$$ 转移显然。

#include<bits/stdc++.h>
using namespace std;

#define N 17
#define rep(i, a, b) for (int i = a; i <= b; i++)

inline int read() {
	int x = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (!(ch ^ '-')) flag = -1; ch = getchar(); }
	while (isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar(); return x * flag;
}

int n, K, s[N], t[N]; long long f[N][1 << N], ans;

int main() {
	n = read(), K = read(); int S = (1 << n) - 1;
	rep(i, 1, n) s[i] = read(), t[i] = 1 << i - 1, f[i][t[i]] = 1;
	rep(i, 0, S) rep(j, 1, n) if (i & t[j]) rep(k, 1, n) if (!(i & t[k]) && abs(s[j] - s[k]) > K) f[k][t[k] | i] += f[j][i];
	rep(i, 1, n) ans += f[i][S];
	printf("%lld", ans);
	return 0;
}
posted @ 2018-02-19 10:51  aziint  阅读(108)  评论(0编辑  收藏  举报
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.