题意:
有一些建在一起的房间,互相之间通过门相连,一个门的控制开关在它连接的两个房间中的一个里,
在有开关的房间可以任意进入没开关的另一侧房间,而在另一侧的房间中要进入有开关的房间中则需要门是开着的,
现在有的房间中有入侵者,同时有一个非常重要的房间需要保护,问要保护那个房间不被入侵,最少要关上几道门。
解析:
主要在于建图。
对于在开关侧房间的入侵者,无论关多少个门,都无法阻止他进入开关连接的另一侧房间,
对于在开关另一侧房间的入侵者,只要关上这个开关,就可以阻止他进入有开关的一侧房间,
所以可以以房间为顶点,门为边,将两种情况分别连无穷大的容量与1 的容量,
另外设一个单独的源点,将其到每个有入侵者的房间连无穷大的边,求出从源点到保护房间的最大流,即可知道最少要关几个门。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1
using namespace std;
const int maxn = 20 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = acos(-1.0);
const double ee = exp(1.0);
int m, n;
int flow[maxn][maxn];
int cap[maxn][maxn];
int lev[maxn];
int a[maxn];
//bfs找层次网络,一次寻找多条增广路径
//st最小顶点编号,ed最大顶点编号,s源点,t汇点
bool bfs(int st, int ed, int s, int t)
{
memset(lev, inf, sizeof(lev));
queue<int> q;
q.push(s);
lev[s] = 0;
while (!q.empty())
{
int t = q.front();
q.pop();
for (int i = st; i <= ed; i++)
{
if (flow[t][i] < cap[t][i])
{
if (lev[t] + 1 < lev[i])
{
lev[i] = lev[t] + 1;
q.push(i);
}
}
}
}
return lev[t] < inf;
}
//利用层次网络进行增广,每次dfs寻找的是从该点出发进行dfs增加的总量
//a表示从源点到该节点可增广流量
int dfs(int v, int st, int ed, int s, int t)
{
int res = 0;
if (v == t)
return a[t];
for (int i = st; i <= ed; i++)
{
if (a[v] == 0)
break;
if (flow[v][i] < cap[v][i] && lev[v] + 1 == lev[i])
{
a[i] = min(a[v], cap[v][i] - flow[v][i]);
int temp = dfs(i, st, ed, s, t);
res += temp;
a[v] -= temp;
flow[v][i] += temp;
flow[i][v] -= temp;
}
}
if (res == 0)
{
lev[v] = inf;
}
return res;
}
int dinic(int st, int ed, int s, int t)
{
int res = 0;
while (bfs(st, ed, s, t))
{
memset(a, inf, sizeof(a));
int temp = dfs(s, st, ed, s, t);
if (temp == 0)
break;
res += temp;
}
return res;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
int ncase;
scanf("%d", &ncase);
while (ncase--)
{
memset(flow, 0, sizeof(flow));
memset(cap, 0, sizeof(cap));
scanf("%d%d", &m, &n);
int s = m, t = n;
for (int i = 0; i < m; i++)
{
char op[3];
int cnt;
scanf("%s", op);
scanf("%d", &cnt);
while (cnt--)
{
int x;
scanf("%d", &x);
cap[i][x] = inf;
cap[x][i] += 1;
}
if (op[0] == 'I')
{
cap[s][i] = inf;
}
}
int ans = dinic(0, m, s, t);
if (ans < inf)
printf("%d\n", ans);
else
printf("PANIC ROOM BREACH\n");
}
return 0;
}