POJ1273(最大流入门)

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;

vector<int> V[205];
int vstd[205],pre[205];
int c[205][205],f[205][205],cf[205][205];
const int maxn=0x7fffffff;
int main()
{
	int n,m;
	while (scanf("%d",&n)!=EOF)
	{
		long long ans=0;
		memset(c,0,sizeof(c));
		memset(f,0,sizeof(f));
		memset(cf,0,sizeof(cf));
		scanf("%d",&m);
		int i;
		for (i=1;i<=m;i++)
			V[i].clear();
		for (i=0;i<n;i++)
		{
			int a,b,x;
			scanf("%d%d",&a,&b);
			scanf("%d",&x);
			if (!c[a][b])
			{
				V[a].push_back(b);
				V[b].push_back(a);
			}
			c[a][b]+=x;
		}

		while (1)
		{
			memset(vstd,0,sizeof(vstd));
			memset(pre,0,sizeof(pre));
			queue<int> Q;
			Q.push(1);
			vstd[1]=1;
			pre[1]=0;
			while (!Q.empty())
			{
				int front=Q.front();
				if (front==m)
					break;
				for (i=0;i<(int)V[front].size();i++)
				{
					int next=V[front][i];
					cf[front][next]=c[front][next]-f[front][next];
					if (!vstd[next] && cf[front][next]>0)
					{
						Q.push(next);
						vstd[next]=1;
						pre[next]=front;
					}
				}
				Q.pop();
			}
			if (Q.empty()) break;
			else
			{
				int x=m;
				int minCf=maxn;
				while (pre[x])
				{
					int a=pre[x],b=x;
					cf[a][b]=c[a][b]-f[a][b];
					if (cf[a][b]<minCf)
						minCf=cf[a][b];
					x=pre[x];
				}
				ans+=minCf;
				x=m;
				while (pre[x])
				{
					int a=pre[x],b=x;
					f[a][b]+=minCf;
					f[b][a]=-f[a][b];
					x=pre[x];
				}
			}
		}
		cout << ans << endl;
	}
}

你可能感兴趣的:(POJ1273(最大流入门))