Cod sursa(job #558094)

Utilizator BitOneSAlexandru BitOne Data 17 martie 2011 08:30:47
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <queue>
#include <vector>
#include <fstream>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#define N_MAX 50011
#define oo 1<<28
#define pr pair< int, int >

using namespace std;
bool was[N_MAX];
int _count[N_MAX], d[N_MAX];
queue< int > Q;
vector< pr > G[N_MAX];
vector< pr >::const_iterator it, iend;
int main()
{
	int N, M, x, y, c;
	ifstream in( "bellmanford.in" );
	for( in>>N>>M; M; --M )
	{
		in>>x>>y>>c;
		d[x]=d[y]=oo;
		G[x].push_back( pr( y, c ) );
	}
	d[1]=0;
	for( Q.push(1); !Q.empty(); )
	{
		x=Q.front(); Q.pop();
		was[x]=false;
		for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
			if( d[it->first] > d[x]+it->second )
			{
				d[it->first]=d[x]+it->second;
				if( false == was[it->first] )
				{
					was[it->first]=true;
					++_count[it->first];
					if( _count[it->first] >= N )
					{
						ofstream out( "bellmanford.out" );
						out<<"Ciclu negativ!\n";
						return EXIT_SUCCESS;
					}
					Q.push( it->first );
				}
			}
	}
	ofstream out( "bellmanford.out" );
	copy( d+2, d+N+1, ostream_iterator<int>( out, " " ) );
	out<<'\n';
	return EXIT_SUCCESS;
}