Cod sursa(job #2117219)

Utilizator LucaSeriSeritan Luca LucaSeri Data 28 ianuarie 2018 18:05:05
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.86 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 355;
const int INF = (1<<30);

int capacity[MAXN][MAXN];
int current_flow[MAXN][MAXN];
int dist[MAXN];
int viz[MAXN];

vector< pair<int, int> > gr[MAXN];
int boss[MAXN];

ifstream f("fmcm.in");
ofstream g("fmcm.out");

bool bf(int source, int target, int n){
    memset(dist, 0x3f, sizeof dist);
    memset(viz, 0, sizeof viz);
    dist[source] = 0;

    queue< int > Q;

    Q.push(source);
    viz[source] = true;
    while(Q.size()){
        int node = Q.front();
        viz[node] = false;
        Q.pop();
        for(auto x : gr[node]){
            if(current_flow[node][x.first] >= capacity[node][x.first]) continue;
            if(dist[node] + x.second >= dist[x.first]) continue;

            dist[x.first] = dist[node] + x.second;
            boss[x.first] = node;
            if(viz[x.first]) continue;

            viz[x.first] = true;
            Q.push(x.first);
        }
    }

    return dist[target] != 0x3f3f3f3f;

}
int main(){
    int n, m, source, target;
    f >> n >> m >> source >> target;

    while(m--){
        int a, b, c, d;
        f >> a >> b >> c >> d;
        gr[a].push_back({b, d});
        capacity[a][b] += c;
    }

    int ans = 0;
    while(bf(source, target, n)){
        int node = target;
        int minimum_flow = INF;

        while(node != source){
            minimum_flow = min(minimum_flow, capacity[ 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 += (dist[target] * minimum_flow);
    }

    g << ans;
    return 0;
}