Cod sursa(job #3349126)

Utilizator matei0000Neacsu Matei matei0000 Data 25 martie 2026 16:57:24
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

using namespace std;

const int inf = 1e9 + 5;

struct Dinic {
	struct Edge {
		int from, to, cap, prev;
	};
	int n;
	vector<Edge> edges;
	vector<int> last, dist, nlast;
	Dinic (int _n) { 
		n = _n + 1;
		last.assign(n, -1);
	}
	void baga(int from, int to, int cap) {
		edges.push_back({from, to, cap, last[from]});
		last[from] = edges.size() - 1;
		
		edges.push_back({to, from, 0, last[to]});
		last[to] = edges.size() - 1;
	}
	bool bfs(int s, int d) {
		nlast = last;
		queue<int> q;
		dist.assign(n, inf);
		dist[s] = 0;
		q.push(s);
		while (!q.empty()) {
			int x = q.front();
			q.pop();
			for (int i = last[x]; i != -1; i = edges[i].prev) {
				if (edges[i].cap == 0 || dist[edges[i].to] != inf) {
					continue;
				}
				dist[edges[i].to] = 1 + dist[x];
				q.push(edges[i].to);
			}
		}
		return dist[d] != inf;
	}
	int dfs(int nod, int d, int push) {
		if (push == 0 || nod == d) {
			return push;
		}
		int x = 0;
		for (int i = nlast[nod]; i != -1; i = edges[i].prev) {
			nlast[nod] = i;
			if (edges[i].cap > 0 && dist[edges[i].to] == 1 + dist[nod]) {
				int y = dfs(edges[i].to, d, min(push, edges[i].cap));
				
				edges[i].cap -= y;
				edges[i ^ 1].cap += y;
				
				push -= y;
				x += y;
			}
			if (push == 0) {
				break;
			}
		}
		return x;
	}
	int flow(int s, int d) {
		int ans = 0;
		while (bfs(s, d)) {
			ans += dfs(s, d, inf);
		}
		return ans;
	}
};

signed main() {
	ifstream cin("maxflow.in");
	ofstream cout("maxflow.out");
	int n, m;
	cin >> n >> m;
	Dinic g(n);
	for (int i = 0; i < m; i ++) {
		int u, v, w;
		cin >> u >> v >> w;
		g.baga(u, v, w);
	}
	cout << g.flow(1, n) << '\n';
}