其他分享
首页 > 其他分享> > 网络流模板

网络流模板

作者:互联网

刘汝佳的EK板子.. 懂的都懂

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
#define INF 20000000
#define maxn 205
using namespace std;
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 EK{ int n,m;
	int a[maxn],p[maxn];
	vector<Edge> edges;vector<int> G[maxn];
	void init(int 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));
		int m=edges.size();
		G[from].push_back(m-2);
		G[to].push_back(m-1);
	}
	int Maxflow(int s,int t){
		int flow=0;
		for(;;){
			memset(a,0,sizeof(a));
			queue<int> Q;Q.push(s);a[s]=INF;
			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(!a[e.to]&&e.cap>e.flow){
						p[e.to]=G[x][i];
						a[e.to]=min(a[x],e.cap-e.flow);
						Q.push(e.to);
					}
				} if(a[t]) break;
			}
			if(!a[t]) break;
			for(int u=t;u!=s;u=edges[p[u]].from){
				edges[p[u]].flow+=a[t];
				edges[p[u]^1].flow-=a[t];
			}
			flow+=a[t];
		}
		return flow; 
	}
};
int main(){ int n,m,i,j,u,v,w,ans,s,t;EK ek;
while(scanf("%d%d",&m,&n)==2){
	ek.init(n);
	for(i=1;i<=m;i++){
		scanf("%d%d%d",&u,&v,&w);
		ek.ADDedge(u,v,w);
	}
	ans=ek.Maxflow(1,n);cout<<ans<<endl;
}
return 0;}

 

标签:EK,int,flow,网络,edges,maxn,include,模板
来源: https://blog.csdn.net/qq_36018057/article/details/110729453