Pagini recente » Cod sursa (job #2610271) | Cod sursa (job #2990794) | Cod sursa (job #3279714) | Cod sursa (job #1206188) | Cod sursa (job #566895)
Cod sursa(job #566895)
#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,j,c;
bitset< 50005 > inq(false);
for(i=2;i<=n;++i)
dist[i]=INF;
dist[1]=0;
q.push(1);
inq[1]=true;
while(!q.empty() && !negative){
x=q.front();
q.pop();
inq[x]=false;
for(i=0;i<a[x].size();++i){
j=a[x][i].first; c=a[x][i].second;
if(dist[x]+c<dist[j]){
dist[j]=dist[x]+c;
if(!inq[j]){
if(cycle[j]>n)
negative=true;
q.push(j);
cycle[j]++;
inq[j]=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!");
}
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;
}