Pagini recente » Cod sursa (job #231479) | Cod sursa (job #2387725) | Cod sursa (job #2839639) | Cod sursa (job #2000638) | Cod sursa (job #566881)
Cod sursa(job #566881)
#include <iostream>
#include <vector>
#include <cstdio>
#include <queue>
#include <bitset>
using namespace std;
const int INF=1<<30;
int n,m;
bool negative=false;
vector< pair<int,int> > a[50005];
int dist[50005];
int cycle[50005];
void readData(){
int i,x,y,c;
freopen("bellmanford.in","r",stdin);
scanf("%d %d",&n,&m);
for(i=0;i<m;++i){
scanf("%d %d %d",&x,&y,&c);
a[x].push_back(make_pair(y,c));
}
}
void bellmanFord(){
queue< int > q; int x,i;
bitset< 50005 > inq(false);
for(i=2;i<=n;++i)
dist[i]=INF;
dist[1]=0;
q.push(1);
inq[1].flip();
while(!q.empty() && !negative){
x=q.front();
q.pop();
inq[x]=false;
for(i=0;i<a[x].size();++i) if(dist[x]<INF)
if(dist[x]+a[x][i].second < dist[a[x][i].first]){
dist[a[x][i].first]=dist[x]+a[x][i].second;
if(!inq[a[x][i].first])
if(cycle[a[x][i].first]>n)
negative=true;
else{
q.push(a[x][i].first);
++cycle[a[x][i].first];
inq[a[x][i].first]=true;
}
}
}
}
void writeData(){
int i;
freopen("bellmanford.out","w",stdout);
if(!negative)
for(i=2;i<=n;++i)
printf("%d ",dist[i]);
else printf("Ciclu Negativ!\n");
}
int main(){
readData();
bellmanFord();
writeData();
/* int i,j;
for(i=1;i<=n;++i)
for(j=0;j<a[i].size();++j)
printf("%d %d %d\n",i,a[i][j].first,a[i][j].second);
*/
return 0;
}