Pagini recente » Cod sursa (job #1979283) | Cod sursa (job #740637) | Cod sursa (job #3318368) | Cod sursa (job #2501154) | Cod sursa (job #3348210)
#include <iostream>
#include <queue>
#include <vector>
const int MAX_N = 50000;
const int MAX_M = 250000;
const int INF = 1e9;
struct Edge {
int v, c;
};
struct Node {
std::vector<Edge> adj;
bool enqueued;
int relax_count;
int d;
};
int n, m;
Node a[MAX_N + 1];
std::queue<int> q;
void read_graph() {
for (int i = 0; i < m; i++) {
int u, v, c;
std::cin >> u >> v >> c;
a[u].adj.push_back({ v, c });
}
}
// returns true if there is a negative cycle
bool spfa() {
a[1].d = 0;
q.push(1);
a[1].enqueued = true;
while (!q.empty()) {
int u = q.front();
q.pop();
a[u].enqueued = false;
for (auto [v, c] : a[u].adj) {
if (a[u].d + c < a[v].d) {
a[v].d = a[u].d + c;
if (!a[v].enqueued) {
q.push(v);
a[v].enqueued = true;
a[v].relax_count++;
if (a[v].relax_count > n) {
return true; // negative cycle
}
}
}
}
}
return false;
}
void print_distances() {
for (int i = 2; i <= n; i++) {
std::cout << a[i].d << ' ';
}
}
void reset_distances() {
for (int i = 1; i <= n; i++) {
a[i].d = INF;
}
}
int main() {
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
std::cin >> n >> m;
read_graph();
reset_distances();
if (spfa()) {
std::cout << "Ciclu negativ!";
} else {
print_distances();
}
}