Pagini recente » Cod sursa (job #2418899) | Cod sursa (job #960356) | Cod sursa (job #2506658) | Cod sursa (job #3138593) | Cod sursa (job #3042065)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
struct edge {
int from, to, cap;
};
vector <int> g[N];
vector <edge> e;
int n, m, s, t;
int lvl[N];
void add_edge(int u, int v, int w) {
g[u].push_back(e.size());
e.push_back({u, v, w});
g[v].push_back(e.size());
e.push_back({v, u, 0});
}
bool bfs() {
fill(lvl, lvl + n + 1, 0);
queue <int> q;
q.push(s);
lvl[s] = 1;
while(!q.empty()) {
int u = q.front();
q.pop();
for(int id : g[u]) {
int v = e[id].to;
if(!lvl[v] && e[id].cap) {
q.push(v);
lvl[v] = lvl[u] + 1;
}
}
}
return lvl[t];
}
int rem[N];
int dfs(int u, int flow) {
if(!flow || u == t) return flow;
for(int& cid = rem[u]; cid < g[u].size(); cid++) {
int id = g[u][cid];
int v = e[id].to;
if(lvl[v] != lvl[u] + 1 || !e[id].cap) continue;
int f = dfs(v, min(flow, e[id].cap));
if(!f) continue;
e[id].cap -= f;
e[id ^ 1].cap += f;
return f;
}
return 0;
}
int main()
{
#ifndef HOME
ifstream cin("maxflow.in");
ofstream cout("maxflow.out");
#endif
ios_base :: sync_with_stdio(false); cin.tie(0); cout.tie(0);
cin >> n >> m;
s = 1; t = n;
for(int i = 0, u, v, w; i < m; i++)
cin >> u >> v >> w,
add_edge(u, v, w);
long long flow = 0;
while(bfs()) {
fill(rem, rem + n + 1, 0);
while(int f = dfs(s, 1e9))
flow += f;
}
cout << flow;
return 0;
}