网络流最大流模板(poj1273)

2012-11-3


#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <string>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cstdio>
#include <map>


using namespace std; 

int const MAX=256; 
int const inf=0x3f3f3f3f; 
int N, M; 
int m[MAX][MAX], flow[MAX], v[MAX], front[MAX]; 
//m[][]残留网络, flow[]各点的流, v[]访问记录, front[]前节点

int bfs(int s, int t)
{
	int i, u; 
	memset(v, 0, sizeof v); 
	memset(flow, 0, sizeof flow); //没流入则为空
	queue<int> Q; 
	while(!Q.empty()) Q.pop(); 
	flow[s] = inf;//初始流inf 
	v[s] = 1; 
	Q.push(s); 
	while(!Q.empty())
	{
		u=Q.front(); 
		Q.pop(); 
		for(i=1; i<=M; i++)
		{
			if(!v[i] && m[u][i]>0)//没访问,有通路
			{	//流量跟上限比较, 取小者
				flow[i]=m[u][i]<flow[u]?m[u][i]:flow[u]; 
				front[i]=u; 
				v[i]=1; 
				Q.push(i); 
			}
		}
	}
	if(flow[t]==0)
		return 0; 	
	return flow[t]; 
}

int EK(int s, int t)
{
	int f, u, max_f=0; 	
	while((f=bfs(s, t))!=0)
	{
		//从尾部向前更新残留网络
		u = t; 
		while(u!=s)
		{
			m[front[u]][u] -= f; 
			m[u][front[u]] += f; 
			u=front[u]; 
		}
		max_f += f; 
	}
	return max_f; 
}

int main()
{
#ifndef ONLINE_JUDGE
	ifstream cin("in.txt"); 
#endif

	int i; 
	while(cin>>N>>M)
	{
		int x, y, f; 
		memset(m, 0, sizeof m); 
		for(i=0; i<N; i++)
		{//m[][] 为残留网络
			cin>>x>>y>>f; 
			m[x][y] += f; 
		}
		cout<<EK(1,M)<<endl; 
	}
	cout<<inf<<endl; 
	return 0; 
}


你可能感兴趣的:(网络流最大流模板(poj1273))