Cod sursa(job #945538)

Utilizator tudorv96Tudor Varan tudorv96 Data 2 mai 2013 11:16:44
Problema Flux maxim Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <iostream>
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

typedef unsigned u;

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

void BFS (int s) {
	Q.push (s);
	while (Q.size() && !tata[D]) {
		int x = Q.front();
		Q.pop();
		for (u i = 0; i < graf[x].size(); ++i)
			if (graf[x][i] != s && !tata[graf[x][i]] && f (x, graf[x][i]) > 0) {
				Q.push (graf[x][i]);
				tata[graf[x][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;
		graf[x].push_back (y);
	}
	fin.close();
	S = 1;
	D = n;
	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;
}