Data Structures & AlgorithmsVery hardICPC regional · graph round

Problem: A directed road map has junctions 0..4 and roads (u, v, w): (0,1,1), (0,2,1), (1,3,1), (2,3,1), (3,4,1), (1,2,1). Count the distinct shortest paths from 0 to 4 using this Dijkstra-with-counting code.

Problem: A directed road map has junctions 0..4 and roads (u, v, w): (0,1,1), (0,2,1), (1,3,1), (2,3,1), (3,4,1), (1,2,1). Count the distinct shortest paths from 0 to 4 using this Dijkstra-with-counting code.
import heapq
n = 5
edges = [(0, 1, 1), (0, 2, 1), (1, 3, 1), (2, 3, 1), (3, 4, 1), (1, 2, 1)]
g = [[] for _ in range(n)]
for u, v, w in edges:
    g[u].append((v, w))
    g[v].append((u, w))
INF = float('inf')
d = [INF] * n
ways = [0] * n
d[0] = 0
ways[0] = 1
pq = [(0, 0)]
while pq:
    du, u = heapq.heappop(pq)
    if du > d[u]:
        continue
    for v, w in g[u]:
        if du + w < d[v]:
            d[v] = du + w
            ways[v] = ways[u]
            heapq.heappush(pq, (d[v], v))
        elif du + w == d[v]:
            ways[v] += ways[u]
print(ways[4])
What is printed?
  1. A. 2
  2. B. 1
  3. C. 3
  4. D. 4

Correct answer: A. 2

Shortest distance from 0 to 4 is 3, achieved by 0-1-3-4 and 0-2-3-4. The edge 1-2 creates a longer route, so it adds no shortest path.

More Coding Interview Problems questions

Exams that ask this topic