Cod sursa(job #1162050)

Utilizator rares96cheseliRares Cheseli rares96cheseli Data 31 martie 2014 16:45:09
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>
#include <vector>
#include <queue>
#define inf 200000000
using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");

int N, M, x, y, z, c, used[352], cap[352][352], flux[352][352], cost[352][352], D[352], prec[352], sink, source, sol;
bool inQ[352];
vector < int > G[352];
queue < int > Q;

inline int bellman(const int &sursa)
{
    for (int i=1; i<=N; ++i)
        D[i]=prec[i]=inf, used[i]=0;
    Q.push(sursa); inQ[sursa]=1; D[sursa]=0; prec[sursa]=sursa;
    while (Q.size())
    {
        int nod=Q.front(); Q.pop(); inQ[nod]=0; ++used[nod];
        if (used[nod]==N) return 0;
        vector <int>::iterator it=G[nod].begin();
        for (; it!=G[nod].end(); ++it)
            if (D[nod]+cost[nod][*it]<D[*it] && cap[nod][*it]>flux[nod][*it])
            {
                D[*it]=D[nod]+cost[nod][*it]; prec[*it]=nod;
                if (!inQ[*it]) inQ[*it]=1, Q.push(*it);
            }
    }
    if (D[sink]!=inf)
    {
        int minflow=inf;
        for (int i=sink; i!=sursa; i=prec[i])
            if (cap[prec[i]][i]-flux[prec[i]][i]<minflow)
                minflow=cap[prec[i]][i]-flux[prec[i]][i];
        if (minflow)
        {
            for (int i=sink; i!=sursa; i=prec[i])
                flux[prec[i]][i]+=minflow, flux[i][prec[i]]-=minflow;
            return minflow;
        }
    }
    return 0;
}

int main()
{
    f>>N>>M>>source>>sink;
    for (int i=1; i<=M; ++i)
    {
        f>>x>>y>>z>>c; cap[x][y]=z;
        cost[x][y]=c; cost[y][x]=-c;
        G[x].push_back(y); G[y].push_back(x);
    }

    for (int flow=bellman(source); flow; flow=bellman(source))
        sol+=flow*D[sink];
    g<<sol<<'\n';
    return 0;
}