Pagini recente » Cod sursa (job #690128) | Cod sursa (job #571139) | Cod sursa (job #130920) | Cod sursa (job #1537377) | Cod sursa (job #3215101)
#include <fstream>
#include <queue>
#define MAX 50000
#define INF 1000000000
using namespace std;
ifstream cin ("bellmanford.in");
ofstream cout ("bellmanford.out");
int dist[MAX + 10], inQueue[MAX + 10], used[MAX + 10];
vector <pair <int, int>> graph[MAX + 10];
queue <int> q;
int main()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
cin >> x >> y >> c;
graph[x].push_back({c, y});
}
for (int i = 2; i <= n; i++)
dist[i] = INF;
q.push(1);
inQueue[1] = 1;
used[1] = 1;
int foundCycle = 0;
while (!q.empty() && foundCycle == 0)
{
int node = q.front();
q.pop();
inQueue[node] = 0;
for (const auto &it : graph[node])
{
int cost = it.first;
int next = it.second;
if (dist[next] > dist[node] + cost)
{
dist[next] = dist[node] + cost;
if (inQueue[next] == 0)
{
q.push(next);
inQueue[next] = 1;
used[next]++;
if (used[next] > n)
foundCycle = 1;
}
}
}
}
if (foundCycle == 1)
cout << "Ciclu negativ!";
else
for (int i = 2; i <= n; i++)
cout << dist[i] << ' ';
return 0;
}