Pagini recente » Cod sursa (job #568210) | Borderou de evaluare (job #1749062) | Cod sursa (job #2096742) | Cod sursa (job #930810) | Cod sursa (job #3239400)
#include <bits/stdc++.h>
using namespace std;
const int MAX = 50005;
vector<pair<int,int>> graph[MAX];
vector<long long> dist, cnt;
int n, m;
int bellman_ford()
{
queue<int> q;
q.push(1);
dist[1] = 0;
while (!q.empty())
{
int node = q.front();
q.pop();
for (pair<int,int> next : graph[node])
{
if (dist[next.first] > dist[node] + next.second)
{
dist[next.first] = dist[node] + next.second;
q.push(next.first);
++cnt[next.first];
if (cnt[next.first] > n)
return 0;
}
}
}
return 1;
}
int main()
{
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
cin >> n >> m;
dist.assign(n+1, LLONG_MAX);
cnt.assign(n+1, 0);
for (int i = 1; i <= m; ++i)
{
int x, y, cost;
cin >> x >> y >> cost;
graph[x].push_back({y, cost});
}
if (!bellman_ford())
cout << "Ciclu negativ!";
else
for (int i = 2; i <= n; ++i)
cout << dist[i] << " ";
return 0;
}