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; + } +}