From 177f34300f8ef57797deb0acb03c1fd8a9ee87b5 Mon Sep 17 00:00:00 2001 From: Edson Neto <72220739+emn2@users.noreply.github.com> Date: Tue, 5 Oct 2021 08:09:05 -0300 Subject: [PATCH] Algorithm to find negative cycles in a graph --- Graphs/negativeCycleFinding.cpp | 43 +++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Graphs/negativeCycleFinding.cpp diff --git a/Graphs/negativeCycleFinding.cpp b/Graphs/negativeCycleFinding.cpp new file mode 100644 index 0000000..0f062c8 --- /dev/null +++ b/Graphs/negativeCycleFinding.cpp @@ -0,0 +1,43 @@ +struct Edge { + ll a, b, cost; +}; + +int n, m; +vector edges; +const ll INF = 1e9 + 5; + +void solve(){ + vector d(n); + vector p(n, -1); + int x; + for (int i = 0; i < n; ++i) { + x = -1; + for (Edge e : edges) { + if (d[e.a] + e.cost < d[e.b]) { + d[e.b] = d[e.a] + e.cost; + p[e.b] = e.a; + x = e.b; + } + } + } + + if (x == -1) { + cout << "NO\n"; + } else { + for (int i = 0; i < n; ++i) + x = p[x]; + + vector cycle; + for (int v = x;; v = p[v]) { + cycle.push_back(v); + if (v == x && cycle.size() > 1) + break; + } + reverse(cycle.begin(), cycle.end()); + + cout << "YES\n"; + for (int v : cycle) + cout << v+1 << ' '; + cout << endl; + } +}