Pagini recente » Cod sursa (job #499316) | Cod sursa (job #1389230) | Cod sursa (job #2113095) | Cod sursa (job #1391523) | Cod sursa (job #1412051)
#include <bits/stdc++.h>
#define oo 1<<30
#define pb push_back
#define mp make_pair
#define N 50005
using namespace std;
vector<pair<int, int>>v[N];
int d[N], cnt[N], i, n, m, x, y, c, nod;
queue<int>q;
bitset<N>inq;
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
scanf("%d%d", &n, &m);
for(; m; m--)
{
scanf("%d%d%d", &x, &y, &c);
v[x].pb(mp(y, c));
}
for(i = 2; i <= n; i++)
d[i] = oo;
q.push(1);
inq[1] = 1;
d[1] = 0;
while(q.size())
{
nod = q.front();
q.pop();
inq[nod] = 0;
for(auto it : v[nod])
if(d[it.first] > d[nod] + it.second)
{
d[it.first] = d[nod] + it.second;
if(inq[it.first])
continue;
cnt[it.first]++;
if(cnt[it.first]>n)
{
printf("Ciclu negativ!");
return 0;
}
q.push(it.first);
inq[it.first] = 1;
}
}
for(i = 2; i <= n; i++)
printf("%d ", d[i]);
return 0;
}