Cod sursa(job #303696)

Utilizator bogdanhm999Casu-Pop Bogdan bogdanhm999 Data 10 aprilie 2009 10:57:12
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <stdio.h>
#include <queue>
#define nMax 355
#define mMax 12505
#define INF 1000000000
using namespace std;
struct mc{short x,y;}a[mMax];
short N,M,S,D,g[nMax],t[nMax],iq[nMax],path[nMax],cap[nMax][nMax],cst[nMax][nMax];
short *v[nMax]; int d[nMax];

void bellman(){
  short i,nod,fiu; queue <short> Q; 
  for (i=1;i<=N;++i)d[i]=INF;
  d[S]=0; iq[S]=1;
  Q.push(S);
  while (!Q.empty()){
    nod=Q.front(); Q.pop(); iq[nod]=0;
    for (i=0;i<g[nod];++i){
      fiu = v[nod][i];
      if ( cap[nod][fiu] > 0 )
        if ( d[nod] + cst[nod][fiu] < d[fiu] ){
          d[fiu] = d[nod] + cst[nod][fiu];
          t[fiu]=nod;
          if (!iq[fiu]){ iq[fiu]=1; Q.push(fiu); }
        }
    }
  }
}

int main(){
  freopen("fmcm.in","r",stdin); freopen("fmcm.out","w",stdout);
  short i,x,y,cc,cs,q,minim; int cost=0,flux=0;

  scanf("%hd %hd %hd %hd",&N,&M,&S,&D);
  for (i=1;i<=M;++i){
    scanf("%hd %hd %hd %hd",&x,&y,&cc,&cs);
    cap[x][y]=cc;
    cst[x][y]=cs; cst[y][x]=-cs;
    g[x]++; g[y]++;
    a[i].x=x; a[i].y=y;
  }
  for (i=1;i<=N;++i){ v[i] = (short*)malloc(g[i]*sizeof(short)); g[i]=0;}
  for (i=1;i<=M;++i){x=a[i].x;y=a[i].y;v[x][g[x]++]=y;v[y][g[y]++]=x;}
  
  do{
    bellman(); if (d[D]==INF)break;
    q=0; x=D;
    do{
      path[++q]=x; x=t[x];
    }while (x);
    ////////
    minim=32000;
    for (i=1;i<q;++i)
      if (cap[path[i+1]][path[i]]<minim)minim=cap[path[i+1]][path[i]];
    for (i=1;i<q;++i){
      cap[path[i+1]][path[i]]-=minim;
      cap[path[i]][path[i+1]]+=minim;
    }
    flux+=minim;
    cost+=minim*d[D];
  }while(1);
  printf("%d\n",cost);
return 0;
}