Pagini recente » Cod sursa (job #2270897) | Cod sursa (job #2232044) | Cod sursa (job #201857) | Cod sursa (job #745914) | Cod sursa (job #2103752)
#include <iostream>
#include <vector>
#include <cstdio>
#include <queue>
#define N 50005
using namespace std;
vector <pair<int, int> > graf[N];
queue <int> q;
int cost[N], n, m, a, b, c, viz[N];
void citire()
{
scanf("%d %d\n", &n, &m);
for(int i=1;i<=m;i++)
{
cost[i]=0x3f3f3f;
scanf("%d %d %d", &a, &b, &c);
graf[a].push_back(make_pair(b, c));
}
}
void parcurg(int x)
{
for(vector <pair<int, int> > :: iterator it=graf[x].begin();it!=graf[x].end();it++)
{
if(cost[x]+it->second<cost[it->first])
{
cost[it->first]=cost[x]+it->second;
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();
cost[1]=0;
q.push(1);
while(!q.empty())
{
int x=q.front();
viz[x]++;
if(viz[x]==n)
{
printf("Ciclu negativ!");
return 0;
}
q.pop();
parcurg(x);
}
afisare();
return 0;
}