Pagini recente » Cod sursa (job #891329) | Cod sursa (job #2982428) | Cod sursa (job #1817779) | Cod sursa (job #2982441) | Cod sursa (job #2817330)
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> a;
map<pair<int,int>, int> cap;
vector<int> bfs(int s, int t, int n, int c){
queue<int> q;
q.push(s);
vector<int> parent(n + 1);
parent[s] = -1;
while(!q.empty()){
int x = q.front();
q.pop();
for(auto it: a[x]){
if(!parent[it] && cap[{x, it}] >= c){
parent[it] = x;
q.push(it);
}
}
}
if(!parent[t]){
return vector<int>{};
}
vector<int> path;
int node = t;
while(node != -1){
path.push_back(node);
node = parent[node];
}
reverse(path.begin(), path.end());
return path;
}
int main(){
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n, m;
in>>n>>m;
a.resize(n + 1);
for(int i = 0; i < m; i++){
int x, y, c;
in>>x>>y>>c;
a[x].push_back(y);
a[y].push_back(x);
cap[{x, y}] = c;
}
int max_flow = 0;
int delta = (1 << 30);
while(delta){
while(true){
vector<int> path = bfs(1, n, n, delta);
if(path.empty()){
break;
}
int bottleneck = INT_MAX;
for(int i = 1; i < path.size(); ++i){
bottleneck = min(bottleneck, cap[{path[i-1], path[i]}]);
}
for(int i = 1; i < path.size(); ++i){
cap[{path[i-1], path[i]}] -= bottleneck;
cap[{path[i], path[i-1]}] += bottleneck;
}
max_flow += bottleneck;
}
delta >>= 1;
}
out<<max_flow;
return 0;
}