Cod sursa(job #2923978)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 22 septembrie 2022 10:39:51
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>
using namespace std;

struct Dinic
{
	struct Edge {
		int to, flow, init, next;
	};
	int N, S, D;
	vector <Edge> edges;
	vector <int> head, at, h;

	void AddEdge(int from, int to, int capacity) {
		edges.push_back({ to, capacity, capacity, (int)edges.size() });
		swap(head[from], edges.back().next);
		edges.push_back({ from, 0, 0, (int)edges.size() });
		swap(head[to], edges.back().next);
	} 

	bool Bfs() {
		fill(h.begin(), h.end(), -1);
		h[S] = 0;
		vector <int> q = { S };
		for (int it = 0; it < (int)q.size(); it++) {
			int nod = q[it];
			for (int i = head[nod]; i != -1; i = edges[i].next) {
				if (edges[i].flow && h[edges[i].to] == -1) {
					h[edges[i].to] = 1 + h[nod], q.push_back(edges[i].to);
					if (edges[i].to == D)
						return true;
				}
			}
		}
		return false;
	}

	int Dfs(int nod, int flow_max) {
		if (nod == D || flow_max == 0)
			return flow_max;
		
		while (at[nod] != -1) {
			Edge& e = edges[at[nod]];
			if (h[e.to] == 1 + h[nod] && e.flow) {
				int added = Dfs(e.to, min(flow_max, e.flow));
				if (added) {
					e.flow -= added;
					edges[at[nod] ^ 1].flow += added;
					return added;
				}
				else
					at[nod] = edges[at[nod]].next;
			}
			else
				at[nod] = edges[at[nod]].next;
		}
		return 0;
	}

	Dinic(int N, int S, int D) : N(N), S(S), D(D), head(N, -1), h(N, -1) { }

	int ComputeFlow() {
		int ans = 0;
		while (Bfs()) {
			at = head;
			int x;
			while ((x = Dfs(S, 1e9))) {
				ans += x;
			}
		}
		return ans;
	}
};

int main()
{
	ifstream in("maxflow.in");
	ofstream out("maxflow.out");

	int n, m;
	in >> n >> m;

	Dinic dinic(n + 1, 1, n);

	while (m--) {
		int from, to, cap;
		in >> from >> to >> cap;
		dinic.AddEdge(from, to, cap);
	}

	out << dinic.ComputeFlow() << '\n';
}