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?- A. 7
- B. 1
- C. 5
- 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
- On vertices 0..4 a weighted directed graph has these edges, stored in the order shown in the code: (3→4, −2), (2→4, 8), (4→1, 2), (1→3…
- A task graph has six nodes 0 to 5 and dependencies 5→0, 4→0, 4→1, 5→2, 2→3, 3→1 (an edge u→v means u must finish before v). Among all…
- Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and…
- Compute the sum over all subarrays of the minimum element, for a = [3, 1, 2, 1, 3]. Subarrays are counted by position, so equal values in…
- Find the sum of the maximum of every window of length 3 in a = [1, 3, −1, −3, 5, 3, 6, 7] (windows slide one step at a time). python…
- In the reflected binary Gray code, the number with index i is i XOR (i >> 1). Using 0-based indices, what is the value printed for i = 5…