Data Structures & AlgorithmsHardCodeforces Div 2 C · GATE CS

A tree has vertices A, C, G, J, N, Q, X, Y and weighted edges (weights in brackets): Y–Q (2), Y–X (5), Y–J (2), J–C (2), C–A (8), X–G (7), X–N (4). What is the largest possible distance between two vertices, where distance is the sum of edge weights on the unique path?

  1. A. 5
  2. B. 12
  3. C. 24
  4. D. 22

Correct answer: C. 24

Two DFS passes (or a DP over subtrees) give the weighted diameter 24. The farthest distance from Y is only 12, and counting edges instead of weights gives 5.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic