Cod sursa(job #764692)

Utilizator Stefex09Stefan Teodorescu Stefex09 Data 5 iulie 2012 22:54:39
Problema Flux maxim de cost minim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

ifstream in ("fmcm.in");
ofstream out ("fmcm.out");

const int MAXN = 360;
const int INF = 1 << 30;

vector < pair < int, int > > graf[MAXN];

int c[MAXN][MAXN], f[MAXN][MAXN], dist[MAXN], t[MAXN];
bool viz[MAXN];
int N, M, S, D;

inline void getmin (int &a, int b)
{
	if (a > b)
		a = b;
}

inline bool BF ()
{
	queue <int> Q;
	vector < pair < int, int > > :: iterator it;
	int nod, i;
	
	/*for (i = 1; i <= N; ++i){
		dist[i] = INF;
		viz[i] = 0;
		t[i] = 0;
	}*/
	memset (dist, INF, sizeof (dist));
	memset (viz, 0, sizeof (viz));
	memset (t, 0, sizeof (t));
	
	dist[S] = 0;
	Q.push (S);
	
	while (!Q.empty ()){
		nod = Q.front ();
		Q.pop ();
		viz[nod] = 0;
		
		for (it = graf[nod].begin (); it != graf[nod].end (); ++it)
			if (dist[nod] + (it -> second) < dist[it -> first] && c[nod][it -> first] != f[nod][it -> first]){
				dist[it -> first] = dist[nod] + (it -> second);
				t[it -> first] = nod;
				
				if (!viz[it -> first]){
					viz[it -> first] = 1;
					Q.push (it -> first);
				}
			}
	}
	
	return (dist[D] != INF);
}

int flux ()
{
	int fm, sol = 0, i;
	
	for ( ; BF (); sol += fm * dist[D]){
		fm = INF;
		
		for (i = D; i != S; i = t[i])
			getmin (fm, c[ t[i] ][i] - f[ t[i] ][i]);
		
		for (i = D; i != S; i = t[i]){
			f[ t[i] ][i] += fm;
			f[i][ t[i] ] -= fm;
		}
	}
	
	return sol;
}

int main ()
{
	int x, y, cap, cost;
	
	in >> N >> M >> S >> D;
	
	while (M--){
		in >> x >> y >> cap >> cost;
		
		c[x][y] = cap;
		graf[x].push_back (make_pair (y, +cost));
		graf[y].push_back (make_pair (x, -cost));
	}
	
	out << flux ();
	
	return 0;
}