【BZOJ】【P1797】【AHOI2009】【最小割】【题解】【最大流+SCC】

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

网上题解很多,不多说了

Code:

//ID:zky
#include<vector>
#include<queue>
#include<stack>
#include<cstdio>
#include<cctype>
#include<climits>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=4010;
struct edge{int u,v,cap,flow;};vector<edge>edges;vector<int>G[maxn];stack<int>S;
void add(int u,int v,int cap);int getint();void Dinic();void deb();void Tarjan(int u);
int n,m,s,t,vis[maxn],cur[maxn],d[maxn],dfn[maxn],low[maxn],Scc_cnt,Bel[maxn],ins[maxn],tot;
int main(){
	n=getint();m=getint();s=getint();t=getint();
	for(int i=1;i<=m;i++){int u=getint(),v=getint(),w=getint();add(u,v,w);}
	Dinic();//deb();
	for(int i=1;i<=n;i++){if(!dfn[i])Tarjan(i);}
	for(int i=0;i<edges.size();i+=2){
		int u=edges[i].u,v=edges[i].v;
		if(Bel[u]!=Bel[v]&&edges[i].cap-edges[i].flow==0){
			if(Bel[u]==Bel[s]&&Bel[v]==Bel[t])puts("1 1");
			else if(Bel[u]==Bel[t]&&Bel[v]==Bel[s])puts("1 1");
			else puts("1 0");
		}else puts("0 0");
	}
	return 0;
} 
void deb(){
	for(int i=0;i<edges.size();i++)if(i%2==0)
	printf("#%d %d -> %d cap:%d flow:%d\n",i,edges[i].u,edges[i].v,edges[i].cap,edges[i].flow);
}
bool bfs(){
	memset(vis,0,sizeof(vis));
	memset(d,0,sizeof(d));
	queue<int>q;q.push(s);
	vis[s]=1;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){
				vis[e.v]=1;
				d[e.v]=d[u]+1;
				q.push(e.v);
			}
		}
	}return vis[t];
}
int dfs(int u,int a){
	if(u==t||a==0)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]==1+d[u]&&(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;
}
void Dinic(){
	int flow=0;
	while(bfs()){
		memset(cur,0,sizeof(cur));int x;
		while(x=dfs(s,INT_MAX)){flow+=x;memset(cur,0,sizeof(cur));}
	}
}
void Tarjan(int u){
	ins[u]=1;dfn[u]=low[u]=++tot;
	S.push(u);
	for(int i=0;i<G[u].size();i++){
		edge e=edges[G[u][i]];
		if(e.cap<=e.flow)continue;
		if(!dfn[e.v]){
			Tarjan(e.v);
			low[u]=min(low[u],low[e.v]);
		}else	if(ins[e.v])low[u]=min(low[u],dfn[e.v]);
	}
	if(dfn[u]==low[u]){
		Scc_cnt++;int v;
		do{
			v=S.top();S.pop();
			Bel[v]=Scc_cnt;ins[v]=0;
		}while(u!=v);
	}
}
int getint(){
	int res=0,ok=0;char ch;
	while(ch=getchar()){
		if(isdigit(ch)){
			res*=10;res+=ch-'0';ok=1;
		}else if(ok)break;
	}return res;
}
void add(int u,int v,int 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);
}


你可能感兴趣的:(bzoj,省选)