Cod sursa(job #2403924)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 12 aprilie 2019 07:34:30
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <bits/stdc++.h>
using namespace std;

struct Dinic {
	struct Edge {
		int to, flow, next;
		Edge(int a, int b, int c) : to(a), flow(b), next(c) { }
	};
	vector <Edge> edges;
	vector <int> adia, at, h;
	int S, D;

	void add_edge(int from, int to, int flow) {
		edges.push_back(Edge({ to, flow, (int)edges.size() }));
		swap(edges.back().next, adia[from]);
		edges.push_back(Edge({ from, 0, int(edges.size()) }));
		swap(edges.back().next, adia[to]);
	}

	bool bfs() {
		fill(h.begin(), h.end(), -1);
		h[S] = 1;
		vector <int> q = { S };
		for (int it = 0; it < q.size(); it++) {
			int nod = q[it];
			if (nod == D)
				continue;
			for (int i = adia[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);
				}
			}
		}
		return (h[D] != -1);
	}

	int dfs(int nod, int cap) {
		if (nod == D || cap == 0)
			return cap;

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

	int MaxFlow() {
		int ans = 0;
		while (bfs()) {
			at = adia;
			int d;
			while ((d = dfs(S, 1e9)) != 0)
				ans += d;
		}
		return ans;
	}


	Dinic() { }
	Dinic(int n, int s, int d) : adia(n + 1, -1), h(n + 1), S(s), D(d) { }
};

int main()
{
	FILE* in = fopen("maxflow.in", "r");
	FILE* out = fopen("maxflow.out", "w");
	int n, m, a, b, c;

	fscanf(in, "%d%d", &n, &m);

	Dinic flow(n, 1, n);

	while (m--) {
		fscanf(in, "%d%d%d", &a, &b, &c);
		flow.add_edge(a, b, c);
	}

	fprintf(out, "%d\n", flow.MaxFlow());

	return 0;
}