Cod sursa(job #442032)

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

#define INF 0x3f3f3f3f
#define MAXN 50005
#define MAXM 250005

typedef vector<pair<int,int> >::iterator iter;
vector<pair<int,int> > g[MAXN];
bitset<MAXN> inList;

int n,m,cn=0,d[MAXN],list[MAXN],cycle[MAXN],lp=0;

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

	for(int i=2;i<=n;i++){
		d[i]=INF;
	}
	d[1]=0,list[++lp]=1,inList[1]=true;
	
	while(lp>0&&!neg){
		top=list[lp--];
		inList[top]=false;
		for(iter it=g[top].begin();it!=g[top].end();it++){
			if(dist[top]<INF){
				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{
							list[++lp]=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",&n,&m);

	for(int i=0;i<m;i++){
		fscanf(fin,"%d %d %d\n",&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]==INF)?0:d[i]);
		}
	}

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