1. 程式人生 > >Dinic模板 (白書) 最大流

Dinic模板 (白書) 最大流

#include<algorithm>
#include<cstring>
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
const int maxn=1e3+10,INF=1e8;
struct Edge{
	int from,to,cap,flow;
	Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
struct Dinic{
	int n,m,s,t;
	vector<int >G[maxn];
	vector<Edge>edges;
	bool vis[maxn];
	int d[maxn],cur[maxn];
	void init(int n){
		this->n=n;
		for(int i=0;i<=n;i++)G[i].clear();
		edges.clear();
	}
	void AddEdge(int from,int to,int cap){
		edges.push_back(Edge(from,to,cap,0));
		edges.push_back(Edge(to,from,0,0));
		m=edges.size();
		G[from].push_back(m-2);
		G[to].push_back(m-1);
	}
	bool bfs(){
		memset(vis,false,sizeof(vis));
		queue<int>Q;
		vis[s]=true;
		d[s]=0;
		Q.push(s);
		while(!Q.empty()){
			int x=Q.front();Q.pop();
			for(int i=0;i<G[x].size();i++){
				Edge &e=edges[G[x][i]];
				if(!vis[e.to] && e.cap>e.flow){
					vis[e.to]=1;
					d[e.to]=d[x]+1;
					Q.push(e.to);
				}
			}
		}
		return vis[t];
	}
	int dfs(int x,int a){//a當前為止所有弧的最小殘量 
		if(x==t || a==0)return a;
		int flow=0,f;
		for(int &i=cur[x];i<G[x].size();i++) {//cur當前弧優化
			Edge &e=edges[G[x][i]];
			if(d[e.to]==d[x]+1 && (f=dfs(e.to,min(a,e.cap-e.flow)))>0){
				e.flow+=f;
				edges[G[x][i]^1].flow-=f;
				flow+=f;
				a-=f;
				if(a==0)break;
			}
		}
		return flow;
	}
	int max_flow(int s,int t){
		this->s=s;this->t=t;
		int flow=0;
		while(bfs()){
			memset(cur,0,sizeof(cur));
			flow+=dfs(s,INF);
		}
		return flow;
	}
};
Dinic solve;
int main(){
	int n,m;
	while(~scanf("%d%d",&m,&n)){
		solve.init(n);
		while(m--){
			int a,b,c;
			scanf("%d%d%d",&a,&b,&c);
			solve.AddEdge(a,b,c);
		}
		printf("%d\n",solve.max_flow(1,n));
	}
	return 0;
}
/*
7 6
1 2 10
1 3 10
2 4 4
2 5 8
3 5 9
4 6 10
5 6 10
*/