Pagini recente » Borderou de evaluare (job #1567371) | Cod sursa (job #3124478) | Borderou de evaluare (job #127316) | Cod sursa (job #1970242) | Cod sursa (job #3271786)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int lmax=1e5;
const int INF = INT_MAX;
struct Edge {
int x, y, c;
};
bool cmp(Edge a, Edge b) {
return a.c < b.c;
}
int dist[lmax];
int parinte[lmax + 1];
std::vector<Edge> edges;
bool bellman_ford_heap(int s, int n) {
std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> pq;
std::fill(dist, dist + n + 1, INF);
std::fill(parinte, parinte + n + 1, -1);
std::vector<bool> inQueue(n + 1, false);
dist[s] = 0;
pq.push({0, s});
inQueue[s] = true;
while (!pq.empty()) {
int d = pq.top().first;
int u = pq.top().second;
pq.pop();
inQueue[u] = false;
// Skip processing if this entry is outdated
if (d > dist[u]) continue;
for (auto& edge : edges) {
if (edge.x == u) {
int v = edge.y, weight = edge.c;
if (dist[u] != INF && dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
parinte[v] = u;
if (!inQueue[v]) {
pq.push({dist[v], v});
inQueue[v] = true;
}
}
}
}
}
// Check for negative cycles
for (auto& edge : edges) {
if (dist[edge.x] != INF && dist[edge.x] + edge.c < dist[edge.y]) {
return false; // Negative cycle detected
}
}
return true;
}
int main() {
int n, m;
fin >> n >> m;
edges.resize(m);
for (int i = 0; i < m; i++) {
fin >> edges[i].x >> edges[i].y >> edges[i].c;
}
if (bellman_ford_heap(1, n)) {
for (int i = 2; i <= n; i++) {
fout << (dist[i] == INF ? 0 : dist[i]) << " ";
}
} else {
fout << "Ciclu negativ!";
}
}