Cod sursa(job #2290993)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 27 noiembrie 2018 11:52:23
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
using namespace std;

namespace Dinic {
	struct Edge {
		int flow, to, next;
	};
	vector <Edge> edges;
	vector <int> adia, at, dist;
	int S, D;

	void add_Edge(int from, int to, int cap) {
		edges.push_back({ cap, to, adia[from] });
		adia[from] = edges.size() - 1;
		edges.push_back({ 0, from, adia[to] });
		adia[to] = edges.size() - 1;
	}

	bool bfs() {
		queue <int> q;
		fill(dist.begin(), dist.end(), 1e9);
		dist[S] = 0;
		q.push(S);
		while (!q.empty()) {
			int x = q.front();
			q.pop();

			for (int i = adia[x]; i != -1; i = edges[i].next) {
				if (dist[edges[i].to] > dist[x] + 1 && edges[i].flow) {
					dist[edges[i].to] = 1 + dist[x];
					q.push(edges[i].to);
				}
			}
		}
		return dist[D] < 1e9;
	}
	int dfs(int nod, int fmax) {
		if (nod == D)
			return fmax;
		while (at[nod] != -1) {
			Edge & e = edges[at[nod]];
			int f;
			if (dist[e.to] == dist[nod] + 1 && e.flow && (f = dfs(e.to, min(fmax, e.flow)))) {
				e.flow -= f;
				edges[at[nod] ^ 1].flow += f;
				return f;
			}
			at[nod] = edges[at[nod]].next;
		}
		return 0;
	}

	int Dinic() {
		int f = 0;
		while (bfs()) {
			at = adia;
			while (int x = dfs(S, 1e9))
				f += x;
		}
		return f;
	}
	void init(int n, int s, int d) {
		S = s, D = d;
		at = dist = adia = vector <int>(n + 1, -1);
	}
}

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

	int n, m, a, b, c;
	in >> n >> m;
	
	Dinic::init(n, 1, n);

	while (m--) {
		in >> a >> b >> c;
		Dinic::add_Edge(a, b, c);
	}

	out << Dinic::Dinic() << '\n';

	return 0;
}