Cod sursa(job #696632)

Utilizator giuliastefGiulia Stef giuliastef Data 28 februarie 2012 19:18:31
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.78 kb
#include <cstdio>
#include <cstring>
#include <vector>
#define NMAX 357
#define INF 1<<28
using namespace std;
vector <int> G[NMAX];
int N,M,S,D,Sum,Drum,l;
int t[NMAX],c[NMAX][NMAX],cost[NMAX][NMAX],f[NMAX][NMAX],dist[NMAX],h[NMAX],pos[NMAX];

void BellmanFord(){
     int i,j,stop;
     memset(dist,INF,sizeof(dist));
     dist[S]=0; stop=0;
     for(i=1;i<=N && !stop;i++){
       stop=1;
       for(j=1;j<=N;j++)
        for(vector<int>::iterator it=G[j].begin();it!=G[j].end();it++)
         if(c[j][*it]-f[j][*it]>0 && dist[j]+cost[j][*it]<dist[*it]){
                                  stop=0;
                                  dist[*it]=dist[j]+cost[j][*it];
         }
     }
     Sum=dist[D];
}
void upheap(int poz)
{
	int aux;
	while(poz>=1 && dist[h[poz]]<dist[h[poz/2]])
	{
        swap(pos[h[poz]],pos[h[poz/2]]);
        swap(h[poz],h[poz/2]);
		poz=poz/2;
	}
}
void downheap(int poz)
{
	int aux;
	while(poz*2+1<=l && (dist[h[poz]]>dist[h[poz*2]] || dist[h[poz]]>dist[h[poz*2+1]]))
	{
		if(poz*2+1<=l && dist[h[poz*2]]>dist[h[poz*2+1]])
		{
			swap(pos[h[poz]],pos[h[poz*2+1]]);
			swap(h[poz],h[poz*2+1]);
			poz=poz*2+1;
		}
		else
		{
			swap(pos[h[poz]],pos[h[poz*2]]);
			swap(h[poz],h[poz*2]);
			poz=poz*2;
		}
	}
}
int Dijkstra(){
    int i,nod;
    for(i=1;i<=N;i++)
     for(vector <int>::iterator it=G[i].begin();it!=G[i].end();it++)
      if(dist[i]!=INF && dist[*it]!=INF) cost[i][*it]+=dist[i]-dist[*it];
    for(i=1;i<=N;i++){
     h[i]=i;
     pos[i]=i;
     dist[i]=INF;
    }  
    l=N; dist[S]=0;
    h[1]=S, h[S]=1;
    pos[1]=S, pos[S]=1;
    while(l){
     nod=h[1];
     h[1]=h[l--];
     pos[h[1]]=1;
     downheap(1);
     for(vector<int>::iterator it=G[nod].begin();it!=G[nod].end();it++){
      if(c[nod][*it]-f[nod][*it]>0 && dist[nod]+cost[nod][*it]<dist[*it]){
       dist[*it]=dist[nod]+cost[nod][*it];
       t[*it]=nod;
       upheap(pos[*it]);
      }
     }
    }  
    if(dist[D]!=INF){
     int fmin=INF;
     Drum=1;
     for(i=D;i!=S;i=t[i])
      fmin=min(fmin,c[t[i]][i]-f[t[i]][i]);
     if(!fmin) return 0;
     for(i=D;i!=S;i=t[i]){
      f[t[i]][i]+=fmin;
      f[i][t[i]]-=fmin;
     }
     Sum+=dist[D];
     return fmin*Sum;
    }
    return 0;
}
long long Flux(){
     long long Sol=0;
     Drum=1;
     while(Drum){
      Drum=0;
      Sol+=Dijkstra();
     }
     return Sol;
}
int main(){
    int x,y,z,t;
     freopen("fmcm.in","r",stdin);
     freopen("fmcm.out","w",stdout);
     scanf("%d%d%d%d",&N,&M,&S,&D);
     for(;M>0;M--){
      scanf("%d%d%d%d",&x,&y,&z,&t);
      G[x].push_back(y);
      G[y].push_back(x);
      c[x][y]=z;      
      cost[x][y]=t;
      cost[y][x]=-t; 
    }
    BellmanFord();
    printf("%lld\n",Flux());
    return 0;
}