Cod sursa(job #2817330)

Utilizator EdgeLordXDOvidiuPita EdgeLordXD Data 13 decembrie 2021 15:33:26
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#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;
}