Cod sursa(job #384563)

Utilizator mihaionlyMihai Jiplea mihaionly Data 20 ianuarie 2010 13:39:22
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <stdio.h>
#define nmax 510
#define ll long long
#define inf 1<<30
#define min(a,b) ((a<b)?(a):(b))
typedef struct nod
 {
 int x;
 nod *urm;
 } graf;
graf *G[nmax];
int Cap[nmax][nmax],Cost[nmax][nmax],Fx[nmax][nmax],Pre[nmax];
int Q[nmax],k;
int n,S,D;
ll Dist[nmax],Vmin;
bool Drum,viz[nmax];
void add(graf *&g,int x)
 {
 graf *p=new graf;
 p->x=x;
 p->urm=g;
 g=p;
 }
ll BF()
 {
 int i,x;
 for(i=1;i<=n;++i){Dist[i]=inf;Pre[i]=-1;viz[i]=false;}
 k=0;
 Q[++k]=S;
 Dist[S]=0;
 viz[S]=true;
 for(i=1;i<=k;++i)
  {
  x=Q[i];
  for(graf *g=G[x];g!=NULL;g=g->urm)
   {
   if(Cap[x][g->x]-Fx[x][g->x]>0 && Cost[x][g->x]+Dist[x]<Dist[g->x])
    {
    Dist[g->x]=Cost[x][g->x]+Dist[x];
	Pre[g->x]=x;
	if(!viz[g->x])
	 {
	 viz[g->x]=true;
	 Q[++k]=g->x;
	 }
    }
   }
  viz[x]=false;
  }
 if(Dist[D]!=inf)
  {
  Vmin=inf;
  Drum=true;
  for(i=D;i!=S;i=Pre[i]) Vmin=min(Cap[Pre[i]][i]-Fx[Pre[i]][i],Vmin);
  for(i=D;i!=S;i=Pre[i])
   {
   Fx[Pre[i]][i]+=Vmin;
   Fx[i][Pre[i]]-=Vmin;
   }
  return Vmin*Dist[D];
  }
 return 0;
 }
ll Flux()
 {
 ll rez=0;
 Drum=true;
 while(Drum)
  {
  Drum=false;
  rez+=BF();
  }
 return rez;
 }
int main()
 {
 FILE *f=fopen("fmcm.in","r");
 int m,i,x,y,c,z;
 fscanf(f,"%d %d %d %d",&n,&m,&S,&D);
 for(i=0;i<m;++i)
  {
  fscanf(f,"%d %d %d %d",&x,&y,&c,&z);
  Cap[x][y]=c;
  add(G[x],y);
  add(G[y],x);
  Cost[x][y]=z;
  Cost[y][x]=-z;
  }
 fclose(f);
 FILE *g=fopen("fmcm.out","w");
 fprintf(g,"%lld",Flux());
 fclose(g);
 }