Pagini recente » Cod sursa (job #244948) | Cod sursa (job #365058) | Cod sursa (job #3225366)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
const int N = 1e3+5;
const int oo = 0x3f3f3f3f;
int n, dist[N], nxt[N], cap[N][N];
vector<int> e[N];
void read();
int flow(), bfs(), dfs(int,int);
int main()
{
read();
fout << flow();
return 0;
}
void read(){
int m; fin >> n >> m;
while (m--){
int a, b, c; fin >> a >> b >> c;
e[a].pb(b); e[b].pb(a);
cap[a][b] = c;
}
}
int flow(){
int ans = 0;
while (true){
int k = bfs();
if (!k) break;
ans += k;
}
return ans;
}
int bfs(){
memset(dist, oo, sizeof dist);
memset(nxt, 0, sizeof nxt);
queue<int> q;
q.push(1); dist[1] = 0;
while (!q.empty()){
int from = q.front(); q.pop();
for (auto to: e[from])
if (cap[from][to] && dist[to] > dist[from] + 1){
dist[to] = dist[from] + 1;
q.push(to);
}
}
int ans = 0;
while (true){
int k = dfs(1, oo);
if (!k) break;
ans += k;
}
return ans;
}
int dfs(int from, int mx) {
if (from == n || !mx) return mx;
while (nxt[from] < (int)e[from].size()){
int to = e[from][nxt[from]];
if (cap[from][to] && dist[to] == dist[from] + 1){
int k = dfs(to, min(mx, cap[from][to]));
if (k){
cap[from][to] -= k;
cap[to][from] += k;
return k;
}
else nxt[from]++;
}
else nxt[from]++;
}
return 0;
}