G - Road Blocked 2 Editorial by LinLeXiao

Alternative Solution

It’s easy to calculate the number of different shortest paths from a certain starting point using Dijkstra.

Let’s say cnt1icnt1_i represents the number of different shortest paths from vertex 11 to vertex ii, and d1id1_i represents the minimal distance from vertex 11 to vertex ii.

Similarly, let cnt2icnt2_i represent the number of different shortest paths from vertex nn to vertex ii, and d2id2_i represent the minimal distance from vertex nn to vertex ii.

A key insight is that, for a bidirectional edge (u,v)(u,v) with weight ww, if the number of shortest path from 11 to nn that pass (u,v)(u,v) equals cnt1ncnt1_n implies all shortest paths include this edge, thus the answer is Yes.

Specifically, the answer for such an edge is Yes if either of the following holds:

  • d1u+d2v+w=d1nd1_u + d2_v + w = d1_n and cnt1u×cnt2v=cnt1ncnt1_u \times cnt2_v = cnt1_n

  • d1v+d2u+w=d1nd1_v + d2_u + w = d1_n and cnt1v×cnt2u=cnt1ncnt1_v \times cnt2_u = cnt1_n

The only problem is that the number of different shortest paths may be too large to store. To solve this, use multi-hashing, and the problem can be easily solved.

Sample code

posted:
last update:



2025-04-08 (Tue)
22:13:20 +00:00