Cod sursa(job #603724)

Utilizator BlaugranasEnal Gemaledin Blaugranas Data 18 iulie 2011 14:09:39
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include<fstream.h>
#define INF 30001
#define N 351
int n,m,k,c[N][N],f[N][N],p,z,i,s,d,pre[N],t,l,o[N][N],h[N],poz[N],j;
long e=0,b[N];

void Down(int t)
{int i,k;
for(i=t?t<<1:1;;i=t<<1)
      {if(i+1<l&&b[h[i+1]]<b[h[t]])
             i++;
      else 
             if(i>=l)
                    return;
      k=poz[h[i]];
      poz[h[i]]=poz[h[t]];
      poz[h[t]]=k;
      k=h[i];
      h[i]=h[t];
      h[t]=k;
      t=i;}}

int Pop()
{int i=h[0];
poz[i]=-1;
h[0]=h[--l];
poz[h[0]]=0;
Down(0);
return i;}

void Up(int i)
{int t,k;
for(t=i>>1;i&&b[t]>b[i];i>>=1,t=i>>1)
      {k=poz[h[i]];
      poz[h[i]]=poz[h[t]];
      poz[h[t]]=k;
      k=h[i];
      h[i]=h[t];
      h[t]=k;}}

void Push(int i,long  dist)
{b[i]=dist;
if(poz[i]==-1)
      {poz[i]=l;
      h[l++]=i;
      Up(poz[i]);}}

int main()
{ifstream h("fmcm.in");
ofstream g("fmcm.out");
h>>n>>m>>s>>d;
s--,d--;
while(m--)
          {h>>i>>j>>p>>z;
          i--,j--;
          c[i][j]=p,o[i][j]=z,o[j][i]=-z;}
while(1)      
          {for(i=0;i<n;i++)
                   pre[i]=poz[i]=-1,b[i]=INF;
          l=0,m=INF;
          Push(s,0);
          while(l)
                   {i=Pop();
                   for(k=0;k<n;k++)
                   if(f[i][k]<c[i][k]&&b[k]>b[i]+o[i][k])
                               {b[k]=b[i]+o[i][k];
                               pre[k]=i;
                               Push(k,b[k]);}}
          if(pre[d]==-1)
                   break;
          for(l=d;l!=s;l=pre[l])
          if(m>(t=c[pre[l]][l]-f[pre[l]][l]))
                   m=t;
          for(l=d;l!=s;l=pre[l])
                   f[pre[l]][l]+=m,f[l][pre[l]]-=m;
          e=e+b[d]*m;}
g<<e;    
h.close();
g.close();
return 0;}