Pagini recente » Cod sursa (job #1837968) | Cod sursa (job #5990) | Cod sursa (job #887513) | Cod sursa (job #2301940) | Cod sursa (job #2353500)
#include <iostream>
#include <cstdio>
#include <queue>
#define inf 0x3f3f3f3f
#define N 50005
using namespace std;
int n, m, cost[N], viz[N];
struct nod
{
int y, c;
};
vector <nod> g[N];
vector <nod> ::iterator it;
queue <int> q;
void citire()
{
scanf("%d %d\n", &n, &m);
for(int i=0;i<m;i++)
{
int xx, yy, cc;
cost[i]=inf;
scanf("%d %d %d\n", &xx, &yy, &cc);
g[xx].push_back({yy, cc});
}
}
void parcurg(int x)
{
for(it=g[x].begin();it!=g[x].end();it++)
if(cost[it->y]>cost[x]+it->c)
{
cost[it->y]=cost[x]+it->c;
q.push(it->y);
}
}
void afisare()
{
for(int i=2;i<=n;i++)
printf("%d ", cost[i]);
}
void bellman()
{
q.push(1);
cost[1]=0;
while(!q.empty())
{
int x=q.front();
q.pop();
if(viz[x]==n)
{
printf("Ciclu negativ!");
return;
}
viz[x]++;
parcurg(x);
}
afisare();
}
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
citire();
bellman();
return 0;
}