题目链接
http://acm.hust.edu.cn/vjudge/problem/31961
思路
题目中n最大到16,因此考虑状压dp
定义状态d[i][s]:当前已经消灭了i个机器人,并且消灭过的机器人的状态为s的总方案数
转移方程:d[i][s] = sum(d[i - 1][ps]); 其中s和ps只有一位不同,并且s中1的个数比ps中1的个数多1
边界:d[0][0] = 0
目标:d[n][(1 << n) - 1]
细节
- 可先预处理出选出的机器人集合能够消灭的其他机器人
- 注意不要忘记root机器人的武器
代码
#include <iostream>
#include <cstring>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <cmath>
#include <queue>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <deque>
#include <bitset>
#include <algorithm>
using namespace std;
#define PI acos(-1.0)
#define LL long long
#define PII pair<int, int>
#define PLL pair<LL, LL>
#define mp make_pair
#define IN freopen("in.txt", "r", stdin)
#define OUT freopen("out.txt", "wb", stdout)
#define scan(x) scanf("%d", &x)
#define scan2(x, y) scanf("%d%d", &x, &y)
#define scan3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define sqr(x) (x) * (x)
#define pr(x) cout << #x << " = " << x << endl
#define lc o << 1
#define rc o << 1 | 1
#define pl() cout << endl
#define CLR(a, x) memset(a, x, sizeof(a))
#define FILL(a, n, x) for (int i = 0; i < n; i++) a[i] = x
const int maxn = 17;
int ab[maxn], root, c[1 << maxn];
LL d[maxn][1 << maxn];
int n, num[1 << maxn];
char s[maxn];
void init() {
memset(c, 0, sizeof(c));
int ALL = 1 << n;
for (int s = 0; s < ALL; s++) {
num[s] = __builtin_popcount(s);
for (int i = 1; i <= n; i++) {
if (s & (1 << (i - 1))) c[s] |= ab[i];
}
}
c[0] = root;
}
LL dp() {
CLR(d, 0);
d[0][0] = 1;
int ALL = 1 << n;
for (int i = 1; i <= n; i++) {
for (int s = 0; s < ALL; s++) {
for (int k = 0; k < n; k++) {
if ((s & (1 << k)) == 0) continue;
int ps = s ^ (1 << k);
if (((c[ps] & (1 << k)) == 0) && (c[0] & (1 << k)) == 0) continue;
d[i][s] += d[i - 1][ps];
}
}
}
return d[n][ALL - 1];
}
int main() {
int T, kase = 0;
scan(T);
while (T--) {
scan(n);
memset(s, '\0', sizeof(s));
scanf("%s", s);
root = 0;
for (int i = 0; i < n; i++) root += ((s[i] - '0') << i);
for (int i = 1; i <= n; i++) {
scanf("%s", &s);
ab[i] = 0;
for (int j = 0; j < n; j++) ab[i] += ((s[j] - '0') << j);
}
init();
LL ans = dp();
printf("Case %d: %lld\n", ++kase, ans);
}
return 0;
}