Pagini recente » Cod sursa (job #1715333) | Cod sursa (job #1560904) | Cod sursa (job #1340716) | Cod sursa (job #10504) | Cod sursa (job #1920927)
#include <bits/stdc++.h>
using namespace std;
const int nmax = 1e3 + 10;
const int inf = 0x3f3f3f3f;
int n, m, S, D, flow;
int dad[nmax], f[nmax][nmax], c[nmax][nmax];
vector < int > g[nmax];
void add_edge(int x, int y, int cap) {
g[x].push_back(y);
g[y].push_back(x);
c[x][y] = cap; c[y][x] = 0;
f[x][y] = f[y][x] = 0;
}
void input() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; ++i) {
int x, y, z;
scanf("%d %d %d", &x, &y, &z);
add_edge(x, y, z);
}
}
bool bfs() {
bool ok = 0;
for (int i = 1; i <= n; ++i) dad[i] = -1;
queue < int > q; q.push(S); dad[S] = 0;
while (q.size()) {
int node = q.front(); q.pop();
for (auto &it: g[node]) {
if (f[node][it] >= c[node][it]) continue;
if (dad[it] != -1) continue;
if (it == D) ok = 1;
else dad[it] = node, q.push(it);
}
}
return ok;
}
void maxflow() {
S = 1; D = n;
while (bfs()) {
for (auto &it: g[D]) {
if (!dad[it]) continue;
dad[D] = it; int best = inf;
for (int node = D; node != S; node = dad[node])
best = min(best, c[dad[node]][node] - f[dad[node]][node]);
if (best == 0) continue;
flow += best;
for (int node = D; node != S; node = dad[node])
f[dad[node]][node] += best,
f[node][dad[node]] -= best;
}
}
}
void output() {
printf("%d\n", flow);
}
int main() {
freopen("maxflow.in","r",stdin);
freopen("maxflow.out","w",stdout);
input();
maxflow();
output();
return 0;
}