Cod sursa(job #442044)

Utilizator nandoLicker Nandor nando Data 13 aprilie 2010 20:22:43
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <cstdio>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;

#define INF 0x3f3f3f3f
#define MAXN 50005

typedef vector<pair<int,int> >::iterator iter;
vector<pair<int,int> > g[MAXN];
bitset<MAXN> inList;
queue<int> lst;
int n,m,cn=0,d[MAXN],cycle[MAXN];

inline bool bellmanford(){
	bool neg=false;
	int top;

	for(int i=2;i<=n;i++){
		d[i]=INF;
	}

	d[1]=0,inList[1]=true,lst.push(1);
	
	while(!lst.empty()&&!neg){
		top=lst.front(),lst.pop();
		inList[top]=false;
		for(iter it=g[top].begin();it!=g[top].end()&&!neg;it++){
			if(d[it->first]>d[top]+it->second){
				d[it->first]=d[top]+it->second;
				if(!inList[it->first]){
					if(cycle[it->first]>n){
						neg=true;
					}else{
						lst.push(it->first),inList[it->first]=true,cycle[it->first]++;						
					}
				}
			}
		}
	}
	return !neg;
}

int main(){
	int x,y,c;
	FILE* fin=fopen("bellmanford.in","r");
	FILE* fout=fopen("bellmanford.out","w");

	fscanf(fin,"%d %d",&n,&m);

	for(int i=0;i<m;i++){
		fscanf(fin,"%d %d %d",&x,&y,&c);
		g[x].push_back(make_pair(y,c));
	}

	if(!bellmanford()){
		fprintf(fout,"Ciclu negativ!\n");
	}else{
		for(int i=2;i<=n;i++){
			fprintf(fout,"%d ",d[i]);
		}
	}

	fclose(fin);
	fclose(fout);
	return 0;
}