Cod sursa(job #544392)

Utilizator avram_florinavram florin constantin avram_florin Data 1 martie 2011 15:57:52
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include<fstream>
#include<vector>
#include<queue>

using namespace std;

const int MaxN = 50001;
const int INF = 0x3f3f3f3f;

int n,m;
int d[MaxN],viz[MaxN];
vector< pair<int,int> > G[MaxN];
queue<int> Q;

inline void read()
{
	int x,y,cost;
	ifstream f ("bellmanford.in");
	f >> n >> m;
	for( int i = 1 ; i <= n ; i++ )
		d[i] = INF;
	for(int i = 1 ; i <= m ; i++ )
		{
			f >> x >> y >> cost;
			G[x].push_back(make_pair(y,cost));
		}
	f.close();
}

int bellman_ford()
{
	int nod;
	vector< pair<int,int> >::iterator it;
	d[1] = 0;
	Q.push(1);
	while( !Q.empty() )
		{
			nod = Q.front();
			Q.pop();
			for( it = G[nod].begin() ; it != G[nod].end() ; ++it )
				if( d[it->first] > d[nod] + it->second )
					{
						d[it->first] = d[nod] +it->second;
						viz[it->first]++;
						if( viz[it->first] > n )
							return 0;	
						Q.push(it->first);
					}
		}
	return 1;
}

inline void print()
{
	ofstream g ("bellmanford.out");
	if( bellman_ford() )
		for( int i = 2 ; i <= n ; i++ )
			g << d[i] << ' ';
		else
		g << "Ciclu negativ!";
	g.close();
}

int main()
{
	read();
	print();
	return 0;
}