Graph Theory37 sections · 1633 units
Open in Course

CSES 1197 Cycle Finding - Parent Tracking

(Reconstructing the cycle)

When you relax an edge uvu \to v, store parent[v] = u. This lets you trace back the path that created the current distance. Parent pointers form a tree of shortest paths from the source. If the nn-th iteration improves distance to node vv, you know vv is affected by a negative cycle.

Trace back from vv using parent pointers to find the cycle. After tracing back nn steps, you are guaranteed to be inside the cycle. This is because any path longer than n1n-1 edges must contain a repeated node, which forms a cycle.