Cod sursa(job #2626478)

Utilizator RaduVFVintila Radu-Florian RaduVF Data 6 iunie 2020 17:22:36
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>

#define N 1003
 
using namespace std;
 
int n, m, C[N][N];
vector<int> G[N], pi(N);
queue<int> Q;
 
int BFS() {
	Q.push(1);
	while (!Q.empty()) {
		int u = Q.front();
		Q.pop();
		for (int x : G[u])
			if (!pi[x] && C[u][x] > 0) {
				pi[x] = u;
				Q.push(x);
			}
	}
	return pi[n];
}
 
int main() {
	ifstream fin("maxflow.in");
	ofstream fout("maxflow.out");

	int x, y, c;
	fin >> n >> m;
	for (int i = 1; i <= m; ++i) {
		fin >> x >> y >> c;
		C[x][y] = c;
		G[x].push_back(y);
		G[y].push_back(x);
	}

	int flow = 0, w;
	while (BFS()) {
		for (int x : G[n]) {
			w = C[x][n];
			for (int i = x; i != 1; i = pi[i]) {
				w = min(w, C[pi[i]][i]);
			}
			for (int i = x; i != 1; i = pi[i]) {
				C[pi[i]][i] -= w;
				C[i][pi[i]] += w;
			}
			flow += w;
			C[x][n] -= w;
			C[n][x] += w;
		}
		pi.assign(N, 0);
	}
	fout << flow;
	return 0;
}