Cod sursa(job #609948)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 23 august 2011 22:37:14
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include<stdio.h>
#define M 1000000000
#define N 510
long n,m,k,j,i,l,s,d,t,q,w,c[N][N],f[N][N],p[N],h[N],r[N],g[N][N],a[N],o[N][N],b[N];
long long e;
int main()
{freopen("fmcm.in","r",stdin),freopen("fmcm.out","w",stdout);
scanf("%ld%ld%ld%ld",&n,&m,&s,&d);
while(m--)
          scanf("%ld%ld%ld%ld",&i,&j,&l,&k),g[i][a[i]++]=j,g[j][a[j]++]=i,o[i][j]=k,o[j][i]=-k,c[i][j]=l;
while(1)      
          {for(i=1;i<=n;i++)
                   b[i]=M,r[i]=0;
          b[s]=p[d]=0,h[1]=s,m=M,l=1;
          while(l)
                   {i=h[1],r[i]=0,h[1]=h[l--],r[h[1]]=1;
                   for(j=1;(t=2*j)<=l;j=t)
                          {if(t<l&&b[h[t+1]]<b[h[t]])
                                 t++;
                          if(b[h[j]]<=b[h[t]])
                                 break;
                          k=h[j],h[j]=h[t],h[t]=k,r[h[j]]=j,r[h[t]]=t;}
                   for(k=0;k<a[i];k++)
                   if(b[j=g[i][k]]>b[i]+o[i][j]&&c[i][j]>f[i][j])
                          {b[j]=b[i]+o[i][j],p[j]=i;
                          if(!r[j])
                                 h[++l]=j,r[j]=l;
                          for(t=r[j];t>2&&b[h[t]]<b[h[q=t/2]];t=q)
                                 w=h[t],h[t]=h[q],h[q]=w,r[h[t]]=t,r[h[q]]=q;}}
          if(!p[d])
                   break;
          for(l=d;l!=s;l=p[l])
          if(m>(k=c[p[l]][l]-f[p[l]][l]))
                   m=k;
          for(l=d;l!=s;l=p[l])
                   f[p[l]][l]+=m,f[l][p[l]]-=m;
          e=e+b[d]*m;}
printf("%lld",e);
return 0;}