Cod sursa(job #2413575)

Utilizator LucaSeriSeritan Luca LucaSeri Data 23 aprilie 2019 15:41:26
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
 
using namespace std;

#define all(x) (x).begin(), (x).end()

const int MAXN = 1010;

vector< int > gr[MAXN];
int cap[MAXN][MAXN];
int lvl[MAXN];

inline void add(int a, int b, int c) {
	gr[a].emplace_back(b);
	gr[b].emplace_back(a);
	cap[a][b] += c;
}

bool bfs(int start, int target) {
	queue< int > q;
	lvl[start] = lvl[target] + MAXN;

	q.push(start);
	while(q.size()) {
		int node = q.front();
		q.pop();
		if(node == target) return true;
		for(auto &x : gr[node]) {
			if(lvl[x] < lvl[start] && cap[node][x] > 0) {
				lvl[x] = lvl[node] + 1;
				q.push(x);
			}
		}
	}

	return false;
}

int dfs(int node, int target, int flow) {
	if(node == target) return flow;
	if(!flow) return 0;

	int ret = 0;
	for(auto &x : gr[node]) {
		if(lvl[x] == lvl[node] + 1 && cap[node][x] > 0) {
			int pa = dfs(x, target, min(flow, cap[node][x]));
			cap[node][x] -= pa;
			cap[x][node] += pa;
			ret += pa;
			flow -= pa;
		} 
	}

	return ret;
}

int main() {
	#ifdef BLAT
		freopen("input", "r", stdin);
	#else
		freopen("maxflow.in", "r", stdin);
		freopen("maxflow.out", "w", stdout);
	#endif
 
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	srand(time(nullptr));

	int n, m;
	cin >> n >> m;

	for(int i = 1; i <= m; ++i) {
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}

	int ans = 0;
	while(bfs(1, n)) ans += dfs(1, n, 1e9);

	cout << ans << '\n';
	return 0;
}