Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

A directed weighted graph has edges 0→1 (2), 0→2 (2), 1→3 (1), 2→3 (1), 1→4 (4), 2→4 (5), 3→4 (3), 3→5 (4), 4→5 (1). Count the number of distinct shortest paths from 0 to 5, where paths are sequences of edges and equal-length alternatives all count.

A directed weighted graph has edges 0→1 (2), 0→2 (2), 1→3 (1), 2→3 (1), 1→4 (4), 2→4 (5), 3→4 (3), 3→5 (4), 4→5 (1). Count the number of distinct shortest paths from 0 to 5, where paths are sequences of edges and equal-length alternatives all count.
import heapq
E={0:[(1,2),(2,2)],1:[(3,1),(4,4)],2:[(3,1),(4,5)],3:[(4,3),(5,4)],4:[(5,1)],5:[]}
INF=float('inf'); d={v:INF for v in E}; cnt={v:0 for v in E}
d[0]=0; cnt[0]=1; h=[(0,0)]
while h:
    du,u=heapq.heappop(h)
    if du>d[u]: continue
    for v,w in E[u]:
        if du+w<d[v]: d[v]=du+w; cnt[v]=cnt[u]; heapq.heappush(h,(d[v],v))
        elif du+w==d[v]: cnt[v]+=cnt[u]
print(cnt[5])
What is printed?
  1. A. 7
  2. B. 1
  3. C. 5
  4. D. 13

Correct answer: C. 5

Dijkstra with a path counter: an improvement resets the count, and an equal distance adds the predecessor's count. Ignoring ties undercounts, reporting the distance is a different quantity, and adding on improvement overcounts paths that were already discarded.

More Coding Interview Problems questions

Exams that ask this topic