Cod sursa(job #409752)

Utilizator alexandru92alexandru alexandru92 Data 3 martie 2010 20:51:00
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <queue>
#include <vector>
#include <fstream>
#define Nmax 1000
#define INF 0x3f3f3f3f

/*
 *
 */
using namespace std;
int N, source, sink;
int C[Nmax][Nmax], Cost[Nmax][Nmax];
vector< vector< int > > G;
vector< int >::const_iterator it, iend;
int find_path( void )
{
	int x;
	queue< int > Q;
	vector< bool > inQ( N );
	vector< int > d( N, INF ), c( N ), father( N, -1 );
	d[source]=0;
	c[source]=INF;
	Q.push( source );
	inQ[source]=true;
	while( !Q.empty() )
	{
		x=Q.front(); Q.pop();
		inQ[x]=false;
		for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
			if( C[x][*it] > 0 && d[x]+Cost[x][*it] < d[*it] )
			{
				father[*it]=x;
				d[*it]=d[x]+Cost[x][*it];
				c[*it]=min( c[x], C[x][*it] );
				if( !inQ[*it] )
				{
					Q.push( *it );
					inQ[*it]=true;
				}
			}
	}
	if( -1 == father[sink] )
		return INF;
	father[source]=-1;
	for( x=sink; -1 != father[x]; x=father[x] )
	{
		C[father[x]][x]-=c[sink];
		if( 0 == C[x][father[x]] )
		{
			G[x].push_back( father[x] );
			Cost[x][father[x]]=-Cost[father[x]][x];
		}
		C[x][father[x]]+=c[sink];
	}
	return c[sink]*d[sink];
}
int MaxFlowMinCut( void )
{
	int path_c, s=0;
	for( path_c=find_path(); INF != path_c; s+=path_c, path_c=find_path() );
	return s;
}
int main( void )
{
	int M, x, y;
	ifstream in( "fmcm.in" );
	in>>N>>M>>source>>sink;
	--source, --sink;
	G.resize(N);
	for( ; M; --M )
	{
		in>>x>>y;
		--x, --y;
		in>>C[x][y]>>Cost[x][y];
		G[x].push_back(y);
	}
	ofstream out( "fmcm.out" );
	out<<MaxFlowMinCut();
	return 0;
}