Data Structures & AlgorithmsVery hardCodeforces Div2 C · GATE CS

A tree has these parent→child edges: 39→43, 98→31, 98→63, 31→52, 61→32, 61→6, 6→26, 7→98, 98→39, 98→61. 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. 142
  2. B. 284
  3. C. 25
  4. D. 85

Correct answer: A. 142

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