Skip to main content
1 of 2
D.W.
  • 165.6k
  • 21
  • 230
  • 490

Since this is a contest problem, I'll just give a hint at one possible approach.

It sounds like you know how to efficiently answer queries of the form "how many vertices are of distance $\le d$ from $v$ and are within the subtree under $w$?".

So, try using that as a subroutine. Assume this is a rooted binary tree. Look at the path from $v$ to the root. In particular, consider $v$'s sibling, $v$'s father's sibling, $v$'$ grandfather's sibling, and try issuing an appropriate query for each. What will the running time be? Does this give you any tips on how to choose the root to make the resulting algorithm efficient?

D.W.
  • 165.6k
  • 21
  • 230
  • 490