Cod sursa(job #582548)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 15 aprilie 2011 15:47:52
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include <cstdio>
#include <cstring>
#include <fstream>
#include <queue>
#define Nmx 355
#define INF 0x3f3f3f3f

using namespace std;

int n,m,C[Nmx][Nmx],F[Nmx][Nmx],sol,cuplaj;
int cost[Nmx],viz[Nmx],prec[Nmx],s,d;
struct nod
{
    int inf,c;
    nod *urm;
};
nod *G[Nmx];
queue <int> Q;

ifstream fin("fmcm.in");

void add(int x,int y,int cst)
{
    nod *aux=new nod;
    aux->inf = y;
    aux->c = cst;
    aux->urm = G[x];
    G[x] = aux;
}

void read()
{
    int x,y,c,cst;
    fin>>n>>m>>s>>d;
    for(int i=1;i<=m;++i)
    {
        fin>>x>>y>>c>>cst;
        C[x][y]=c;
        add(x,y,cst);
        add(y,x,-cst);
    }
}

int bellmand()
{
    for(int i=1;i<=n;++i)
        cost[i]=INF;
    cost[s]=0;
    prec[s]=0;
    viz[s]=1;
    Q.push(s);
    while(!Q.empty())
    {
        int x = Q.front();
        Q.pop();
        viz[x]=0;
        for(nod *p=G[x];p;p=p->urm)
            if((C[x][p->inf]-F[x][p->inf] > 0) && (cost[p->inf] > (cost[x] + p->c)))
            {
                cost[p->inf]=cost[x]+p->c;
                prec[p->inf]=x;
                if(!viz[p->inf])
                {
                    viz[p->inf]=1;
                    Q.push(p->inf);
                }
            }
    }
    if(cost[d]<INF)
        return 1;
    return 0;
}

void solve()
{
    while(bellmand())
    {
        int Vmin=INF;
        for(int j=d;prec[j];j=prec[j])
            Vmin=min(Vmin,C[prec[j]][j]-F[prec[j]][j]);
        if(Vmin)
        {
            for(int j=d;prec[j];j=prec[j])
            {
                F[prec[j]][j]+=Vmin;
                F[j][prec[j]]-=Vmin;
            }
            if(Vmin*cost[d]!=0)
                sol+=Vmin*cost[d],cuplaj+=Vmin;
        }
    }
    printf("%d\n",sol);
}

int main()
{
    freopen("fmcm.in","r",stdin);
    freopen("fmcm.out","w",stdout);
    read();
    solve();
    return 0;
}