Cod sursa(job #572662)

Utilizator avram_florinavram florin constantin avram_florin Data 5 aprilie 2011 15:22:07
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include<cstdio>
#include<vector>
#include<queue>

#define minim(a, b) ((a)<=(b)?(a):(b))
#define InFile "fmcm.in"
#define OutFile "fmcm.out"

using namespace std;

const int MaxN = 351;
const int INF = 0x3f3f3f3f;

int n,m,S,D;
short int C[MaxN][MaxN],F[MaxN][MaxN],d[MaxN],T[MaxN];
bool inQ[MaxN];
vector< pair<short int,short int> > G[MaxN];
queue<short int> Q;

int Bellman_Ford(int S , int D )
{
	memset(inQ,0,sizeof(inQ));
	memset(T,0,sizeof(T));
	memset(d,INF,sizeof(d));
	d[S] = 0;
	inQ[S] = true;
	Q.push(S);
	while( !Q.empty() )
		{
			int nod;
			vector< pair<short int,short int> >::iterator it,iend;
			nod = Q.front();
			Q.pop();
			inQ[nod] = false;
			if( nod == D )
				continue;
			it = G[nod].begin();
			iend = G[nod].end();
			for( ; it != iend ; ++it )
				if( C[nod][it->first] > F[nod][it->first] && d[it->first] > d[nod] + it->second )
					{
						d[it->first] = d[nod] + it->second;
						T[it->first] = nod;
						if( !inQ[it->first] )
							{
								Q.push(it->first);
								inQ[it->first] = true;
							}
					}
		}
	return T[D];
}

int Flux()
{
	int flux = 0;
	while( Bellman_Ford(S,D) )
		{
			int nod,fluxmin;
			fluxmin = INF;
			for( nod = D ; nod != S ; nod = T[nod] )
				fluxmin = minim(fluxmin , C[T[nod]][nod] - F[T[nod]][nod]);
			if( !fluxmin )
				continue;
			for( nod = D ; nod != S ; nod = T[nod] )
				{
					F[T[nod]][nod] += fluxmin;
					F[nod][T[nod]] -= fluxmin;
				}
			flux += (fluxmin*d[D]);
		}
	return flux;
}

void Read_BuildGraph()
{
	freopen( InFile , "r" , stdin );
	scanf("%d%d%d%d" , &n , &m , &S , &D);
	int i,x,y,c,z;
	for( i = 0 ; i < m ; i++ )
		{
			scanf("%d%d%d%d" , &x , &y , &c , &z );
			G[x].push_back(make_pair(y,z));
			G[y].push_back(make_pair(x,-z));
			C[x][y] = c;
		}
}

void write()
{
	freopen( OutFile , "w" , stdout );
	printf("%d\n" , Flux() );
}

int main()
{
	Read_BuildGraph();
	write();
	return 0;
}