最大流模板(dinic)

 

以 POJ 1273爲例

//#include<bits/stdc++.h>
#include<cstdio>
#include<vector>
#include<queue>
#include<cstring>
using namespace std;
const int maxn=100005;
const int inf=0x3f3f3f;
typedef long long ll;
int cur[maxn],d[maxn];
bool vis[maxn];
int n,m,x,y,z;

struct edge{
	int s,t;
	ll cap,flow;
	edge(){}
	edge(int s,int t,int cap,int flow):s(s),t(t),cap(cap),flow(flow){}
};

vector<int> e[maxn];
vector<edge> v;

void add_edge(int x,int y,int z){
	v.push_back(edge(x,y,z,0));
	v.push_back(edge(y,x,0,0));
	int temp=v.size();
	e[x].push_back(temp-2);
	e[y].push_back(temp-1);
}

bool bfs(){
	memset(vis,0,sizeof(vis));
	queue<int> q;
	d[1]=0;
	vis[1]=1;
	q.push(1);
	while(!q.empty()){
		int temp=q.front(); q.pop();
		for(int i=0;i<e[temp].size();i++){
			int j=e[temp][i];
			edge &w=v[j];
			if(!vis[w.t]&&w.cap>w.flow){
				d[w.t]=d[temp]+1;
				vis[w.t]=1;
				q.push(w.t);
			}
		}
	}
	return vis[m];
}

ll dfs(int x,ll y){
	if(x==m||y==0) return y;
	ll flow=0,c;
	for(int& i=cur[x];i<e[x].size();i++){
		int j=e[x][i];
		edge &w=v[j];
		if(d[x]+1==d[w.t]&&(c=dfs(w.t,min(y,w.cap-w.flow)))>0){
			v[j].flow+=c;
			v[j^1].flow-=c;
			flow+=c;
			y-=c;
			if(y==0) break;
		}
	}
	return flow;
}

int main(){
	
	while(~scanf("%d%d",&n,&m)) {
		for(int i=1;i<=n;i++){
			e[i].clear();
		}
		v.clear();
		for(int i=1;i<=n;i++){
			scanf("%d%d%d",&x,&y,&z);
			add_edge(x,y,z);
		}
		ll max=0;
		while(bfs()){
			memset(cur,0,sizeof(cur));
			max+=dfs(1,inf);
			
		}
		printf("%lld\n",max);
	}
	return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章