Graph Theory37 sections · 1633 units
Open in Course

CSES 1197 Cycle Finding - Algorithm

(Detection and extraction)

1.1. Run Bellman-Ford for n1n-1 iterations, tracking parent pointers.

2.2. On the nn-th iteration, find any node vv where distance improves. If none, no negative cycle exists.

3.3. Walk back nn steps from vv using parents to get inside the cycle.

4.4. From that node, follow parents and collect nodes until you see a repeat. That sequence is the cycle.

5.5. Output the cycle in correct order by reversing the collected sequence.

The double-walk approach (first nn steps to enter cycle, then loop to extract it) guarantees correct cycle extraction.