LG1345 「USACO5.4」Telecowmunication 最小割

问题描述

LG1345


题解

点边转化,最小割,完事。


\(\mathrm{Code}\)

#include<bits/stdc++.h>
using namespace std;

template <typename Tp>
void read(Tp &x){
	x=0;char ch=1;int fh;
	while(ch!='-'&&(ch>'9'||ch<'0')) ch=getchar();
	if(ch=='-') ch=getchar(),fh=-1;
	else fh=1;
	while(ch>='0'&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
	x*=fh;
}

const int maxn=1007;
const int maxm=10007;
const int INF=0x3f3f3f3f;

int n,m,xx,yy;
int Head[maxn],to[maxm],w[maxm],Next[maxm],tot=1;

void add(int x,int y,int z){
	to[++tot]=y,Next[tot]=Head[x],Head[x]=tot,w[tot]=z;//错误笔记:如果我加边再不计边权,我就*****
}

int S,T,d[maxn];

bool bfs(){
	memset(d,0,sizeof(d));
	queue<int>q;q.push(S);d[S]=1;
	while(!q.empty()){
		int x=q.front();q.pop();
		for(int i=Head[x];i;i=Next[i]){
			int y=to[i];
			if(d[y]||!w[i]) continue;
			q.push(y);d[y]=d[x]+1;
			if(y==T) return true;
		}
	}
	return false;
}

int dfs(int x,int flow){
	if(x==T) return flow;
	int rest=flow;
	for(int i=Head[x];i&&rest;i=Next[i]){
		int y=to[i];
		if(d[y]!=d[x]+1||!w[i]) continue;
		int k=dfs(y,min(rest,w[i]));
		if(!k) d[y]=0;
		else{
			w[i]-=k,w[i xor 1]+=k;
			rest-=k;
		}
	}
	return flow-rest;
}

int main(){
	read(n);read(m);read(xx);read(yy);
	for(int i=1,x,y;i<=m;i++){
		read(x);read(y);
		add(x+n,y,INF);add(y,x+n,0);
		add(y+n,x,INF);add(x,y+n,0);
	}
	for(int i=1;i<=n;i++){
		add(i,i+n,1);add(i+n,i,0);
	}
	S=xx+n,T=yy;
	int ans=0;
	while(bfs()){
		int t;
		while(t=dfs(S,0x3f3f3f3f)) ans+=t;
	}
	printf("%d\n",ans);
	return 0;
}
posted @ 2019-11-01 21:55  览遍千秋  阅读(126)  评论(0编辑  收藏  举报