Pagini recente » Cod sursa (job #220217) | Cod sursa (job #134133) | Cod sursa (job #225495) | Cod sursa (job #68274) | Cod sursa (job #659805)
Cod sursa(job #659805)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
#define maxN 250005
#define INF 0x3f3f3f3f
vector < pair <int , int> > lista[maxN];
queue <int> Q;
int cost[maxN] , cost_aux , noduri[maxN];
int N , M;
int main ()
{
freopen ("bellmanford.in" , "r" , stdin);
freopen ("bellmanford.out" , "w" , stdout);
scanf ("%d %d" , &N , &M);
int a , b , c;
for (int i = 1 ; i <= M ; ++i)
{
scanf ("%d %d %d" , &a , &b , &c);
lista[a].push_back (make_pair (b , c));
}
for (int i = 1 ; i <= N ; ++i)
cost[i] = INF;
int nod;
Q.push (1);
cost[1] = 0;
while (!Q.empty ())
{
nod = Q.front ();
for (unsigned i = 0 ; i < lista[nod].size () ; ++i)
{
cost_aux = cost[nod] + lista[nod][i].second;
if (cost[lista[nod][i].first] > cost_aux)
{
cost[lista[nod][i].first] = cost_aux;
noduri[lista[nod][i].first]++;
if (noduri[lista[nod][i].first] > N)
{
printf ("Ciclu negativ!");
return 0;
}
Q.push (lista[nod][i].first);
}
}
Q.pop ();
}
for (int i = 2 ; i <= N ; ++i)
if (cost[i] != INF)
printf ("%d " , cost[i]);
else printf ("0 ");
return 0;
}