Cod sursa(job #1698065)

Utilizator gabib97Gabriel Boroghina gabib97 Data 3 mai 2016 16:33:28
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <stdio.h>
#include <queue>
#include <vector>
#include <stdlib.h>
#define inf 100000000
using namespace std;
int n,m,i,C[351][351],z[351][351],f[1001],t[1001],cost,s,w,d[351],r,j,q;
short *G[351];
bool o[351];
int Q[2000000];
void citire()
{
    int x,y,c,q;
    scanf("%i%i%i%i",&n,&m,&s,&w);
    for (i=1;i<=n;i++)
        G[i]=(short*) calloc(1,sizeof(short));
    for (i=1;i<=m;i++)
    {
        scanf("%i%i%i%i",&x,&y,&c,&q);
        C[x][y]=c;
        z[x][y]=q;
        z[y][x]=-q;
        G[x]=(short*) realloc(G[x],(++G[x][0]+1)*sizeof(short));
        G[x][G[x][0]]=y;
        G[y]=(short*) realloc(G[y],(++G[y][0]+1)*sizeof(short));
        G[y][G[y][0]]=x;
    }
}
bool bellmanford()
{
    int i,x,y,p,u;
    p=u=1;
    for (i=1;i<=n;i++) d[i]=inf,t[i]=0,o[i]=0;
    d[s]=0; o[s]=1;
    while (p<=u)
    {
        x=Q[p++];
        o[x]=0;
        for (i=1;i<=G[x][0];i++)
        {
            y=G[x][i];
            if (d[y]>d[x]+z[x][y]&&C[x][y]>0)
            {
                d[y]=d[x]+z[x][y];
                t[y]=x;
                if (!o[y])
                {
                    o[y]=1;
                    Q[++u]=y;
                }
            }
        }
    }
    return t[w];
}
int main()
{
    freopen ("fmcm.in","r",stdin);
    freopen ("fmcm.out","w",stdout);
    citire();
    Q[1]=s;
    while (bellmanford())
    {
        r=inf;
        for (j=w;j!=s;j=t[j])
            r=min(r,C[t[j]][j]);
        for (j=w;j!=s;j=t[j])
        {
            C[t[j]][j]-=r;
            C[j][t[j]]+=r;
        }
        cost+=r*d[w];
    }
    printf("%i",cost);
    fclose(stdin);
    fclose(stdout);
    return 0;
}