Cod sursa(job #2811426)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 2 decembrie 2021 11:30:32
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

using namespace std;

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

const int INF = 1e9;

int n, m, ans;
vector<int> parent;
vector<vector<int>> edges, capacity, flow;

bool bfs(int s) {
	parent = vector<int>(n + 1, -1);
	vector<bool> visited(n, 0);
	queue<int> q;
	q.push(s);
	visited[s] = 1;

	while(!q.empty()) {
		int node = q.front();
		q.pop();

		for(auto it: edges[node]) {
			if(!visited[it] && flow[node][it] != capacity[node][it ]) {
				q.push(it);
				visited[it] = 1;
				parent[it] = node;
			}
		}
	}

	return visited[n];
}

int main() {
	fin >> n >> m;

	edges = vector<vector<int>>(n + 1);
	capacity = vector<vector<int>>(n + 1, vector<int>(n + 1, 0));
	flow = vector<vector<int>>(n + 1, vector<int>(n + 1, 0));

	for(int i = 0; i < m; i++) {
		int x, y, c;
		fin >> x >> y >> c;

		capacity[x][y] = c;
		edges[x].push_back(y);
		edges[y].push_back(x);
	}

	while(bfs(1)) {
		for(auto it: edges[n]) {
			parent[n] = it;
			int maxflow = INF;

			for(int p = n; 1; p = parent[p]) {
				if(p == -1 || parent[p] == -1) {
					break;
				}
				maxflow = min(maxflow, capacity[parent[p]][p] - flow[parent[p]][p]);
			}

			if(maxflow == 0) {
				continue;
			}

			for(int p = n; 1; p = parent[p]) {
				if(p == -1 || parent[p] == -1) {
					break;
				}
				flow[p][parent[p]] -= maxflow;
				flow[parent[p]][p] += maxflow;
			}

			ans += maxflow;
		}
	}

	fout << ans << '\n';

	return 0;
}