Cod sursa(job #1263775)

Utilizator DuxarFII-Stefan-Negrus Duxar Data 15 noiembrie 2014 08:26:54
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <vector>
#include <fstream>
#include <cstdio>
#include <queue>
#include <climits>

#define pb push_back

using namespace std;

int N, M, maxflow;
vector <vector <int> > graph, mat;
vector <int> prec;

bool breadth_first_search();

int main() {
#ifdef INFOARENA
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);
#else
	freopen("input", "r", stdin);
#endif

	int i, minflow, from, to, c;

	scanf("%d %d", &N, &M);

	graph.resize(N + 1);
	prec.resize(N + 1);
	mat.resize(N + 1, vector <int> (N + 1));

	for (i = 0; i < M; ++i) {
		scanf("%d %d %d", &from, &to, &c);
		graph[from].pb(to);
		graph[to].pb(from);
		mat[from][to] = c;
	}

	while (breadth_first_search()) {
		for (auto from: graph[N]) {
			if (prec[from] && mat[from][N] > 0) {
				minflow = INT_MAX;
				prec[N] = from;
				from = N;
				while (prec[from] != 0) {
					minflow = min(minflow, mat[prec[from]][from]);
					from = prec[from];
				}
				from = N;
				while (prec[from] != 0) {
					mat[prec[from]][from] -= minflow;
					mat[from][prec[from]] += minflow;
					from = prec[from];
				}
				maxflow += minflow;
			}
		}
	}

	printf("%d\n", maxflow);

	return 0;
}

bool breadth_first_search() {
	int from;
	queue <int> que;
	que.push(1);
	fill(prec.begin(), prec.end(), 0);
	while (!que.empty()) {
		from = que.front();
		que.pop();
		if (from == N) {
			return true;
		}
		for (auto to: graph[from]) {
			if (to != 1 && prec[to] == 0 && mat[from][to] > 0) {
				prec[to] = from;
				que.push(to);
			}
		}
	}
	return false;
}