Pagini recente » Cod sursa (job #35911) | Cod sursa (job #2445904) | Cod sursa (job #636245) | Cod sursa (job #2837259) | Cod sursa (job #2811447)
#include <bits/stdc++.h>
#include <vector>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n, m, x, y, z;
int s, t;
int r[1005][1005];
int lvl[1005];
vector <int> g[1005];
queue <int> q;
bool bfs() {
q.push(s);
lvl[s] = 0;
while(!q.empty()) {
int nod = q.front();
q.pop();
for(auto &fiu : g[nod]) {
if(r[nod][fiu] <= 0 || lvl[fiu] >= 0)
continue;
lvl[fiu] = lvl[nod] + 1;
q.push(fiu);
}
}
return lvl[t] >= 0;
}
int dfs(int nod, int add) {
if(!add)
return 0;
if(nod == t)
return add;
for(auto &fiu : g[nod]) {
if(r[nod][fiu] <= 0 || lvl[fiu] != 1 + lvl[nod])
continue;
int mx = dfs(fiu, min(r[nod][fiu], add));
if(mx) {
r[nod][fiu] -= mx;
r[fiu][nod] += mx;
return mx;
}
lvl[fiu] = 0;
}
return 0;
}
int main() {
in >> n >> m;
for(int i = 1; i <= m; i++) {
in >> x >> y >> z;
g[x].push_back(y);
g[y].push_back(x);
r[x][y] += z;
}
s = 1, t = n;
int flow = 0;
while(true) {
for(int i = 1; i <= n; i++)
lvl[i] = -1;
if(!bfs())
break;
int add = 0;
do {
add = dfs(s, (int)1e9);
flow += add;
} while(add);
}
out << flow;
return 0;
}