Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P1896 [SCOI2005]互不侵犯

P1896 [SCOI2005]互不侵犯

看到 $n \le 9$ ,考虑状态压缩。对于一般的棋盘状的状压DP,常用的策略是对于一层,先生成出所有合法的状态。因为不能在八连通的两个格子同时放国王,所以在一层中的要求即相邻的格子不能同时放国王。同时,这题要求放特定的个数的国王,所以对于每一个状态我们同时要预处理出其中选择放的格子的个数。不难发现,每一层的方案只和上一层有关,与上上层无关,所以一层的状态从上一层转移即可。用 $f(i, x, j)$ 表示当前在第 $i$ 行,状态为 $x$ ,数量为 $j$ ,易得转移方程 $f(i, x, j) = \displaystyle \sum _ {同时选择 x 和 y 合法} f(i - 1, y, j - num(x))$ ,其中 $num(x)$ 表示该状态中选择的个数。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const int N = 2e3 + 10;
LL f[11][N][110];
int n, k, cnt, state[N], num[N];
bool check (int x, int y)
{
if ((state[x] & state[y]) | ((state[x] << 1) & state[y]) | (state[x] & (state[y] << 1)))
return false;
return true;
}
int main ()
{
cin >> n >> k;
for (int i = 0; i < 1 << n; i++)
{
bool flag = true;
for (int j = 0; j < n - 1; j++)
if ((i >> j & 1) & (i >> j + 1 & 1))
{
flag = false;
break;
}
if (!flag)
continue;
state[++cnt] = i;
for (int j = i; j; j >>= 1)
num[cnt] += j & 1;
}
for (int i = 1; i <= cnt; i++)
f[1][i][num[i]] = 1;
for (int i = 2; i <= n; i++)
for (int x = 1; x <= cnt; x++)
for (int y = 1; y <= cnt; y++)
if (check(x, y))
for (int j = num[x]; j <= k; j++)
f[i][x][j] += f[i - 1][y][j - num[x]];
LL res = 0;
for (int i = 1; i <= cnt; i++)
res += f[n][i][k];
cout << res;
return 0;
}