Cod sursa(job #1886549)

Utilizator DobosDobos Paul Dobos Data 20 februarie 2017 22:49:23
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <bits/stdc++.h>
#define NMAX 360
#define INF 1e9
#define f first
#define s second
using namespace std;

ifstream fin("fmcm.in");
ofstream fout("fmcm.out");

vector < pair < int , int > > G[NMAX];

int F[NMAX][NMAX],C[NMAX],D[NMAX],ant[NMAX],RD[NMAX];
bool B[NMAX];



void bellmanford(const int &n,const int &S){
    for(int i = 1; i <= n; i++)
        D[i] = INF;

    D[S] = 0;
    int nod;
    B[S] = 1;
    deque < int > Q;
    Q.push_back(S);

    while(!Q.empty()){
        nod = Q.front();
        Q.pop_front();
        B[nod] = 0;
        for(auto const &it : G[nod]){
            if(!F[nod][it.f] || D[it.f] <= D[nod] + it.s) continue;

            D[it.f] = D[nod] + it.s;
            if(!B[it.f]){
                Q.push_back(it.f);
                B[it.f] = 1;
            }
        }
    }
}

bool Dijkstra(const int &S,const int &De,const int &n){

    priority_queue < pair < int , int >, vector < pair < int , int > >,greater < pair < int , int > > > PQ;

    for(int i = 1; i <= n; i++)
        C[i] = RD[i] = INF;

    C[S] = RD[S] = 0;

    PQ.push({0,S});

    while(!PQ.empty()){
        int cost = PQ.top().f,nod = PQ.top().second;
        PQ.pop();

        if(cost != C[nod]) continue;

        for(auto const &it : G[nod]){
            int aux = C[nod] + it.s + D[nod] - D[it.f];
            if(!F[nod][it.f] || C[it.f] <= aux) continue;

            C[it.f] = aux;
            RD[it.f] = RD[nod] + it.s;
            ant[it.f] = nod;

            PQ.push({aux,it.f});

        }
    }

    for(int i = 1; i <= n; i++)
        D[i] = RD[i];

    return RD[De] != INF;


}


int main()
{
    ios :: sync_with_stdio(false);

    int n,m,x,y,c,f,S,De;

    fin >> n >> m >> S >> De;

    for(int i = 1; i <= m; i++){

        fin >> x >> y >> c >> f;
        G[x].push_back({y,f});
        G[y].push_back({x,-f});

        F[x][y] = c;

    }

    bellmanford(n,S);
    int sol = 0,flow;

    while(Dijkstra(S,De,n)){

        flow = INF;

        for(int i = De; i != S; i = ant[i])
            flow = min(flow,F[ant[i]][i]);

        if(flow == 0) continue;

        for(int i = De; i != S; i = ant[i]){

            F[ant[i]][i] -= flow;
            F[i][ant[i]] += flow;

        }
        sol += flow * RD[De];

    }

    fout << sol;

    return 0;
}