Pagini recente » Cod sursa (job #1896585) | Cod sursa (job #2065948) | Cod sursa (job #664645) | Cod sursa (job #2026730) | Cod sursa (job #442043)
Cod sursa(job #442043)
#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[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{
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;
}