Cod sursa(job #2295743)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 3 decembrie 2018 22:14:48
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
using namespace std;

struct Edge {
	int to, flow, next;
};

vector <Edge> edges;
vector <int> adia, dist, head;
int s, d;

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

bool bfs()
{
	fill(dist.begin(), dist.end(), 0);
	dist[s] = 1;
	vector <int> q = { s };
	for (int i = 0; i < q.size(); i++) {
		int nod = q[i];
		for (int id = adia[nod]; id != -1; id = edges[id].next) {
			if (!dist[edges[id].to] && edges[id].flow) {
				dist[edges[id].to] = 1 + dist[nod];
				q.push_back(edges[id].to);
			}
		}
	}
	return dist[d] != 0;
}

int dfs(int nod, int fmax)
{
	int ans = 0, f;
	if (nod == d)
		return fmax;
	while (head[nod] != -1) {
		Edge & e = edges[head[nod]];
		if (e.flow && dist[e.to] == 1 + dist[nod] && (f = dfs(e.to, min(fmax, e.flow)) > 0)) {
			ans += f, fmax -= f;
			e.flow -= f;
			edges[head[nod] ^ 1].flow += f;
			head[nod] = e.next;
			return f;
		}
		head[nod] = e.next;
	}
	return ans;
}

int Dinic()
{
	int f = 0;
	while (bfs()) {
		head = adia;
		f += dfs(s, 1e9);
	}
	return f;
}

int main()
{
	int n, m, a, b, c;
	ifstream in("maxflow.in");
	in >> n >> m;
	s = 1, d = n;
	adia = vector <int>(n + 1, -1);
	dist = vector <int>(n + 1);
	while (m--) {
		in >> a >> b >> c;
		add_edge(a, b, c);
	}

	ofstream out("maxflow.out");
	out << Dinic() << '\n';

	return 0;
}