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