Cod sursa(job #241789)

Utilizator AndreyPAndrei Poenaru AndreyP Data 11 ianuarie 2009 00:21:33
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 1005
const int inf=1<<30;
int *a[N];
int cvec[N];
int c[N][N],f[N][N];
int t[N],q[N];
bool viz[N];
int n,m,flux;
struct ajt
{
	int x,y;
};
inline int min(int x,int y)
{
	if(x<y)
		return x;
	return y;
}
void citire()
{
	scanf("%d%d",&n,&m);
	int z;
	ajt v[5010];
	for(int i=0; i<m; i++)
	{
		scanf("%d%d%d",&v[i].x,&v[i].y,&z);
		++cvec[v[i].x];
		++cvec[v[i].y];
		c[v[i].x][v[i].y]=z;
	}
	for(int i=1; i<=n; i++)
	{
		a[i]=new int[cvec[i]+2];
		a[i][0]=0;
	}
	for(int i=0; i<m; i++)
	{
		a[v[i].x][++a[v[i].x][0]]=v[i].y;
		a[v[i].y][++a[v[i].y][0]]=v[i].x;
	}
}
bool bfs()
{
	int p=0,u=0,now,next;
	q[0]=1;
	memset(viz,0,sizeof(viz));
	viz[1]=true;
	while(p<=u)
	{
		now=q[p++];
		if(now==n)
			continue;
		for(int i=1; i<=cvec[now]; i++)
		{
			next=a[now][i];
			if(viz[next] || c[now][next]==f[now][next])
				continue;
			viz[next]=true;
			q[++u]=next;
			t[next]=now;
		}
	}
	return viz[n];
}
int main()
{
	freopen("maxflow.in","r",stdin);
	freopen("maxflow.out","w",stdout);
	citire();
	int r,nod,j;
	while(bfs())
	{
		for(int i=1; i<=cvec[n]; i++)
		{
			nod=a[n][i];
			if(!viz[nod] || f[nod][n]==c[nod][n])
				continue;
			r=inf;
			t[n]=nod;
			j=n;
			while(j!=1)
			{
				r=min(r,c[t[j]][j]-f[t[j]][j]);
				j=t[j];
			}
			if(!r)
				continue;
			j=n;
			while(j!=1)
			{
				f[t[j]][j]+=r;
				f[j][t[j]]-=r;
				j=t[j];
			}
			flux+=r;
		}
	}
	printf("%d\n",flux);
	return 0;
}