Pagini recente » Cod sursa (job #134698) | Cod sursa (job #1563995) | Cod sursa (job #1709079) | Cod sursa (job #3227787) | Cod sursa (job #2784196)
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3;
const int MAXM = 5e3;
struct Edge {
int next;
int capacity;
int flow;
int rev;
Edge(int _next, int _capacity, int _flow, int _rev) {
next = _next;
capacity = _capacity;
flow = _flow;
rev = _rev;
}
};
int n, m;
vector< Edge > g[MAXN + 2];
int depth[MAXN + 2];
bool bfs() {
queue<int> q;
memset(depth, 0, sizeof(depth));
bool reachedSink = false;
q.push(1);
int cur;
while (q.size()) {
cur = q.front();
q.pop();
for (auto &x : g[cur]) {
if (x.next == n) {
depth[n] = depth[cur] + 1;
reachedSink = true;
}
else if (depth[x.next] == 0 && x.next != 1 && x.capacity - x.flow > 0) {
depth[x.next] = depth[cur] + 1;
q.push(x.next);
}
}
}
return reachedSink;
}
int dfs(int cur, int flow) {
if (cur == n)
return flow;
for (auto &x : g[cur]) {
if (depth[x.next] == depth[cur] + 1 && x.capacity - x.flow > 0) {
int tmpFlow = dfs(x.next, min(flow, x.capacity - x.flow));
if (tmpFlow) {
x.flow += tmpFlow;
g[x.next][x.rev].flow -= tmpFlow;
return tmpFlow;
}
}
}
depth[cur] = -1;
return 0;
}
int main() {
// #ifdef LOCAL
// freopen("date.in", "r", stdin);
// freopen("date.out", "w", stdout);
// #else
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
// #endif
cin >> n >> m;
for (int i = 0; i < m; ++ i) {
int x, y, z;
cin >> x >> y >> z;
g[x].push_back(Edge(y, z, 0, g[y].size()));
g[y].push_back(Edge(x, 0, 0, g[x].size() - 1));
}
int maxFlow = 0;
while (bfs()) {
int tmpFlow = 0;
do {
tmpFlow = dfs(1, 2e9);
maxFlow += tmpFlow;
} while (tmpFlow > 0);
}
cout << maxFlow << '\n';
return 0;
}