Cod sursa(job #241779)

Utilizator AndreyPAndrei Poenaru AndreyP Data 10 ianuarie 2009 23:53:18
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 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;
inline int min(int x,int y)
{
	if(x<y)
		return x;
	return y;
}
void citire()
{
	scanf("%d%d",&n,&m);
	int x,y,z;
	for(; m; m--)
	{
		scanf("%d%d%d",&x,&y,&z);
		if((cvec[x]&7)==0)
			a[x]=(int*)realloc(a[x],(cvec[x]+10)*sizeof(int));
		if((cvec[y]&7)==0)
			a[y]=(int*)realloc(a[y],(cvec[y]+10)*sizeof(int));
		a[x][++cvec[x]]=y;
		a[y][++cvec[y]]=x;
		c[x][y]=z;
	}
}
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;
}