Pagini recente » Cod sursa (job #3322394) | Profil Vman | Cod sursa (job #3310377) | Autentificare | Cod sursa (job #3328425)
#include <bits/stdc++.h>
using namespace std;
const int INF = 1000000000;
struct Flow {
struct Edge {
int u, v, c;
};
int n;
vector<vector<int>> g;
vector<int> d;
vector<Edge> e;
void build(int _n) {
n = _n;
g.assign(n+1, vector<int>());
d.assign(n+1, 0);
}
void pushEdge(int u, int v, int c) {
g[u].push_back(e.size());
e.push_back({u, v, c});
g[v].push_back(e.size());
e.push_back({v, u, 0});
}
int dfs(int node, int t, int f) {
if(node == t || f == 0) {
return f;
}
int ans = 0;
for(auto son : g[node]) {
auto [u, v, c] = e[son];
if(d[v] == d[u] + 1) {
int val = dfs(v, t, min(f, c));
f -= val;
ans += val;
e[son].c -= val;
e[son^1].c += val;
}
}
return ans;
}
bool bfs(int s, int t) {
for(auto &i : d) {
i = -1;
}
queue<int> q;
q.push(s);
d[s] = 0;
while(!q.empty()) {
int node = q.front();
q.pop();
for(auto son : g[node]) {
auto [u, v, c] = e[son];
if(d[v] == -1 && c != 0) {
d[v] = d[u] + 1;
q.push(v);
}
}
}
return d[t] != -1;
}
int getMaxFlow(int s, int t) {
int ans = 0;
while(bfs(s, t)) {
ans += dfs(s, t, INF);
}
return ans;
}
};
int main() {
#ifndef LOCAL
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
#endif
ios::sync_with_stdio(false); cin.tie(0);
int n, m; cin>>n>>m;
Flow f;
f.build(n);
for(int i=1; i<=m; ++i) {
int a, b, c; cin>>a>>b>>c;
f.pushEdge(a, b, c);
}
cout<<f.getMaxFlow(1, n);
return 0;
}