Cod sursa(job #1394503)

Utilizator vladrochianVlad Rochian vladrochian Data 20 martie 2015 12:57:23
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

const int kMaxN = 1005;
const int kInf = 0x3f3f3f3f;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int N, M, cap[kMaxN][kMaxN], padre[kMaxN], maxflow;
vector<int> G[kMaxN];
bool use[kMaxN];

bool BFS() {
	memset(use, 0, sizeof use);
	queue<int> q;
	q.push(1);
	use[1] = true;
	while (!q.empty()) {
		int node = q.front();
		q.pop();
		if (node != N)
			for (int i : G[node])
				if (!use[i] && cap[node][i]) {
					padre[i] = node;
					q.push(i);
					use[i] = true;
				}
	}
	return use[N];
}

int main() {
	fin >> N >> M;
	while (M--) {
		int x, y, c;
		fin >> x >> y >> c;
		G[x].push_back(y);
		G[y].push_back(x);
		cap[x][y] = c;
	}
	while (BFS()) {
		for (int node : G[N])
			if (use[node] && cap[node][N]) {
				padre[N] = node;
				int flow = kInf;
				for (int i = N; i != 1; i = padre[i])
					flow = min(flow, cap[padre[i]][i]);
				for (int i = N; i != 1; i = padre[i]) {
					cap[padre[i]][i] -= flow;
					cap[i][padre[i]] += flow;
				}
				maxflow += flow;
			}
	}
	fout << maxflow << "\n";
	return 0;
}