Data Structures & AlgorithmsVery hardICPC regional · Product Company SDE

Problem: A directed graph has 4 vertices (0–3) and arcs with weights: 0→1 (4), 1→2 (−3), 0→2 (2), 2→3 (1), 1→3 (5), 3→1 (−1). Start with distance 0 at vertex 0 and infinity elsewhere. Run Bellman–Ford for exactly 2 rounds; each round relaxes all arcs once, in the order listed above. Count the successful relaxations, meaning the arcs that strictly lower some distance, over both rounds together.

  1. A. 7
  2. B. 4
  3. C. 10
  4. D. 12

Correct answer: A. 7

Round 1 lowers d1 = 4, d2 = 1, d3 = 2, d1 = 1 (4 relaxations); round 2 lowers d2 = −2, d3 = −1, d1 = −2 (3 more), so 7 — the cycle 1→2→3→1 has weight −3 and keeps improving. One round gives 4, three rounds give 10, and 12 counts every arc examined.

More Coding Interview Problems questions

Exams that ask this topic