Pagini recente » Cod sursa (job #2871621) | Cod sursa (job #2295218) | Cod sursa (job #2910670) | Cod sursa (job #2739392) | Cod sursa (job #2817377)
#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){
queue<int> q;
q.push(s);
vector<int> parent(n + 1);
parent[s] = -1;
while(!q.empty()){
int x = q.front();
q.pop();
if(x == n){
continue;
}
for(auto it: a[x]){
if(!parent[it] && cap[{x, it}] > 0){
parent[it] = x;
q.push(it);
}
}
}
return parent;
}
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;
bool found = 1;
while(found){
vector<int> bfs_tree = bfs(1, n, n);
found = 0;
for(auto it: a[n]){
if(!bfs_tree[it]){
continue;
}
found = 1;
int bottleneck = INT_MAX;
for(int i = it, prev = n; i != -1; prev = i, i = bfs_tree[i]){
bottleneck = min(bottleneck, cap[{i, prev}]);
}
if(!bottleneck){
continue;
}
for(int i = it, prev = n; i != -1; prev = i, i = bfs_tree[i]){
cap[{i, prev}] -= bottleneck;
cap[{prev, i}] += bottleneck;
}
max_flow += bottleneck;
}
}
out<<max_flow;
return 0;
}