Cod sursa(job #1619870)

Utilizator emanuel_rRamneantu Emanuel emanuel_r Data 28 februarie 2016 19:40:17
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include<iostream>
#include<fstream>
#include<vector>
#include<cmath>
#include<queue>

using namespace std;

ifstream f("fmcm.in");
ofstream g("fmcm.out");

vector <pair <int, int> > G[355];
queue <int> Q;
long long C[355][355], F[355][355];
long long InQ[355], D[355], TT[355];
long long n, m, s, d, maxflow, totcost;
int const oo = 1000000000;

void citire()
{
    int x, y, c, z, i;

    f>>n>>m>>s>>d;
    for(i=1; i<=m; i++){
        f>>x>>y>>c>>z;
        G[x].push_back(make_pair(y, z));
        C[x][y] = c;
        G[y].push_back(make_pair(x, -z));
    }
}

bool Bellman()
{
    long long i, nod, vecin, cost;

    for(i=1; i<=n; i++){
        D[i] = oo;
        InQ[i] = 0;
    }

    D[s] = 0;
    Q.push(s);
    InQ[s] = 1;
    while(!Q.empty()){
        nod = Q.front();
        Q.pop();
        for(i=0; i<G[nod].size(); i++){
            vecin = G[nod][i].first;
            cost = G[nod][i].second;
            if( (D[nod] + cost < D[vecin]) && (C[nod][vecin] - F[nod][vecin] > 0) ){
                D[vecin] = D[nod] + cost;
                TT[vecin] = nod;
                if(!InQ[vecin]){
                    Q.push(vecin);
                    InQ[vecin] = 1;
                }
            }
        }
    }

    if(D[d] != oo)
        return 1;
    return 0;
}

void Flow()
{
    long long u, flow;

    while(Bellman()){
        u = d;
        flow = oo;
        while(u != s){
            flow = min(flow, C[TT[u]][u] - F[TT[u]][u]);
            u = TT[u];
        }

        maxflow += flow;
        totcost += flow * D[d];

        u = d;
        while(u != s){
            F[u][TT[u]] -= flow;
            F[TT[u]][u] += flow;
            u = TT[u];
        }
    }

    g<<totcost<<"\n";
}

int main()
{
    citire();
    Flow();
    return 0;
}