Cod sursa(job #3137199)

Utilizator VladNANegoita Vlad-Andrei VladNA Data 11 iunie 2023 17:11:04
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>
#pragma GCC optimize("Ofast,unroll-loops")
#pragma GCC target("sse,avx,fma,avx2,bmi,bmi2,lzcnt,popcnt")

using namespace std;

class EdmondsKarp {

private:
	int n;
	static const int INF = 1e9;
	vector<vector<int>> adj_matrix;
	vector<vector<int>> adj_list;

	vector<int> pi; 
	bool bfs(int source, int sink) {
		vector<bool> visited (n, false);
		fill(pi.begin(), pi.end(), -1);
		queue<int> q; q.push(source), visited[source] = true;

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

			for (int v : adj_list[u])
				if (!visited[v] && adj_matrix[u][v] > 0)
					visited[v] = true, q.push(v), pi[v] = u;
		}

		return visited[sink];
	}

	int get_flow(int source, int node, int flow = INF) {
		if (node == -1)
			return 0;

		if (node == source)
			return flow;

		int curr_flow = get_flow(source, pi[node], min(flow, adj_matrix[pi[node]][node]));
		adj_matrix[pi[node]][node] -= curr_flow, adj_matrix[node][pi[node]] += curr_flow;
		return curr_flow;
	}

public:
	EdmondsKarp(int _n) {
		n = _n;
		adj_matrix = vector<vector<int>> (n, vector<int> (n, 0));
		adj_list.resize(n);
		pi.resize(n);
	}

	void insert_edge(int x, int y, int c) {
		adj_list[x].push_back(y);
		adj_list[y].push_back(x);
		adj_matrix[x][y] += c;
	}

	int get_max_flow(int source, int sink) {
		int max_flow = 0;
		while(bfs(source, sink))
			for (int neigh : adj_list[sink])
				max_flow += get_flow(source, neigh, INF);

		return max_flow;
	}
};

int main()
{
	freopen("maxflow.in", "r", stdin);
	freopen("maxflow.out", "w", stdout);

	int n, m;
	cin >> n >> m;

	EdmondsKarp solver(n);
	for (int edge = 0, x, y, c; edge < m; ++edge) {
		cin >> x >> y >> c;
		--x, --y;
		solver.insert_edge(x, y, c);
	}

	cout << solver.get_max_flow(0, n - 1) << endl;
	return 0;
}