Cod sursa(job #945521)

Utilizator tudorv96Tudor Varan tudorv96 Data 2 mai 2013 10:55:31
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;

#define in "maxflow.in"
#define out "maxflow.out"
#define N 1005
#define f(x,y) C[x][y]
#define oo 1 << 30

queue <int> Q;
int C[N][N], sol;
short n, m, S, D;
vector <short> grad (N, 0), gradT (N, 0);
vector <short> tata (N, 0);

void BFS (int s) { //Complexitate O (n^2)
	Q.push (s);
	while (Q.size() && !tata[D]) {
		int x = Q.front();
		Q.pop();
		for (int i = 1; i <= n; ++i)
			if (i != s && !tata[i] && f (x, i) > 0) {
				Q.push (i);
				tata[i] = x;
			}
	}
	while (!Q.empty())
		Q.pop();
}

int main () {
	ifstream fin (in);
	fin >> n >> m;
	for (int i = 0; i < m; ++i) {
		int x, y, c;
		fin >> x >> y >> c;
		f (x, y) = c;
		grad[x]++;
		gradT[y]++;
	}
	fin.close();
	//Gasirea sursei si destinatiei
	for (int i = 1; i <= n && (!S || !D); ++i) {
		if (!D && !grad[i])
			D = i;
		else
			if (!S && !gradT[i])
				S = i;
	}
	do {
		for (int i = 1; i <= n; ++i)
			tata[i] = 0;
		BFS (S);
		if (!tata[D]) //Nu exista arce nesaturate
			break;
		short x = D; 
		int MIN = oo;
		while (tata[x]) { //Determinarea fluxului maxim din lantul de ameliorare 
			MIN = min (MIN, f(tata[x], x));
			x = tata[x];
		}
		sol += MIN;
		x = D;
		while (tata[x]) { //Ameliorarea fluxului pe acest drum
			f(tata[x], x) -= MIN;
			x = tata[x];
		}
	} while (1);
	ofstream fout (out);
	fout << sol;
	fout.close();
	return 0;
}