Data Structures & AlgorithmsVery hardCodeforces Div 2 C · GATE CS

Floyd–Warshall runs on vertices 1 to 4 with these arcs u→v (weight): 1→3 (1), 1→4 (4), 2→1 (1), 2→3 (3), 3→1 (12), 3→2 (11), 3→4 (3), 4→1 (9), 4→3 (3). dist[i][i] = 0, dist[i][j] is the arc weight, or ∞ when there is no arc. The outer loop runs over k = 1, 2, … in that order. After the iterations for k = 1 through 3 have finished, what is dist[1][2]?

  1. A. ∞
  2. B. 11
  3. C. 12
  4. D. 18

Correct answer: C. 12

After rounds k = 1..3, only vertices 1 to 3 may sit inside a path. Vertex 1 reaches 2 only through 3: 1→3 (1) + 3→2 (11) = 12, available once k = 3 has run. Stopping after k = 2 leaves ∞, 11 reads just the arc 3→2, and 18 detours through vertex 4, which is not yet allowed and longer anyway.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic