Data Structures & AlgorithmsVery hardICPC regional · shortest path with edge limit

Problem: Find the minimum cost to reach node 3 from node 0 using at most 2 edges in the directed graph with edges (0,1,5), (1,3,5), (0,2,20), (2,3,1). Run the Bellman-Ford DP restricted to k = 2 rounds.

Problem: Find the minimum cost to reach node 3 from node 0 using at most 2 edges in the directed graph with edges (0,1,5), (1,3,5), (0,2,20), (2,3,1). Run the Bellman-Ford DP restricted to k = 2 rounds.
edges = [(0, 1, 5), (1, 3, 5), (0, 2, 20), (2, 3, 1)]
INF = float('inf')
d = [0, INF, INF, INF]
for _ in range(2):
    nd = d[:]
    for u, v, w in edges:
        if d[u] + w < nd[v]:
            nd[v] = d[u] + w
    d = nd
print(d[3])
What is printed?
  1. A. 21
  2. B. 1
  3. C. 6
  4. D. 10

Correct answer: D. 10

Two edges cost 5 + 5 = 10 via 0->1->3, while the direct 0->2->3 route with weight 21 is more expensive. The copy nd keeps each round to paths with at most one more edge.

More Coding Interview Problems questions

Exams that ask this topic