Cod sursa(job #680010)

Utilizator balakraz94abcd efgh balakraz94 Data 13 februarie 2012 23:20:26
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.26 kb
#include<cstdio>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#define infile "fmcm.in"
#define outfile "fmcm.out"
#define n_max 355
#define INF 1<<30
#define nxt *it
#define pb push_back
#define mkp make_pair
#define FOR(g) \
   for(vector<int> ::iterator it = g.begin(); it!=g.end(); ++it)
using namespace std;


vector < int > v[n_max];

int Cost[n_max][n_max], C[n_max][n_max], F[n_max][n_max], Dist[n_max], T[n_max];

int N, M, Src, Sink;

int Drum, Sum;



void citeste()
{
	freopen(infile,"r",stdin);
	
	scanf("%d %d %d %d", &N, &M, &Src, &Sink);
	
	int x, y, c, cost;
	
	while(M--)
	{
		scanf("%d %d %d %d", &x, &y, &c, &cost);
		
		v[x].pb(y);
		v[y].pb(x);
		
		Cost[x][y] = cost;
		Cost[y][x] = -cost;
		C[x][y] = c;
		
	}
	
	fclose(stdin);
}



void BellmanFord()
{	
	for(int i=1;i<=N;++i)
		Dist[i] = INF;
	Dist[Src] = 0;
	
	int stop = 1;

	for(int i=1;i<=N && stop; ++i)
	{
		stop = 0;
		
		for(int nod=1; nod<=N; ++nod)
			FOR(v[nod])
				if(C[nod][nxt] > F[nod][nxt] && Dist[nod] + Cost[nod][nxt] < Dist[nxt]) 
				{
					stop = 1;
				
					Dist[nxt] = Dist[nod] + Cost[nod][nxt];
				}
	}

	Sum = Dist[Sink];
}




inline int Dijkstra()
{
	for(int i=1; i<=N; i++)
		FOR(v[i])
			if(Dist[i]!=INF && Dist[nxt]!=INF)
				Cost[i][nxt] += Dist[i] - Dist[nxt];

	priority_queue < pair <int, int> > H;		

	for(int i=1;i<=N;i++)
	{
		Dist[i] = INF;
		T[i] = 0;
	}		
	Dist[Src] = 0;
	
	H.push(mkp(-0,Src));
	
	while(!H.empty())
	{
		int nod = H.top().second;
		H.pop();
		
		FOR(v[nod])
			if(C[nod][nxt] - F[nod][nxt] > 0 && Dist[nod] + Cost[nod][nxt] < Dist[nxt])
			{
				Dist[nxt] = Dist[nod] + Cost[nod][nxt];
				H.push(mkp(-Dist[nxt], nxt));
				T[nxt] = nod;
			}
	}
	
	if(Dist[Sink] == INF)
		return 0 ;
	
	Drum = 1;
	int fmin = INF;
	
	for(int i = Sink; i != Src; i = T[i])
		fmin = min(fmin, C[T[i]][i] - F[T[i]][i]);
	
	for(int i = Sink; i != Src; i = T[i])
	{
		F[T[i]][i] += fmin;
		F[i][T[i]] -= fmin;
	}
	
	Sum += Dist[Sink];
	
	return Sum * fmin;
}



long long Flux()
{
	long long sol = 0;
	Drum = 1;
	
	while(Drum)
	{
		Drum = 0;
		sol += Dijkstra();
	}
	
	return sol;
}



void afiseaza()
{
	freopen(outfile,"w",stdout);
	
	printf("%lld\n",Flux());
	
	fclose(stdout);
}


int main()
{
	citeste();
	
	BellmanFord();
	
	afiseaza();
	
	return 0;
}