Cod sursa(job #1453175)

Utilizator al.mocanuAlexandru Mocanu al.mocanu Data 22 iunie 2015 20:13:49
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <stdio.h>
#include <queue>
#include <vector>
#define MAX 50005
#define INF 1<<20
using namespace std;

typedef struct{
	int node, cost;
} TNod;

int n, m, i, j, x, y, z, d[MAX];
bool viz[MAX];
vector<TNod> L[MAX];
queue<TNod> q;

bool bf(int s);

int main(){
	freopen("bellmanford.in", "r", stdin);
	freopen("bellmanford.out", "w", stdout);
	TNod aux;
	scanf("%d%d", &n, &m);
	for(i = 0; i < m; i++){
		scanf("%d%d%d", &x, &y, &z);
		aux.node = y;
		aux.cost = z;
		L[x].push_back(aux);
	}
	if(bf(1) == false)
		printf("Ciclu negativ!\n");
	else{
		for(i = 2; i <= n; i++)
			printf("%d ", d[i] == INF ? 0 : d[i]);
		printf("\n");
	}
	return 0;
}

bool bf(int s){
	vector<TNod>::iterator it;
	for(i = 1; i <= n; i++)
		d[i] = INF;
	d[s] = 0;

	for(i = 0; i < n; i++)
		for(j = 1; j <= n; j++)
			if(!L[j].empty()){
				it = L[j].begin();
				while(it < L[j].end()){
					if(d[it->node] > d[j] + it->cost)
						d[it->node] = d[j] + it->cost;
					it++;
				}
			}

	for(i = 2; i <= n; i++)
		while(!L[i].empty()){
			if(d[L[i].back().node] > d[i] + L[i].back().cost)
				return false;
			L[i].pop_back();
		}
	
	return true;
}