Pagini recente » Cod sursa (job #1150892) | Cod sursa (job #1998336) | Monitorul de evaluare | Cod sursa (job #2200982) | Cod sursa (job #3353392)
#include <bits/stdc++.h>
using namespace std;
const int inf = 1e9;
struct Dinic {
struct Edge {
int from, to, cap, prev;
};
vector<Edge> edges;
vector<int> dist, last, clast;
int n;
Dinic (int _n) {
n = _n + 1;
clast.resize(n, -1);
}
void baga(int from, int to, int cap) {
edges.push_back({from, to, cap, clast[from]});
clast[from] = edges.size() - 1;
edges.push_back({to, from, 0, clast[to]});
clast[to] = edges.size() - 1;
}
bool bfs(int s, int d) {
last = clast;
dist.assign(n, inf);
queue<int> q;
q.push(s);
dist[s] = 0;
while (!q.empty()) {
auto 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) {
dist[edges[i].to] = 1 + dist[edges[i].from];
q.push(edges[i].to);
}
}
}
return dist[d] != inf;
}
int dfs(int nod, int d, int push) {
if (nod == d || !push) {
return push;
}
int ans = 0;
for (int i = last[nod]; i != -1; i = edges[i].prev) {
last[nod] = i;
if (dist[edges[i].from] + 1 == dist[edges[i].to]) {
int x = dfs(edges[i].to, d, min(push, edges[i].cap));
ans += x;
push -= x;
edges[i].cap -= x;
edges[i ^ 1].cap += x;
}
if (!push) {
break;
}
}
return ans;
}
int flux(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.flux(1, n) << '\n';
}