Pagini recente » Cod sursa (job #1284229) | Cod sursa (job #1016002) | Cod sursa (job #1864938) | Cod sursa (job #1506582) | Cod sursa (job #876816)
Cod sursa(job #876816)
#include<stdio.h>
#include<vector>
#include<queue>
#define INF (1 << 30)
using namespace std;
vector < pair <int, int> > G[50001];
queue < int > q;
int M, i, x, y, c, m;
int N, viz[50001], d[50001];
int main () {
freopen ("bellmanford.in", "r", stdin);
freopen ("bellmanford.out", "w", stdout);
//read
scanf ("%d %d", &N, &M);
for (i = 1; i <= M; ++i) {
scanf("%d %d %d", &x, &y, &c);
G[x].push_back(make_pair(y, c));
}
//
//solve
for (i = 1; i <= N; ++i)
d[i] = INF;
d[1] = 0;
q.push(1);
int ok = 1;
while (!q.empty()) {
x = q.front();
q.pop();
m = G[x].size();
for (i = 0; i < m; ++i) {
y = G[x][i].first;
c = G[x][i].second;
if (d[y] > d[x] + c) {
d[y] = d[x] + c;
q.push(y);
++viz[x];
}
}
if (viz[x] > N)
ok = 0;
}
//
//print
if (!ok)
printf("Ciclu negativ!\n");
else {
for (i = 2; i <= N; ++i)
if (d[i] != INF)
printf ("%d ", d[i]);
else printf("0");
}
//
return 0;
}