Cod sursa(job #1410463)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 31 martie 2015 02:42:59
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.57 kb
#include<cstdio>
#include<vector>
#include<deque>
#include<queue>
#include<bitset>

using namespace std;

typedef pair<int, int> PII;
const int INF = (1 << 30);
const int NMAX = 355;

int N, M, Source, Destination, Sol;
vector<int> V[NMAX];
int Capacity[NMAX][NMAX];
int Cost[NMAX][NMAX];
int Flow[NMAX][NMAX];

deque<int> Q;
bitset<NMAX> viz;
int DistBF[NMAX];
int DistDJ[NMAX];
int Dist[NMAX];
int T[NMAX];
priority_queue<PII, vector<PII>, greater<PII> > PQ;

int i, x, y, c, z, d;
vector<int>::iterator it;

void BellmanFord() {
    for(i = 1; i <= N; i++)
        DistBF[i] = INF;

    Q.push_back(Source);
    viz[Source] = 1;
    DistBF[Source] = 0;

    while(!Q.empty()) {
        x = Q.front();
        Q.pop_front();
        viz[x] = 0;

        for(it = V[x].begin(); it != V[x].end(); it++)
            if(DistBF[x] + Cost[x][*it] < DistBF[*it] && Flow[x][*it] < Capacity[x][*it]) {
                DistBF[*it] = DistBF[x] + Cost[x][*it];
                if(!viz[*it]) Q.push_back(*it), viz[*it] = 1;
            }
    }
}

int Dijkstra() {
    for(i = 1; i <= N; i++)
        DistDJ[i] = INF;

    PQ.push(make_pair(0, Source));
    T[Source] = Source;
    DistDJ[Source] = 0;

    while(!PQ.empty()) {
        d = PQ.top().first;
        x = PQ.top().second;
        PQ.pop();

        if(d > DistDJ[x]) continue;

        for(it = V[x].begin(); it != V[x].end(); it++)
            if(Flow[x][*it] < Capacity[x][*it]) {
                c = Cost[x][*it] + DistBF[x] - DistBF[*it];

                if(DistDJ[x] + c < DistDJ[*it]) {
                    DistDJ[*it] = DistDJ[x] + c;
                    Dist[*it] = Dist[x] + Cost[x][*it];
                    T[*it] = x;
                    PQ.push(make_pair(DistDJ[*it], *it));
                }
            }
    }

    for(i = 1; i <= N; i++)
        DistBF[i] = Dist[i];

    return DistDJ[Destination] != INF;
}

int main() {
    int x, y, c, z, v;

    freopen("fmcm.in", "r", stdin);
    freopen("fmcm.out", "w", stdout);

    scanf("%d%d%d%d", &N, &M, &Source, &Destination);

    for(; M; --M) {
        scanf("%d%d%d%d", &x, &y, &c, &z);
        Capacity[x][y] = c;
        Cost[x][y] = z;
        Cost[y][x] = -z;
        V[x].push_back(y);
        V[y].push_back(x);
    }

    BellmanFord();

    while(Dijkstra()) {
        v = INF;

        for(x = Destination; x != T[x]; x = T[x])
            v = min(v, Capacity[T[x]][x] - Flow[T[x]][x]);

        for(x = Destination; x != T[x]; x = T[x]) {
            Flow[T[x]][x] += v;
            Flow[x][T[x]] -= v;
        }

        Sol += v * DistBF[Destination];
    }

    printf("%d\n", Sol);
    return 0;
}