Cod sursa(job #721303)

Utilizator doru.nituNitu Doru Constantin doru.nitu Data 23 martie 2012 16:12:57
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include<cstdio>
#include<vector>
#include<queue>

using namespace std;

int i,j,n,m,t[1024],c[1024][1024],f[1024][1024],flux;

vector<int> a[1024];

queue<int> q;

int BF(int s,int d)
{
	memset(t,0,sizeof(t));
	
	q.push(s);

	while(!q.empty()&&!t[d])
	{
		int u=q.front();
		q.pop();
		
		for(int j=0;j<a[u].size();++j)
		{
			int fiu=a[u][j];
			if(!t[fiu]&&c[u][fiu]>f[u][fiu])
			{
				t[fiu]=u;
				q.push(fiu);
			}
		}
	}
	while(!q.empty())	q.pop();
	
	if(t[d]) return 1;
	return 0;
}

void fluxmax(int s,int d)
{
	while(BF(s,d))
	{
		int r=1000000;
		
		int j=d;
		while(j&&j!=s)
		{
			r=min(r,c[t[j]][j]-f[t[j]][j]);
			j=t[j];
		}
		
		j=d;
		while(j&&j!=s)
		{
			f[t[j]][j]+=r;
			f[j][t[j]]-=r;
			j=t[j];
		}
		
		flux+=r;
	}
}

int main()
{
	freopen("maxflow.in","r",stdin);
	freopen("maxflow.out","w",stdout);
	
	scanf("%d %d",&n,&m);
	
	for(i=1;i<=m;++i)
	{
		int x,y,z;
		scanf("%d %d %d",&x,&y,&z);
		
		c[x][y]=z;
		
		a[x].push_back(y);
		a[y].push_back(x);
	}
	
	fluxmax(1,n);
	
	printf("%d\n",flux);
	
	fclose(stdin);
	fclose(stdout);
	
	return 0;
}