Cod sursa(job #405084)

Utilizator alexandru92alexandru alexandru92 Data 27 februarie 2010 14:59:33
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <queue>
#include <vector>
#include <fstream>


/*
 *
 */
using namespace std;
int N;
int C[1024][1024];
vector< vector< int > > G;
int find_path( void ) // min_c if there is a agumenting path, -1 else
{
	int n, x, i, j, min_c;
	queue< int > Q;
	vector< int > father( N+1, -1 );
	Q.push( 0 );
	father[0]=-2;
	while( -1 == father[N] && !Q.empty() ) //try to find a agumenting path
	{
		x=Q.front(); Q.pop();
		for( j=0, n=G[x].size(); j < n; ++j )
		{
			i=G[x][j];
			if( -1 == father[i] )
			{
				if( C[x][i] > 0 )
				{
					Q.push( i );
					father[i]=x;
				}
			}
			
		}
	}
	if( -1 == father[N] ) //if there wasn't any path
		return -1;
	//if there is a agumenting path
	min_c=C[ father[N] ][ N ]; 
	father[0]=-2;
	for( i=father[N]; -2 != father[i]; i=father[i] ) //find the min C from the path
		min_c=min( min_c, C[ father[i] ][ i ] ); 
	for( i=N; -2 != father[i]; i=father[i] ) //update
	{
		C[ father[i] ][ i ]-=min_c;
		C[ i ][ father[i] ]+=min_c;
		G[i].push_back( father[i] );
	}
	return min_c;
}
int Maximum_Flow( void )
{
	int path_c, s=0;
	for( path_c=find_path(); -1 != path_c; s+=path_c, path_c=find_path() );
	return s;
}
int main( void )
{
	int M, x, y;
	ifstream in( "maxflow.in" );
	in>>N>>M;
	G.resize( N );
	N-=1;
	for( ; M; --M )
		in>>x>>y, in>>C[x-1][y-1], G[x-1].push_back( y-1 );
	ofstream out( "maxflow.out" );
	out<<Maximum_Flow();
	return 0;
}