Cod sursa(job #2811451)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 2 decembrie 2021 11:58:23
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 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<bool> visited;
vector<int> parent;
vector<vector<int>> edges, capacity, flow;

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

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

		if(node == n) {
			return 1;
		}

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

	return visited[n];
}

//parent[30] = 23
//parent[23] = 30

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 = 1; 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;

			if(flow[parent[n]][n] == capacity[parent[n]][n] || !visited[parent[n]]) {
				continue;
			}

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

			if(maxflow == 0) {
				continue;
			}

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

			ans += maxflow;
		}
	}

	fout << ans << '\n';

	return 0;
}