Cod sursa(job #3039428)

Utilizator DordeDorde Matei Dorde Data 28 martie 2023 15:59:21
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int const inf = 1e9 , N = 351;
int n , m , s , d , x , y , l , r;
int q[12501] , t[N] , viz[N] , dp[N];
int f[N][N] , w[N][N];
int update(){
    int flow = inf , cost = 0;
    x = d;
    while(t[x]){
        flow = (flow < f[t[x]][x] ? flow : f[t[x]][x]);
        x = t[x];
    }
    if(!flow)
        return 0;
    x = d;
    while(t[x]){
        f[t[x]][x] -= flow;
        f[x][t[x]] += flow;
        cost += flow * w[t[x]][x];
        x = t[x];
    }
    return cost;
}
bool bellman(){
    for(int i = 1 ; i <= n ; ++ i)
        t[i] = 0 , dp[i] = inf;
    q[l = r = 1] = s;
    dp[s] = 0;
    while(l <= r){
        x = q[l++];
        for(y = 1 ; y <= n ; ++ y){
            if(f[x][y] > 0 && w[x][y] + dp[x] < dp[y]){
                dp[y] = dp[x] + w[x][y];
                t[y] = x;
                q[++r] = y;
            }
        }
    }
    return t[d];
}
int fmcm(){
    int cost(0);
    while(bellman()){
        cost += update();
    }
    return cost;
}
int main(){
    fin >> n >> m >> s >> d;
    for(int i = 1 ; i <= m ; ++ i){
        fin >> x >> y >> f[x][y] >> w[x][y];
        w[y][x] = -w[x][y];
    }
    fout << fmcm() << '\n';
    return 0;
}