【poj3084】 Panic Room

http://poj.org/problem?id=3084 (题目链接)

题意

  一个房子里面有m个房间,一些房间之间有门相连,而门的开关只在一个房间有,也就是说只有一个房间可以控制该扇门的开关。现在一些房间出现了入侵者,问最少需要关紧几扇门才能够保护第n号房间。

Solution

  最少关闭多少扇门使得n号点不与入侵点联通,很容易看出最小割模型,于是建图就变得很显然。

  对于一扇门(u,v):从u连一条容量为1的边到v,表示这扇门可以被u关闭;从v连一条容量为inf的边到u,表示这扇门不可以被v关闭。再新建汇点t,从所有入侵点向t连容量为inf的边。接下来从n向t跑Dinic求最小割即可。

细节

  注意特判无解的情况。

代码

// poj3084
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
#define LL long long
#define inf 1000000000
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;

const int maxn=10010;
struct edge {int to,next,w;}e[maxn];
int head[maxn],d[maxn];
int m,cnt,ans,es,et;
char ch[10];

void Init() {
	memset(head,0,sizeof(head));
	cnt=1;ans=0;
}
void link(int u,int v,int w) {
	e[++cnt]=(edge){v,head[u],w};head[u]=cnt;
}
bool bfs() {
	memset(d,-1,sizeof(d));
	queue<int> q;q.push(es);d[es]=0;
	while (!q.empty()) {
		int x=q.front();q.pop();
		for (int i=head[x];i;i=e[i].next) if (e[i].w && d[e[i].to]<0) {
				d[e[i].to]=d[x]+1;
				q.push(e[i].to);
			}
	}
	return d[et]>0;
}
int dfs(int x,int f) {
	if (x==et || f==0) return f;
	int used=0,w;
	for (int i=head[x];i;i=e[i].next) if (e[i].w && d[e[i].to]==d[x]+1) {
			w=dfs(e[i].to,min(e[i].w,f-used));
			used+=w;
			e[i].w-=w;e[i^1].w+=w;
			if (used==f) return used;
		}
	if (!used) d[x]=-1;
	return used;
}
bool Dinic() {
	while (bfs()) {
		int tmp=dfs(es,inf);
		if (tmp==inf) return 0;
		else ans+=tmp;
	}
	return 1;
}		
int main() {
	int T;scanf("%d",&T);
	while (T--) {
		Init();
		scanf("%d%d",&m,&es);es++;et=m+1;
		for (int x,u=1;u<=m;u++) {
			scanf("%s",ch);
			if (ch[0]=='I') link(u,et,inf),link(et,u,0);
			scanf("%d",&x);
			for (int v,i=1;i<=x;i++) {
				scanf("%d",&v);v++;
				link(u,v,1);link(v,u,inf);
			}
		}
		if (Dinic()) printf("%d
",ans);
		else puts("PANIC ROOM BREACH");
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/MashiroSky/p/6216197.html