杭电ACM3549(最大流)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3549

题目大意:给出一个有向带权图,求出从源点到汇点的最大流。

解题思路:Ford-Fulkerson算法。

AC代码:

#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
#define max 1005
bool visit[max];
int pre[max];
int map[max][max];
int s,t;
int n,m;
bool bfs()
{
	int i,curr;
	queue<int> Q;
	memset(pre,0,sizeof(pre));
	memset(visit,0,sizeof(visit));
	visit[s] = true;
	Q.push(s);
	while(!Q.empty())
	{
		curr = Q.front();
		Q.pop();
//		cout<<"curr"<<curr<<"t"<<t<<endl;
		if(curr==t)return true;
		for(i=1;i<=n;i++)
		{
			if(!visit[i]&&map[curr][i])
			{
				Q.push(i);
				pre[i] = curr;
				visit[i] = true;
			}
		}
	}
	return false;
}

int max_flow()
{
	int i,ans=0;
	while(true)
	{
		if(!bfs())return ans;
		int min = 2000000;
		for(i=t;i!=s;i=pre[i])
			min = min<map[pre[i]][i]?min:map[pre[i]][i];
		for(i=t;i!=s;i=pre[i])
		{
			map[pre[i]][i]-=min;
			map[i][pre[i]]+=min;
		}
//		cout<<min<<endl;
		ans+=min;
	}
}
int main()
{
	int T;
	int u,v,c;
	cin>>T;
	for(int i=1;i<=T;i++)
	{
		cin>>n>>m;
		s = 1;
		t = n;
		memset(map,0,sizeof(map));
		while(m--)
		{
			cin>>u>>v>>c;
			map[u][v]+=c;
		}
		cout<<"Case "<<i<<": "<<max_flow()<<endl;
	}
	return 0;
}


你可能感兴趣的:(算法,ACM,杭电)