Cod sursa(job #498661)

Utilizator PlayLikeNeverB4George Marcus PlayLikeNeverB4 Data 5 noiembrie 2010 18:25:07
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <stdio.h>

const int maxn=1001,INF=1100001;
struct nod {
	int inf;
	nod *next;
} *A[maxn];
int i,N,M,from[maxn],C[maxn][maxn];


void citire()
{
	int x,y,z;
	scanf("%d %d",&N,&M);
	for(i=1;i<=M;i++)
	{
		scanf("%d %d %d",&x,&y,&z);
		nod *q=new nod;
		q->inf=y;
		q->next=A[x];
		C[x][y]+=z;
		A[x]=q;
		q=new nod;
		q->inf=x;
		q->next=A[y];
		C[y][x]=0;
		A[y]=q;
	}
}

int bfs()
{
	int v[maxn],cd[maxn],ps,pi,k;
	for(i=1;i<=N;i++) { v[i]=0; cd[i]=0; from[i]=0;}
	cd[1]=1; v[1]=1; ps=1; pi=1;
	while(true)
	{
		k=cd[ps];
		for(nod *x=A[k];x;x=x->next)
			if(v[x->inf]==0 && C[k][x->inf]>0)
			{
				cd[++pi]=x->inf;
				v[x->inf]=1;
				from[x->inf]=k; // from[x] = nodul din care se ajunge la x
				if(x->inf==N) return 1;
			}
		ps++;
		if(ps>pi) return 0;
	}
}

int path()
{
	int p,k=N,min=INF; 
	do
	{
		p=k; k=from[k];
		if(C[k][p]<min) min=C[k][p];
	}
	while(k!=1);
	return min;
}

void update(int x)
{
	int k=N;
	do
	{
		C[k][from[k]]+=x;
		C[from[k]][k]-=x;
		k=from[k];
	}
	while(k!=1);
}

int maxflow()
{
	int drum,R=0;
    while(bfs()) //pana cand exista drum de la 1 la N
	{
		do
		{
		drum=path(); //aflu cu cat pot mari fluxul
		update(drum); //fac update in graful rezidual
		R+=drum; //adaug la rezultat
		}
		while(drum>0);
	}
	return R;
}

int main()
{
	freopen("maxflow.in","r",stdin);
	freopen("maxflow.out","w",stdout);
	citire();
	printf("%d",maxflow());
}