【BZOJ】【P1322】【Zju2429 Destroying The Graph】【题解】【最小割】

传送门:http://www.lydsy.com/JudgeOnline/problem.php?id=1322

点i拆为i和i'

s->i cap=Wi-

i'->t cap=Wi+

原图中的有向边u,v

u->v' cap=inf

最小割显然

Code:

#include<bits/stdc++.h>
using namespace std;
const int maxn=205;
struct edge{int u,v,cap,flow;};
vector<edge>edges;
vector<int>G[maxn];
int s,t;
int cur[maxn],d[maxn];
void add(int u,int v,int cap){
//	printf("%d->%d cap:%d\n",u,v,cap);
	edges.push_back((edge){u,v,cap,0});
	G[u].push_back(edges.size()-1);
	edges.push_back((edge){v,u,0,0});
	G[v].push_back(edges.size()-1);
}
bool bfs(){
	static int vis[maxn];
	memset(vis,0,sizeof vis);vis[s]=1;
	queue<int>q;q.push(s);d[s]=0;
	while(!q.empty()){
		int u=q.front();q.pop();
		for(int i=0;i<G[u].size();i++){
			edge e=edges[G[u][i]];if(vis[e.v]||e.cap==e.flow)continue;
			d[e.v]=d[u]+1;vis[e.v]=1;q.push(e.v);
		}
	}return vis[t];
}
int dfs(int u,int a){
	if(u==t||!a)return a;
	int flow=0,f;
	for(int &i=cur[u];i<G[u].size();i++){
		edge e=edges[G[u][i]];
		if(d[e.v]==d[u]+1&&(f=dfs(e.v,min(a,e.cap-e.flow)))>0){
			edges[G[u][i]].flow+=f;
			edges[G[u][i]^1].flow-=f;
			flow+=f;a-=f;if(!a)break;
		}
	}return flow;
}
int dinic(){
	int flow=0,x;
	while(bfs()){
		memset(cur,0,sizeof cur);
		while(x=dfs(s,INT_MAX)){
			flow+=x;
			memset(cur,0,sizeof cur);
		}
	}return flow;
}
int n,m,win[maxn],wout[maxn];
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)scanf("%d",&win[i]);
	for(int i=1;i<=n;i++)scanf("%d",&wout[i]);
	s=0;t=201;
	for(int i=1;i<=n;i++)add(s,i,wout[i]);
	for(int i=1;i<=n;i++)add(i+n,t,win[i]);
	for(int i=1;i<=m;i++){
		int u,v;scanf("%d%d",&u,&v);
		add(u,v+n,INT_MAX);
	}
//	for(int i=0;i<edges.size();i++)if(i%2==0)
//	printf("%d->%d cap:%d\n",edges[i].u,edges[i].v,edges[i].cap);
	cout<<dinic()<<endl;
	return 0;
}



你可能感兴趣的:(bzoj)