From a65db14a555810306ec6af024bc9f0afd2e0a60b Mon Sep 17 00:00:00 2001 From: Michael Hayter Date: Tue, 15 Apr 2025 20:46:24 -0400 Subject: [PATCH] Update finding-negative-cycle-in-graph.md Resolves 1419. --- src/graph/finding-negative-cycle-in-graph.md | 21 +++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/graph/finding-negative-cycle-in-graph.md b/src/graph/finding-negative-cycle-in-graph.md index 7589c09db..a9b87c7f9 100644 --- a/src/graph/finding-negative-cycle-in-graph.md +++ b/src/graph/finding-negative-cycle-in-graph.md @@ -30,35 +30,33 @@ Do $N$ iterations of Bellman-Ford algorithm. If there were no changes on the las struct Edge { int a, b, cost; }; - -int n, m; + +int n; vector edges; const int INF = 1000000000; - + void solve() { - vector d(n, INF); + vector d(n, 0); vector p(n, -1); int x; - - d[0] = 0; - + for (int i = 0; i < n; ++i) { x = -1; for (Edge e : edges) { - if (d[e.a] < INF && d[e.a] + e.cost < d[e.b]) { + if (d[e.a] + e.cost < d[e.b]) { d[e.b] = max(-INF, d[e.a] + e.cost); p[e.b] = e.a; x = e.b; } } } - + if (x == -1) { cout << "No negative cycle found."; } else { for (int i = 0; i < n; ++i) x = p[x]; - + vector cycle; for (int v = x;; v = p[v]) { cycle.push_back(v); @@ -66,14 +64,13 @@ void solve() { break; } reverse(cycle.begin(), cycle.end()); - + cout << "Negative cycle: "; for (int v : cycle) cout << v << ' '; cout << endl; } } - ``` ## Using Floyd-Warshall algorithm