Cod sursa(job #2745138)

Utilizator YouDontNeedMyNameJurcut Paul YouDontNeedMyName Data 25 aprilie 2021 22:10:54
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#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];
vector<int> lista[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(auto i: lista[u]){
        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(auto i: lista[s]){
        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(auto j: lista[elem]){
                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;
        if(!capacity[x][y] && !capacity[y][x]){
            lista[x].push_back(y);
            lista[y].push_back(x);
        }
        in >> capacity[x][y];
    }
    out << max_flow(1,n) << '\n';
    return 0;
}