Cod sursa(job #1437434)

Utilizator nytr0gennytr0gen nytr0gen Data 17 mai 2015 18:44:17
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <queue>
#include <visited>

using namespace std;

const int INF = 1<<30;
const int NMAX = 1000 + 1;

vector<int> adjacent[NMAX];
int capacity[NMAX][NMAX]; // speram ca se initializeaza cu zero ^^

int findPath(const int source, const int sink) {
	queue<int> Q;
	bitset<NMAX> visited;

	Q.push(source);
	visited[source] = true;

	vector<int> from(NMAX, -1);

	int where;
	while (!Q.empty()) {
		where = Q.front(); Q.pop();
		for (int next: adjacent[where]) {
			if (!visited[next] && capacity[where][next] > 0) {
				Q.push(next);
				visited[next] = 1;
				from[next] = where;
				if (next == sink) {
					break;
				}
			}
		}
	}

	// we compute the path capacity
	int pathCap = INF;
	where = sink;
	while (from[where] != -1) {
		int prev = from[where]; // the prev vertex
		pathCap = min(pathCap, capacity[prev][where]);
		where = prev;
	}

	// we update the residual network; if no path is found the while
	// loop will not be entered
	where = sink;
	while (from[where] > -1) {
		int prev = from[where];
		capacity[prev][where] -= pathCap;
		capacity[where][prev] += pathCap;
		where = prev;
	}

	// if no path is found, path_cap is infinity
	if (pathCap == INF) {
		return 0;
	} else {
		return pathCap;
	}
}

int maxFlow(const int source, const int sink) {
	int result = 0, pathCap;
	do {
		pathCap = findPath(source, sink);
		if (pathCap != 0) {
			result += pathCap;
		}
	} while (pathCap != 0);

	return result;
}

int main() {
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);

	int N, M; scanf("%d %d", &N, &M);
	for (int i = 0; i < M; i++) {
		int x, y, c;
		scanf("%d %d %d\n", &x, &y, &c);
		adjacent[x].push_back(y);
		adjacent[y].push_back(x);
		capacity[x][y] = c;
	}

	printf("%d", maxFlow(1, N));

	return 0;
}