uva 11825(dp + 状态压缩)

来源:互联网 发布:知乎 德昌路 编辑:程序博客网 时间:2024/06/17 13:07

题意:有n台计算机吗,每个计算机都运行n种服务,一个黑客对于每台计算机可以让一种服务停止,然后和这台计算机相邻的计算机的这种服务都会停止,问最多让多少服务停止。

题解:先把每台计算机和其相邻的计算机都用位向量表示存储到p[i],然后枚举所有选中计算机的情况,得到选中不同计算机的覆盖情况,f[s]表示子集s(计算机集合的分组情况)最多可以分多少组,用状态转移方程f[s] = max{f[s], f[s^s0] + 1}更新f数组,s0是s的子集。

#include <stdio.h>#include <algorithm>using namespace std;const int N = 100000;int n, m, f[N], cover[N], p[N];int main() {int a, cas = 1;while (scanf("%d", &n) && n) {for (int i = 0; i < n; i++) {p[i] = (1 << i);scanf("%d", &m);for (int j = 0; j < m; j++) {scanf("%d", &a);p[i] |= (1 << a);}}for (int S = 0; S < (1 << n); S++) {cover[S] = 0;for (int i = 0; i < n; i++)if (S & (1 << i))cover[S] |= p[i];}f[0] = 0;int temp = (1 << n) - 1;for (int S = 1; S < (1 << n); S++) {f[S] = 0;for (int S0 = S; S0; S0 = (S0 - 1) & S)if (cover[S0] == temp)f[S] = max(f[S], f[S ^ S0] + 1);}printf("Case %d: %d\n", cas++, f[temp]);}return 0;}


0 0