Pagini recente » Cod sursa (job #3245801) | Cod sursa (job #1187611) | Cod sursa (job #945022) | Cod sursa (job #1969623) | Cod sursa (job #3215180)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
int d[50005], cnt[50005];
vector<pair<int, int>> a[50005];
queue<int> Q;
int main()
{
int x, y, cost;
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
fin >> x >> y >> cost;
a[x].push_back({cost, y});
}
for (int i = 1; i <= n; i++)
d[i] = 2e9;
d[1] = 0;
Q.push(1);
while (!Q.empty())
{
x = Q.front();
Q.pop();
for (pair<int, int> e : a[x])
if (d[e.second] > d[x] + e.first)
{
d[e.second] = d[x] + e.first;
cnt[e.second]++;
Q.push(e.second);
if (cnt[e.second] > n)
{
fout << "Ciclu negativ!" << "\n";
return 0;
}
}
}
for (int i = 2; i <= n; i++)
fout << d[i] << " ";
fout << "\n";
return 0;
}