Cod sursa(job #2626482)

Utilizator RaduVFVintila Radu-Florian RaduVF Data 6 iunie 2020 17:31:33
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#define N 1003
 
using namespace std;
 
int n, m, C[N][N], flow;
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, w;
	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);
	}
	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;
}