Data Structures & AlgorithmsHardCodeforces Div2 C · GATE CS

A tree has these parent→child edges: 42→41, 40→42, 42→93, 89→65, 41→8, 65→21, 93→34, 41→49, 8→89. The distance between two nodes is the number of edges on the path between them. Let W be the sum of the distances over all unordered pairs of distinct nodes. What is W?

  1. A. 274
  2. B. 29
  3. C. 61
  4. D. 137

Correct answer: D. 137

Each edge contributes s·(n−s) to W, where s is the number of nodes on the child side of that edge. Doubling for ordered pairs or summing depths from the root measures other things.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic