Cod sursa(job #435569)

Utilizator MciprianMMciprianM MciprianM Data 7 aprilie 2010 17:12:23
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
# include <fstream>
# include <vector> 

using namespace std;

//Bellman Ford algorithm with a queue ( using BFS )
//supposed to obtain 35p.

struct neighbour{
	int y, c;
};

int dist [ 51 ], queue[51], qs;
bool viz [ 51 ];
vector <neighbour> G [ 51 ];
const int inf = 2000000001;

int main(){

	ifstream f ( "bellmanford.in" );
	ofstream g ( "bellmanford.out" );

	int n, m, i, x, h;
	neighbour a;
	vector <neighbour> :: iterator it, end;

	f >> n >> m;
	for ( i = 0; i < m; ++ i ){
		f >> x >> a . y >> a . c ;
		G [ x ] . push_back ( a );
	}
	f . close ();
	
	for ( i = 2; i <= n; ++ i )
		dist [ i ] = inf;
	
	for ( i = 1; i < n; ++ i ){
		h=0;	qs = 0;
		queue [ qs ++ ] = 1;
		memset ( viz, 0, sizeof ( viz ) );
		while ( h < qs ){
			end = G [ queue [ h ] ] . end ();
			for ( it = G [ queue [ h ] ] . begin (); it != end; ++ it ){
				if ( ! viz [ it -> y ] )
					queue [ qs ++ ] = it -> y;
				viz [ it -> y ] = 1;
				if ( dist [ it -> y ] > dist [ queue [ h ] ] + it -> c )
					dist [ it -> y ] = dist [ queue [ h ] ] + it -> c;
			}
			++ h;
		}
	}
		
	h=0;	qs = 0;
	queue [ qs ++ ] = 1;
	memset ( viz, 0, sizeof ( viz ) );
	while ( h < qs ){
		end = G [ queue [ h ] ] . end ();
		for ( it = G [ queue [ h ] ] . end (); it != end; ++ it ){
			if ( ! viz [ it -> y ] )
				queue [ qs ++ ] = it -> y;
			viz [ it -> y ] = 1;
			if ( dist [ it -> y ] > dist [ queue [ h ] ] + it -> c ){
				g << "Ciclu negativ!\n";
				g . close ();
				return 0;
			}
		}
		++ h;
	}
	
	for ( i = 2; i <= n; ++ i )
		g << dist [ i ] << ' ';
	g << '\n';
	g . close ();

	return 0;

}