Pagini recente » Cod sursa (job #3362348) | Cod sursa (job #3362023) | Cod sursa (job #3362350) | Cod sursa (job #3362026) | Cod sursa (job #3362337)
#include <bits/stdc++.h>
using namespace std;
const int N = 5e4 + 1, INF = 2e9 + 1;
int n, m, x, y, c, dist[N], vis[N];
vector<pair<int, int>> mc[N];
queue<int> q;
bool bf()
{
for (int i = 2; i <= n; ++i)
dist[i] = INF;
q.push(1);
while (!q.empty())
{
int nod = q.front();
q.pop();
vis[nod]++;
if (vis[nod] == n + 1)
return false;
for (auto f : mc[nod])
{
if (dist[nod] + f.second < dist[f.first])
{
dist[f.first] = dist[nod] + f.second;
q.push(f.first);
}
}
}
return true;
}
int main()
{
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= m; ++i)
{
cin >> x >> y >> c;
mc[x].push_back({y, c});
}
if (!bf())
{
cout << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; ++i)
{
cout << dist[i] << ' ';
}
}
return 0;
}