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?- A. 21
- B. 1
- C. 6
- 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
- Problem: Count the nodes at depth exactly 2 in the rooted tree with children 0: [1, 2], 1: [3], 2: [4, 5], 3: [], 4: [], 5: []. Root 0 has…
- Problem: How many integers from 1 to 1000 are divisible by 3 or by 5 but not by both?
- Problem: What is the product of the distinct prime factors of 360? Run the code. python n = 360 p, prod = 2, 1 while p p <= n: if n % p ==…
- Problem: What is the sum of all primes up to 50? Run the code. python print(sum(p for p in range(2, 51) if all(p % d for d in range(2…
- Problem: What is C(20, 10) mod 1000? Compute it with Pascal's triangle reduced mod 1000. Run the code. python n, k = 20, 10 C = [[0] (k +…
- Problem: How many distinct palindromes can be formed by rearranging the letters of 'aabb' (distinct strings, all letters used)? Run the…