Graph Theory37 sections · 1633 units
Open in Course

CSES 1672 Shortest Routes II - Why Floyd-Warshall Fits

(All-pairs in one shot)

Shortest Routes II gives you qq queries for shortest paths. If qq is large, running Dijkstra for each query is too slow.

Instead, run Floyd-Warshall once in O(n3)O(n^3) to precompute all distances. Then answer each query in O(1)O(1) by indexing the distdist array. Total time: O(n3+q)O(n^3 + q). This beats O(qnlogn)O(q \cdot n \log n) when qq is large. The pattern is: expensive preprocessing, cheap queries. Recognize this pattern and you will know when to use Floyd-Warshall.

Space complexity is O(n2)O(n^2) for the data structures used.