Cod sursa(job #441209)

Utilizator MciprianMMciprianM MciprianM Data 12 aprilie 2010 20:21:44
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.33 kb
# include <fstream>
# include <vector>
# include <queue>

using namespace std;

const int MAXN = 512, inf = 2000000001;
int maxFlow, minCost;
int N, M, S, D;
int cap [ MAXN ] [ MAXN ], cost [ MAXN ] [ MAXN ];
int dist [ MAXN ], from [ MAXN ];
vector <int> G [ MAXN ];
queue <int> q;

void oneSourceMultipleDestinationsMinPaths (){

	int i;
	vector <int> :: iterator it;
	
	for ( i = 1; i <= N; ++ i )
		dist [ i ] = inf;
	dist [ S ] = 0;
	memset ( from, -1, sizeof ( from ) );
	
	q . push ( S );
	while ( ! q. empty () ){
		for ( it = G [ q . front () ] . begin (); it != G [ q . front () ] . end (); ++ it )
			if ( cap [ q . front () ] [ * it ] > 0 && dist [ q . front () ] != inf
				&& dist [ * it ] > dist [ q . front () ] + cost [ q . front () ] [ * it ] ){
					dist [ * it ] = dist [ q . front () ] + cost [ q . front () ] [ * it ];
					q . push ( * it );
					from [ * it ] = q . front ();
			}
		q . pop ();
	}
}

void findAugmentingPathOfMinCost ( int &flow, int &cst ){
	
	int dad;
	
	flow = inf; cst = 0;
	
	oneSourceMultipleDestinationsMinPaths ();
	
	if ( from [ D ] == -1 ){
		flow = 0;
		return;
	}
	
	dad = D;
	while ( from [ dad ] != -1 ){
		
		cst += cost [ from [ dad ] ] [ dad ];
		if ( cap [ from [ dad ] ] [ dad ] < flow )
			flow = cap [ from [ dad ] ] [ dad ];
		dad = from [ dad ];
		
	}
	
	dad = D;
	while ( from [ dad ] != -1 ){
		
		cap [ dad ] [ from [ dad ] ] += flow;
		cap [ from [ dad ] ] [ dad ] -= flow;
		dad = from [ dad ];
		
	}
	
}

void fmcm (){
	
	int flux, cst;
	
	do{
	
		findAugmentingPathOfMinCost ( flux, cst );
		maxFlow += flux;
		minCost += flux * cst;
		
	}	while ( flux > 0 );
	
}

void creareGraf (){
	
	/* Graful contine cel mult un arc intre oricare doua noduri x si y,
		iar daca ( x, y ) apartine lui E, atunci ( y, x ) nu apartine lui E,
		unde E este multimea arcelor	*/
	
	int i, x, y;
	ifstream f ( "fmcm.in" );
	
	f >> N >> M >> S >> D;
	for ( i = 0; i < M; ++ i ){
		f >> x >> y;
		f >> cap [ x ] [ y ] >> cost [ x ] [ y ];
		cost [ y ] [ x ] = - cost [ x ] [ y ];
		G [ x ] . push_back ( y );
		G [ y ] . push_back ( x );
	}
	
	f . close ();
	
}

void afis (){
	
	ofstream g ( "fmcm.out" );
	g << minCost << '\n';
	g . close ();
	
}

int main(){
	
	creareGraf ();
	fmcm ();
	afis ();
	
	return 0;
	
}