Cod sursa(job #696751)

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

void BellmanFord(){
     int i,j,stop;
     for(i=1;i<=N;i++) dist[i]=INF;
     dist[S]=0; stop=0;
     for(i=1;i<=N && !stop;i++){
       stop=1;
       for(j=1;j<=N;j++)
        for(vector<short int>::iterator it=G[j].begin();it!=G[j].end();it++)
         if(f[j][*it]>0 && dist[j]+cost[j][*it]<dist[*it]){
                                  stop=0;
                                  dist[*it]=dist[j]+cost[j][*it];
         }
     }
     Sum=dist[D];
}
inline void upheap(int poz)
{
	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;
	}
}
inline void downheap(int poz)
{
	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;
		}
	}
}
bool Dijkstra(){
    int i,nod=S;
    for(i=1;i<=N;i++)
     for(vector <short 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 && dist[nod]!=INF){
     nod=h[1];
     h[1]=h[l--];
     pos[h[1]]=1;
     downheap(1);
     for(vector<short int>::iterator it=G[nod].begin();it!=G[nod].end();it++){
      if(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)
     return 1;
    return 0;
}
int main(){
    long long Flux=0;
    int x,y,z,p,k,fmin;
     ifstream in("fmcm.in");
     in>>N>>M>>S>>D;
     for(;M>0;M--){
      in>>x>>y>>z>>p;
      G[x].push_back(y);
      G[y].push_back(x);
      f[x][y]=z;      
      cost[x][y]=p;
      cost[y][x]=-p; 
    }
    in.close();
    BellmanFord();
    while(Dijkstra()){
     fmin=INF;
     for(k=D;k!=S;k=t[k])
      fmin=min(fmin,f[t[k]][k]);
     for(k=D;k!=S;k=t[k]){
      f[t[k]][k]-=fmin;
      f[k][t[k]]+=fmin;
     }
     Sum+=dist[D];
     Flux+=fmin*Sum;
    }
    ofstream out("fmcm.out");
    out<<Flux<<'\n';
    out.close();
    return 0;
}