Cod sursa(job #3039813)

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

#define pii pair<int,int>
#define fi first
#define se second

using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int const inf = 1e9 , N = 1001;
int n , m , s , d , l , r , a , b;
int q[N*N] , t[N] , dp[N] , dst[N] , inq[N] , dp2[N];
int f[N][N] , w[N][N];
vector<int> v[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;
}
void bellman(){
    fill(dst + 1 , dst + 1 + n , inf);
    fill(inq + 1 , inq + 1 + n , 0);
    dst[s] = 0;
    q[l = r = 1] = s;
    inq[s] = 1;
    while(l <= r){
        int x = q[l++];
        for(int y : v[x]){
            if(f[x][y] > 0 && dst[y] > dst[x] + w[x][y]){
                dst[y] = dst[x] + w[x][y];
                if(!inq[y]){
                    q[++r] = y;
                    inq[y] = 1;
                }
            }
        }
        inq[x] = 0;
    }
}
priority_queue<pii> h;
bool dijkstra(){
    fill(dp + 1 , dp + 1 + n , inf);
    fill(dp2 + 1 , dp2 + 1 + n , inf);
    dp[s] = dp2[s] = 0;
    h.emplace(0 , s);
    while(!h.empty()){
        int x = h.top().se;
        int wx = -h.top().fi;
        h.pop();
        if(wx != dp[x])
            continue;
        for(int y : v[x]){
            if(f[x][y] > 0 && dp[x] - dst[y] + w[x][y] + dst[x] < dp[y]){
                dp[y] = dp[x] - dst[y] + w[x][y] + dst[x];
                dp2[y] = dp2[x] + w[x][y];
                t[y] = x;
                h.emplace(-dp[y] , y);
            }
        }
    }
    copy(dp2 + 1 , dp2 + 1 + n , dst + 1);
    return dp[d] != inf;
}
int fmcm(){
    int cost(0);
    while(dijkstra()){
        cost += update();
    }
    return cost;
}
int main(){
    fin >> n >> m >> s >> d;
    for(int i = 1 ; i <= m ; ++ i){
        fin >> a >> b >> f[a][b] >> w[a][b];
        v[a].push_back(b);
        v[b].push_back(a);
        w[b][a] = -w[a][b];
    }
    bellman();
    fout << fmcm() << '\n';
    return 0;
}