Pagini recente » Cod sursa (job #1992729) | Cod sursa (job #2638866) | Cod sursa (job #438482) | Cod sursa (job #2797263) | Cod sursa (job #2575765)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int nmax = 50005;
const int inf = (1 << 30);
int n, m;
struct Point
{
int to, cost;
};
vector < Point > l[nmax];
queue < int > q;
bitset < nmax > viz;
int cnt[nmax], dist[nmax];
int main()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
l[x].push_back({y, c});
}
for (int i = 2; i <= n; i++)
dist[i] = inf;
q.push(1);
cnt[1] = 1;
viz[1] = 1;
int nod;
while (!q.empty())
{
nod = q.front();
q.pop();
viz[nod] = 0;
for (Point p : l[nod])
{
if (dist[p.to] > dist[nod] + p.cost)
{
dist[p.to] = dist[nod] + p.cost;
if (!viz[p.to])
{
viz[p.to] = 1;
cnt[p.to]++;
if (cnt[p.to] > n)
{
fout << "Ciclu negativ!";
fin.close();
fout.close();
return 0;
}
q.push(p.to);
}
}
}
}
for (int i = 2; i <= n; i++)
fout << dist[i] << ' ';
fin.close();
fout.close();
return 0;
}