Pagini recente » Cod sursa (job #1604024) | Cod sursa (job #1842133) | Monitorul de evaluare | Cod sursa (job #1418943) | Cod sursa (job #3319417)
#include <fstream>
#include <vector>
#include <climits>
#include <bitset>
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
int n, m;
vector<vector<pair<int ,int>>> graph;
vector<int> dist;
vector<int> cnt;
queue<int> q;
bitset<(int)(5e4 + 5)> in_queue;
bool spfa() {
dist[1] = 0;
q.push(1);
in_queue[1] = true;
while (!q.empty()) {
int current_node = q.front();
q.pop();
in_queue[current_node] = false;
for (auto [neighbour_node, cost] : graph[current_node]) {
if (dist[current_node] + cost < dist[neighbour_node]) {
dist[neighbour_node] = dist[current_node] + cost;
if (!in_queue[neighbour_node]) {
q.push(neighbour_node);
in_queue[neighbour_node] = true;
cnt[neighbour_node]++;
if (cnt[neighbour_node] > n) {
return false;
}
}
}
}
}
return true;
}
int main() {
cin >> n >> m;
dist.resize(n + 2, INT_MAX);
graph.resize(n + 2);
cnt.resize(n + 2, 0);
for (int i = 0 ; i < m ; ++i) {
int a, b, cost;
cin >> a >> b >> cost;
graph[a].push_back({b, cost});
}
if (!spfa()) {
cout << "Ciclu negativ!";
return 0;
}
for (int i = 2 ; i <= n ; ++i) {
cout << dist[i] << " ";
}
return 0;
}