Cod sursa(job #811557)

Utilizator MtkMarianHagrSnaf MtkMarian Data 12 noiembrie 2012 17:17:45
Problema Flux maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2 kb
#include<cstdio>
#include<algorithm>
#include<vector>
#include<queue>
#include <string.h>
using namespace std;


#define NMAX 355
#define INF 2e7



int n , m , x ,y , z ,fluxmin,cp,surs,dest ,global;

long long flx ;

vector< int > g[NMAX] ;

vector< int > h ;

int d[NMAX] ;
int c[NMAX][NMAX]={0} , viz[NMAX] , t[NMAX] ;
int flux[NMAX][NMAX] ={0} , cost[NMAX][NMAX] ;

int bellford()
{
	
	
	for(int i = 1 ; i <= n ; ++i)
	{		
		d[i]=INF;
		t[i]=-1;
	}

	memset(viz, 0, sizeof(viz));

	long pas=0 ;

	d[surs] = 0;

	h.clear();

	h.push_back(surs);
	make_heap(h.begin(),h.end());
	viz[surs]=1;

	while(h.size() && pas<=1LL*n*m)		
	{
		pop_heap(h.begin(),h.end() ) ;
		
		int el = h.back();

		
		h.pop_back();

		viz[el]=0;

		++pas;

		for(int j=0 ; j < g[el].size() ; ++j)
		{
			int y1=g[el][j];

			z=cost[el][y1];

			if( d[ y1 ] > d[ el ] + z && flux[el][y1]< c[el][y1] )			
			{
				d[ y1 ] = d[ el ]+z;

				t[y1]=el;	

				if(!viz[y1])
				{
					viz[y1]=1;
					h.push_back(y1);
					push_heap(h.begin(),h.end());
				}
			}
		}
	}

	if( d[ dest ] != INF)
	{
		fluxmin=INF;
		global=1;

		for(int nod = dest ; nod != surs ; nod = t[nod])
			fluxmin =  min ( fluxmin , c[ t [ nod ] ] [ nod ] - flux [ t[nod] ] [ nod ] ) ;				

		 for(int nod = dest ; nod != surs; nod = t [ nod ] )
			{
				flux [ t[ nod ] ][nod] += fluxmin;
				flux [nod] [ t[nod] ] -= fluxmin;
			}

			return d[dest]*fluxmin ;
	}

	return 0 ;

}

void apel ()
{
	global=1;

	while( global )
	{
		global = 0;
		flx += bellford();
	}
}

void citeste()
{
	scanf("%d %d %d %d" , &n , &m , &surs , &dest );

	for(int i = 1 ; i <= m ;++i)
	{
		scanf("%d %d %d %d",&x,&y,&cp,&z);

		c[x][y] = cp;
		cost[x][y] +=z ;
		cost[y][x] -=z ;

		g[x].push_back ( y );
		g[y].push_back( x );
	}
	

}

int main()
{
	freopen("fmcm.in", "r",stdin);
	freopen("fmcm.out","w",stdout);
	
	citeste();
	
	apel();
	
	printf("%lld",flx);

	return 0;
}