Cod sursa(job #399752)
#include <iostream>
using namespace std;
const int inf = 10000;
struct graf{
int vc, cost;
graf *next;
} *L[250];
int d[300], n,m;
void add(graf *&prim, int vc, int c)
{
graf *q= new graf;
q -> vc = vc;
q-> cost = c,
q->next = prim;
prim = q;
}
void citire()
{
freopen("bellmanford.in", "r", stdin);
scanf("%d%d", &n, &m);
d[1] = 0;
for(int i=2;i<=n;i++)
d[i] = inf;
for(int i = 1; i<=m; i++)
{
int x, y,c;
scanf("%d%d%d", &x, &y, &c);
add(L[x], y, c);
if(x == 1)
d[y] = c;
}
}
void bellman()
{
int ok;
do {
ok = 0;
for(int k=1;k<=n;k++)
for(graf *p = L[k];p;p= p->next)
if( d[p->vc] > d[k] + p->cost)
{
d[p->vc] = d[k] + p->cost /*pre[p->vc] = k*/;
ok = 1;
}
}while(ok == 0);
}
int circuit()
{
for(int k=1;k<=n;k++)
for(graf *p = L[k];p;p= p->next)
if( d[p->vc] > d[k] + p->cost)
return 0;
return 1;
}
/*
void afisare()
{
}*/
int main()
{
freopen("bellmanford.out", "w", stdout);
citire();
bellman();
if(circuit() == 0)
printf("ciclu negativ!");
else
for(int i=2;i<=n;i++)
printf("%d ",d[i]);
return 0;
}