Cod sursa(job #2395557)

Utilizator giotoPopescu Ioan gioto Data 2 aprilie 2019 17:56:06
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include <bits/stdc++.h>
using namespace std;

int n, m, S, D;
int Fc;
bool inq[355];
int d[355], C[355][355], Cost[355][355], reald[355], old[355], TT[355];
bool f[355];
vector <int> v[355];
priority_queue <pair <int, int> > pq;
queue <int> q;
inline void bellman(){
    for(int i = 1; i <= n ; ++i)
        old[i] = 2000000000;
    q.push(S);
    old[S] = 0;
    while(!q.empty()){
        int nod = q.front();
        q.pop();
        f[nod] = 0;
        for(auto it : v[nod]){
            if(!C[nod][it]) continue ;
            if(old[it] > old[nod] + Cost[nod][it]){
                old[it] = old[nod] + Cost[nod][it];
                if(f[it] == 0)  f[it] = 1, q.push(it);
            }
        }
    }
}
inline bool dijkstra(){
    memset(inq, 0, sizeof(inq));
    for(int i = 1; i <= n ; ++i)
        d[i] = 2000000000;
    inq[S] = 1;
    d[S] = 0; reald[S] = 0;
    pq.push({0, S});

    while(!pq.empty()){
        int nod = pq.top().second;
        inq[nod] = 0;
        pq.pop();
        for(auto it : v[nod]){
            if(!C[nod][it]) continue ;
            if(d[it] > d[nod] + Cost[nod][it] + old[nod] - old[it]){
                d[it] = d[nod] + Cost[nod][it] + old[nod] - old[it];
                reald[it] = reald[nod] + Cost[nod][it];
                if(!inq[it]){
                    pq.push({-d[it], it});
                    inq[it] = 1;
                }
                TT[it] = nod;
            }
        }
    }

    memcpy(old, reald, sizeof(old));
    if(d[D] == 2000000000) return false;

    int Minf = 2000000000, cst = 0;
    for(int w = D; w != S ; w = TT[w]){
        Minf = min(Minf, C[TT[w]][w]);
        cst += Cost[TT[w]][w];
    }

    Fc += Minf * reald[D];

    for(int w = D; w != S ; w = TT[w]){
        C[TT[w]][w] -= Minf;
        C[w][TT[w]] += Minf;
    }
    return true;
}
int main()
{
    freopen("fmcm.in", "r", stdin);
    freopen("fmcm.out", "w", stdout);

    scanf("%d%d%d%d", &n, &m, &S, &D);
    int x, y, c, z;
    for(int i = 1; i <= m ; ++i){
        scanf("%d%d%d%d", &x, &y, &c, &z);
        v[x].push_back(y);
        v[y].push_back(x);
        C[x][y] = c;
        Cost[x][y] = z;
        Cost[y][x] = -z;
    }

    bellman();
    while(dijkstra()) ;
    printf("%d", Fc);
    return 0;
}