Pagini recente » Cod sursa (job #2654609) | Cod sursa (job #3245567) | Cod sursa (job #3179694) | Cod sursa (job #2977796) | Cod sursa (job #2745128)
#include <bits/stdc++.h>
#define nmax 1005
#define inf 1000000009
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int n,m,capacity[nmax][nmax],flow[nmax][nmax],excess[nmax],height[nmax];
void push(int u, int v){
int d = min(excess[u], capacity[u][v] - flow[u][v]);
flow[u][v] += d;
flow[v][u] -= d;
excess[u] -= d;
excess[v] += d;
}
void relabel(int u){
int d = inf;
for(int i=0; i<=n; i++){
if(capacity[u][i] > flow[u][i]){
d = min(d, height[i]);
}
}
if(d<inf){
height[u] = d+1;
}
}
vector<int> max_heights(int s, int t){
vector<int> res;
for(int i=0; i<=n; i++){
if(i != s && i != t && excess[i] > 0){
if(!res.empty() && height[i] > height[res[0]])
res.clear();
if(res.empty() || height[i] == height[res[0]]){
res.push_back(i);
}
}
}
return res;
}
int max_flow(int s, int t){
memset(height, 0, sizeof(height));
memset(flow, 0, sizeof(flow));
memset(excess, 0, sizeof(excess));
height[s] = n;
excess[s] = inf;
for(int i=0; i<=n; i++){
if(i != s){
push(s, i);
}
}
for(auto cur = max_heights(s, t); !cur.empty(); cur=max_heights(s, t)){
for(auto elem: cur){
bool pushed = false;
for(int j=0; j<=n; j++){
if(capacity[elem][j] - flow[elem][j] > 0 && height[elem] == height[j] + 1){
push(elem, j);
pushed = true;
}
}
if(!pushed){
relabel(elem);
break;
}
}
}
return excess[t];
}
int main(){
in >> n >> m;
for(int i=1; i<=m; i++){
int x, y;
in >> x >> y;
in >> capacity[x][y];
}
out << max_flow(1,n) << '\n';
return 0;
}