Cod sursa(job #2101913)

Utilizator LucaSeriSeritan Luca LucaSeri Data 8 ianuarie 2018 11:17:56
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1001;

vector < int > gr[MAXN];
int maximum_flow[MAXN][MAXN];
int current_flow[MAXN][MAXN];
int boss[MAXN];

bool can_push(int source, int target){
    memset(boss, 0, sizeof boss);
    boss[source] = source;
    queue< int > Q;
    Q.push(source);
    while(Q.size()){
        int node = Q.front();
        Q.pop();
        if(node == target) continue;
        for(auto x : gr[node]){
            if(boss[x] == 0 && current_flow[node][x] < maximum_flow[node][x]){
                boss[x] = node;
                Q.push(x);
            }
        }
    }

    return boss[target] != 0;
}

void update_flow(int source, int target, int &ans){
    for(auto x : gr[target]){
        if(boss[x] == 0) continue;
        if(current_flow[x][target] == maximum_flow[x][target]) continue;
        boss[target] = x;
        int node = target;
        int minimum_flow = 1<<30;
        while(node != source){
            minimum_flow = min(minimum_flow, maximum_flow[boss[node]][node] - current_flow[boss[node]][node]);
            node = boss[node];
        }
        node = target;
        while(node != source){
            current_flow[boss[node]][node] += minimum_flow;
            current_flow[node][boss[node]] -= minimum_flow;
            node = boss[node];
        }

        ans += minimum_flow;
    }
}
int main(){
    ifstream f("maxflow.in");
    ofstream g("maxflow.out");
    int ans = 0;
    int n, m;
    f >> n >> m;
    for(int i = 1; i <= m; ++i){
        int a, b, c;
        f >> a >> b >> c;
        gr[a].push_back(b);
        gr[b].push_back(a);
        maximum_flow[a][b] += c;
    }

    while(can_push(1, n)) update_flow(1, n, ans);

    g << ans;
    return 0;
}