Pagini recente » Cod sursa (job #1513330) | Cod sursa (job #2147571) | Cod sursa (job #2632530) | Cod sursa (job #2700235) | Cod sursa (job #1962432)
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#define NMAX 50005
#define inf 0x3f3f3f
using namespace std;
int n, m, distanta[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);
int x, y, c;
for(int i=1; i<=m; ++i)
{
scanf("%d%d%d", &x, &y, &c);
g[x].push_back(make_pair(y, c));
}
for(int i=2; i<=n; ++i)
distanta[i]=inf;
}
int bellmanFord()
{
q.push(1);
int nod;
while(!q.empty())
{
nod=q.front();
q.pop();
for(it=g[nod].begin(); it!=g[nod].end(); ++it)
if(distanta[nod] + it->second < distanta[it->first])
{
distanta[it->first] = distanta[nod] + it->second;
nrTreceri[it->first]++;
if(nrTreceri[nod]>n)
return 0;
q.push(it->first);
}
}
return 1;
}
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
read();
if(bellmanFord())
for(int i=2; i<=n; ++i)
printf("%d ", distanta[i]);
else
printf("Ciclu negativ!");
return 0;
}