Cod sursa(job #662155)

Utilizator pykhNeagoe Alexandru pykh Data 15 ianuarie 2012 23:07:11
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include<cstdio>
#include<queue>
#include<vector>
#include<bitset>
#include<cstring>
using namespace std;

const int Max_N = 50100;
const int INF = 0x3f3f3f3f;

const char in[] = "bellmanford.in";
const char out[]= "bellmanford.out";

#define pb push_back

vector<int>G[Max_N], C[Max_N];
queue<int>Q;

int dist[Max_N], cnt_Q[Max_N], N, M;
bool in_Q[Max_N], ciclu_negativ;

int main()
	{
		freopen(in,"r",stdin);
		freopen(out,"w",stdout);
		scanf("%d %d", &N, &M);
		memset(dist, INF, sizeof(dist));
		int a, b, cost, x;
		for(int i = 1 ; i <= M ; ++i)
			scanf("%d%d%d", &a, &b, &cost), G[a].pb(b), C[a].pb(cost);
		dist[1] = 0, Q.push(1), in_Q[1] = true;
		
		while( Q.size() && !ciclu_negativ )
		{
			x = Q.front();
			Q.pop();
			in_Q[x] = false;
		for(int i = 0 ; i < G[x].size() ; ++i)
		{
			if(dist[G[x][i]] > dist[x] + C[x][i])
			{
				dist[G[x][i]] = dist[x] + C[x][i];
				if(!in_Q[G[x][i]])
					if(cnt_Q[G[x][i]] > N)ciclu_negativ = true;
				else
				{
					Q.push(G[x][i]);
					in_Q[G[x][i]] = true;
					++cnt_Q[G[x][i]];
				}
			}
		}
		}
		if(ciclu_negativ)printf("Ciclu negativ!");
		else 
			for(int i = 2 ;  i <= N ; ++i)
				printf("%d ", dist[i]);
		return 0;
		}