Pagini recente » Cod sursa (job #2724462) | Cod sursa (job #1740289) | Cod sursa (job #2620582) | Cod sursa (job #959471) | Cod sursa (job #3138506)
#include <bits/stdc++.h>
using namespace std;
using llx = long long;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int inf = 1'000'000'000;
vector<vector<pair<int, int>>> v;
vector<int> dist;
bool bellman_ford(int n)
{
queue<int> q;
vector<bool> in_queue;
vector<int> opt;
int na, x, y;
dist.assign(n+1, inf), opt.assign(n+1, 0), in_queue.assign(n+1, 0);
dist[1] = 0;
q.push(1);
in_queue[1] = 1;
while (q.empty() == 0)
{
na = q.front();
q.pop();
in_queue[na] = 0;
for (const auto &pairv : v[na])
{
tie(x, y) = pairv;
if (dist[x] > dist[na] + y)
{
dist[x] = dist[na] + y;
if (in_queue[x] == 0)
{
q.push(x);
in_queue[x] = 1;
opt[x]++;
if (opt[x] >= n)
return 0;
}
}
}
}
return 1;
}
int main()
{
int n, m, i, x, y, z;
fin >> n >> m;
v.resize(n+1);
for (i = 1; i<=m; i++)
{
fin >> x >> y >> z;
v[x].push_back({y, z});
}
if (bellman_ford(n) == 0)
fout << "Ciclu negativ!";
else
for (i = 2; i<=n; i++)
fout << dist[i] << ' ';
return 0;
}