Pagini recente » Cod sursa (job #1519218) | Cod sursa (job #1632318) | Cod sursa (job #2339724) | Cod sursa (job #2073965) | Cod sursa (job #2126129)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#define INF 0x3f3f3f
#define NMAX 50005
using namespace std;
int N, M, dist[NMAX], nrTreceri[NMAX];
vector <pair <int, int> > G[NMAX];
vector <pair <int, int> >::iterator it;
queue <int> Q;
void read()
{
scanf("%d %d", &N, &M);
for(int i=1; i<=M; ++i)
{
int x, y, c;
scanf("%d %d %d", &x, &y, &c);
G[x].push_back(make_pair(y, c));
}
for(int i=2; i<=N; ++i)
dist[i] = INF;
}
bool bellmanFord()
{
Q.push(1);
while(!Q.empty())
{
int nod = Q.front();
Q.pop();
for(it = G[nod].begin(); it != G[nod].end(); ++it)
if(dist[it->first] > dist[nod] + it->second)
{
dist[it->first] = dist[nod] + it->second;
nrTreceri[it->first]++;
if(nrTreceri[it->first] > N)
return false;
Q.push(it->first);
}
}
return true;
}
void print()
{
for(int i=2; i<=N; ++i)
printf("%d ", dist[i]);
}
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
read();
if(bellmanFord())
print();
else
printf("Ciclu negativ!");
return 0;
}