Cod sursa(job #410817)

Utilizator alexandru92alexandru alexandru92 Data 4 martie 2010 16:44:03
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.72 kb
#include <queue>
#include <vector>
#include <fstream>
#define Nmax 351
#define INF 2000000000

/*
 *
 */
using namespace std;
int N, source, sink, S, NH;
int C[Nmax][Nmax], Cost[Nmax][Nmax];
int H[Nmax], P[Nmax], D[Nmax], F[Nmax];
vector< vector< int > > G;
vector< int >::const_iterator it, iend;
void DownHeap( int k )
{
	int son;
	for( ; ; )
	{
		son=2*k;
		if( son > NH )
			return;
		if( son < NH && D[H[son]] > D[H[son+1]] )
			++son;
		if( D[H[k]] <= D[H[son]] )
			return;
		swap( H[k], H[son] );
		swap( P[H[k]], P[H[son]] );
		k=son;
	}
}
void UpHeap( int k )
{
	int key=D[H[k]], f=k/2;
	while( k > 1  && key < D[H[f]] )
	{
		swap( P[H[k]], P[H[f]] );
		swap( H[k], H[f] );
		k=f;
		f=k/2;
	}
}
void BellmanFord( void )
{
	int x;
	queue< int > Q;
	vector< bool > inQ( N );
	for( x=0; x < N; ++x )
		D[x]=INF;
	D[source]=0;
	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] )
			{
				D[*it]=D[x]+Cost[x][*it];
				if( !inQ[*it] )
				{
					Q.push( *it );
					inQ[*it]=true;
				}
			}
	}
	S=D[sink];
}
int find_path( void )
{
	int x, min_c;
	for( x=0; x < N; ++x )
		if( INF != D[x] )
			for(  it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
				if( INF != D[*it]   )
					Cost[x][*it]+=D[x]-D[*it];
	for( NH=x=0; x < N; ++x )
	{
		D[x]=INF;
		F[x]=-1;
		H[x+1]=x;
		P[x]=x+1;
	}
	NH=N;
	D[source]=0;
	UpHeap( P[source] );
	while( NH )
	{
		x=H[1];
		if( INF == D[x] )
			break;
		H[1]=H[NH];
		P[H[1]]=1;
		--NH;
		DownHeap( 1 );
		for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
			if( C[x][*it] > 0 && D[x]+Cost[x][*it] < D[*it] )
			{
				F[*it]=x;
				D[*it]=D[x]+Cost[x][*it];
				UpHeap( P[*it] );
			}
	}
	if( INF == D[sink] )
		return INF;
	min_c=C[ F[sink] ][ sink ];
	for( x=F[sink]; source != x; x=F[x] )
		min_c=min( min_c, C[ F[x] ][ x ] );
	for( x=sink; source != x; x=F[x] )
	{
		C[ F[x] ][ x ]-=min_c;
		if( 0 == C[x][F[x]] && 0 == Cost[x][F[x]] )
		{
			G[x].push_back( F[x] );
			Cost[x][F[x]]=-Cost[F[x]][x];
		}
		C[ x ][ F[x] ]+=min_c;
	}
	S+=D[sink];
	return S*min_c;
}
long long int MaxFlowMinCut( void )
{
	BellmanFord();
	int path_c;
	long long int 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;
}