Graph Theory37 sections · 1633 units
Open in Course

CSES 1673 High Score - Two-Way Reachability

(Cycle must matter)

A negative cycle only causes infinite score if you can use it on a path from 11 to nn. The cycle must be both reachable from the source and able to reach the destination. Run BFS from node 11 to find all reachable nodes. Run BFS on the reversed graph from node nn to find all nodes that can reach nn.

A node can reach nn in the original graph if nn can reach it in the reversed graph. If a negative cycle node is both reachable from 11 and can reach nn, output 1-1. Otherwise, the cycle is irrelevant, and you output the negated shortest distance.