Cod sursa(job #1952267)

Utilizator bullseYeIacob Sergiu bullseYe Data 4 aprilie 2017 00:17:07
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#define NMAX 1010
#define MMAX 5010
#define INF 1000000000

using namespace std;

FILE *fin = freopen("maxflow.in", "r", stdin);
FILE *fout = freopen("maxflow.out", "w", stdout);

vector <int> L[NMAX];
queue <int> coada;
int n, m, capacity[NMAX][NMAX], parent[NMAX], maxFlow;
bool viz[NMAX];

void afisare();
void solve();
bool BFS();
void citire();

int main() {
	citire();
	solve();
	afisare();
}

void citire() {
	int i, a, b, c;

	//FILE *fin = fopen("maxflow.in", "r");

	scanf("%d %d\n", &n, &m);
	//for (i = 1; i <= n; ++i)
		//L[i].reserve(NMAX);

	for (i = 1; i <= m; ++i) {
		scanf("%d %d %d\n", &a, &b, &c);
		L[a].push_back(b);
		L[b].push_back(a);
		capacity[a][b] += c;
	}
}

void solve() {
	int flow, pathNode;

	while (BFS()) {//cat timp mai gasesc un drum de ameliorare
		for (int adiacentNode : L[n]) {
			if (!viz[adiacentNode] || !capacity[adiacentNode][n])
				continue;
			
			flow = INF;
			for (pathNode = n; pathNode != 1; pathNode = parent[pathNode])
				flow = min(flow, capacity[parent[pathNode]][pathNode]);

			maxFlow += flow;

			for (pathNode = n; pathNode != 1; pathNode = parent[pathNode]) {
				capacity[parent[pathNode]][pathNode] -= flow;
				capacity[pathNode][parent[pathNode]] += flow;
			}
		}
	}
}

bool BFS() {
	int currentNode;

	memset(viz, 0, sizeof(viz));
	//for (int i = 2; i <= n; ++i) viz[i] = false;
	while (!coada.empty()) coada.pop();

	viz[1] = true; coada.push(1);
	while (!coada.empty()) {
		currentNode = coada.front(); coada.pop();
		if (currentNode == n)
			return true;

		for (int adiacentNode : L[currentNode])
			if (!viz[adiacentNode] && capacity[currentNode][adiacentNode]) {
				viz[adiacentNode] = true;
				coada.push(adiacentNode);
				parent[adiacentNode] = currentNode;
			}
	}

	return false;
}

void afisare() {
	//FILE *fout = fopen("maxflow.out", "w");
	printf("%d\n", maxFlow);
}