Cod sursa(job #906080)

Utilizator dicu_dariaDaria Dicu dicu_daria Data 6 martie 2013 14:27:12
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <fstream>
#include <set>
#include <utility>
#include <queue>
#include <vector>
#define mp make_pair
#define N 360
#define M 13000
#define oo int(2e9)
using namespace std;

queue<int> Q;
bool inq[N];
vector<int> :: iterator it;
vector<int> G[N];
int real[N], prev[N], D[N], Mx[M], My[M], Mz[M], C[N][N], cost[N][N], Cost[N][N];
int flow, sol, i, n, m, x, y, z, c, Src, Dest;
set<pair<int, int> >S;

void Bellman()
{
    for(i = 1; i <= n; i++) D[i] = oo;
    D[Src] = 0;
    Q.push(Src);
    while(!Q.empty())
    {
        x = Q.front();
        Q.pop();
        inq[x] = 0;
        for(it = G[x].begin(); it != G[x].end(); ++it)
        if(D[*it] > D[x] + cost[x][*it] and C[x][*it])
        {
            D[*it] = D[x] + cost[x][*it];
            if(!inq[*it])
            {
                inq[*it] = 1;
                Q.push(*it);
            }
        }
    }
    for(i = 1; i<= m; i++)
    {
        x = Mx[i]; y = My[i]; z = Mz[i];
        Cost[x][y] = D[x] + z - D[y];
        Cost[y][x] = Cost[x][y];
    }
}

bool Dijkstra()
{
    for(i = 1; i <= n; i++) D[i] = oo;
    while(!S.empty()) S.erase(S.begin());
    D[Src] = 0;
    real[Src] = 0;
    S.insert(mp(0, Src));
    while(!S.empty())
    {
        x = S.begin()->second;
        S.erase(S.begin());
        for(it = G[x].begin(); it != G[x].end(); ++it)
            if(C[x][*it] and D[*it] > D[x] + Cost[x][*it])
            {
                D[*it] = D[x] + Cost[x][*it];
                real[*it] = real[x] + cost[x][*it];
                prev[*it] = x;
                S.insert(mp(D[*it], *it));
            }
    }
    return D[Dest] != oo;

}

int main()
{
    ifstream fi("fmcm.in");
    ofstream fo("fmcm.out");
    fi >> n >> m >> Src >> Dest;
    for(i = 1; i <= m; i++)
    {
        fi >> x >> y >> c >> z;
        C[x][y] = c;
        C[y][x] = 0;
        cost[x][y] = cost[y][x] = z;
        Mx[i] = x; My[i] = y; Mz[i] = z;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    Bellman();
    while(Dijkstra())
    {
        flow = int(2e9);
        for(i = Dest; i != Src; i = prev[i])
            flow = min(flow, C[prev[i]][i]);
        for(i = Dest; i != Src; i = prev[i])
            C[prev[i]][i] -= flow, C[i][prev[i]] += flow;
        sol += flow*real[Dest];
    }
    fo << sol << "\n";
    return 0;
}