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?- A. 2
- B. 1
- C. 3
- 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
- Problem: A grid of 0/1 costs (a cell costs its value when you enter it) is solved by 0-1 BFS from the top-left cell to the bottom-right…
- Problem: Junctions 1..6 form a precedence graph with edges 4 to 1, 3 to 1, 2 to 5 (an edge a to b means a must come before b). Kahn's…
- Problem: Kruskal's algorithm with union-find is run on 5 nodes (0..4) with weighted edges (4,0,1), (1,1,2), (3,0,2), (2,2,3), (7,3,4)…
- Problem: Count the subsets (including the empty subset) of {1, 2, 3, 4, 5, 6} whose sum is divisible by 3. python a = [1, 2, 3, 4, 5, 6]…
- Problem: How many integers x with 1 <= x <= 100 have no two adjacent equal decimal digits? Use the rule that a one-digit number always…
- Problem: What is the sum of all divisors of 360 = 2^3 3^2 5?