Cod sursa(job #442577)

Utilizator mottyMatei-Dan Epure motty Data 14 aprilie 2010 20:27:06
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <cstdio>
#include <vector>
#include<cstring>
using namespace std;

const int N=1024,INF=1000000000;

int n, m, flow, kc[N][N], fx[N][N], sz[N], q[N*N*5], t[N];

bool viz[N];

vector <int> mc[N];

void read()
{
	int x,y,z;
	scanf("%d%d",&n,&m);
	while( m-- )// nr. de muchii este nefolositor pt. restul programului
	{
		scanf("%d%d%d",&x,&y,&z);
		kc[x][y]=z;
		mc[x].push_back(y);
		mc[y].push_back(x);//muchie de intoarcere din y in x (are capacitatea 0)
		++sz[x];
		++sz[y];
	}
}

bool bfs()
{
	int d,u;
	
	int nod,next;
	
	memset(viz,0,sizeof(viz));
	
	q[1]=1,d=1,u=1,viz[1]=true;
	
	while( d<=u )
	{
		nod=q[d];
		
		++d;
		
		for( int i=0 ; i<sz[nod] ; ++i )
		{
			next=mc[nod][i];
			
			if( !viz[next] && kc[nod][next] - fx[nod][next] > 0 )
			{
				viz[next]=1;
				q[++u]=next;
				t[next]=nod;
				
				if( next==n )
					return 1;
			}
		
		}
	}
	
	return 0;
}

int calcMin()
{
	int mini=INF;
	for( int i=n ; i!=1 ; i=t[i] )
		if( kc[t[i]][i]-fx[t[i]][i] < mini )
			mini=kc[t[i]][i]-fx[t[i]][i];
	return mini;
}

void maxFlow()
{
	int fm;
	while( bfs() )//cat timp mai exista drumuri de la sursa la destinatie
	{
		fm=calcMin();
		
		flow+=fm;
		
		for( int i=n ; i!=1 ; i=t[i] )
		{
//			printf("%d ",i);
			fx[ t[i] ][i]+=fm;
			fx[i][ t[i] ]-=fm;
		}
		
//		printf("\n");
	}
}

int main()
{
	freopen("maxflow.in","r",stdin);
	freopen("maxflow.out","w",stdout);
	
	read();
	
	maxFlow();
	
	printf("%d\n",flow);
	
	return 0;
}