Pagini recente » Cod sursa (job #2355056) | Istoria paginii utilizator/boss_de_boss | Cod sursa (job #240151) | Cod sursa (job #313845) | Cod sursa (job #1844540)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 1010, inf = 0x3f3f3f3f;
int N, M;
struct FlowEdge {
int x, y, c, f;
FlowEdge *rev;
FlowEdge(int x, int y, int c, int f, FlowEdge *rev):
x(x),
y(y),
c(c),
f(f),
rev(rev) {
}
};
vector<FlowEdge *> FN[NMAX];
FlowEdge *from[NMAX];
void addEdge(int x, int y, int c) {
FlowEdge *dir = new FlowEdge(x, y, c, 0, 0);
FlowEdge *rev = new FlowEdge(y, x, 0, 0, 0);
dir->rev = rev;
rev->rev = dir;
FN[x].push_back(dir);
FN[y].push_back(rev);
}
bool BFS(int S, int D) {
memset(from, 0, sizeof from);
queue<int> Q;
Q.push(S);
from[S] = (FlowEdge *)-1;
while (!Q.empty()) {
int now = Q.front();
Q.pop();
for (const auto &it: FN[now]) {
if (from[it->y] || it->f >= it->c)
continue;
from[it->y] = it;
Q.push(it->y);
}
}
return from[D] != 0;
}
int EdmondsKarp(int S, int D) {
int flow = 0;
while (BFS(S, D)) {
for (int it = 0; it < int(FN[D].size()); ++it) {
if (from[FN[D][it]->y] == 0)
continue;
int augument = inf;
FlowEdge *temp = FN[D][it]->rev;
while (from[temp->x] != (FlowEdge *)-1) {
augument = min(augument, temp->c - temp->f);
temp = from[temp->x];
}
augument = min(augument, temp->c - temp->f);
temp = FN[D][it]->rev;
while (from[temp->x] != (FlowEdge *)-1) {
temp->f += augument;
temp->rev->f -= augument;
temp = from[temp->x];
}
temp->f += augument;
temp->rev->f -= augument;
flow += augument;
}
}
return flow;
}
int main() {
assert(freopen("maxflow.in", "r", stdin));
assert(freopen("maxflow.out", "w", stdout));
int i;
int x, y, c;
cin >> N >> M;
for (i = 1; i <= M; ++i) {
cin >> x >> y >> c;
addEdge(x, y, c);
}
cout << EdmondsKarp(1, N) << '\n';
return 0;
}