Pagini recente » Cod sursa (job #2144386) | Cod sursa (job #1526045) | Cod sursa (job #1849804) | Cod sursa (job #462997) | Cod sursa (job #1145233)
#include<iostream>
#include<cstdio>
#define MAXIM 2147483647
#include<vector>
#include<queue>
using namespace std;
vector<pair<int, int> > a[50001];
queue<int>q;
int main()
{
int i, j, prim, ultim, viz[50001], d[50001], nr[50001], x, y, c, n, m;
FILE *fin, *fout;
fin=fopen("bellmanford.in", "r");
fout=fopen("bellmanford.out", "w");
fscanf(fin, "%d %d", &n, &m);
for(i=0; i<m; i++) {
fscanf(fin, "%d %d %d", &x, &y, &c);
a[x-1].push_back(make_pair(y-1, c));
}
for(i=0; i<n; i++) {
d[i]=MAXIM;
viz[i]=0;
nr[i]=0;
}
q.push(0);
viz[0]=1;
d[0]=0;
int ok=1;
while(!q.empty() && ok==1) {
for(i=0; i<a[q.front()].size(); i++)
if(d[q.front()]<MAXIM)
if(d[a[q.front()][i].first] > d[q.front()]+a[q.front()][i].second) {
d[a[q.front()][i].first] = d[q.front()]+a[q.front()][i].second;
if(viz[a[q.front()][i].first]==0) {
if(nr[a[q.front()][i].first]>n)
ok=0;
else {
q.push(a[q.front()][i].first);
viz[a[q.front()][i].first]=1;
nr[a[q.front()][i].first]++;
ultim++;
}
}
}
viz[q.front()]=0;
q.pop();
}
if(ok==0)
fprintf(fout, "Ciclu negativ!\n");
else
for(i=1; i<n; i++)
fprintf(fout, "%d ", d[i]);
}