Skip to main content
2 of 2
added 164 characters in body
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?

Update: This doesn't suffice for $O(n \lg n)$ running time, because there may be no way to choose the root so that the average depth of a random leaf is $o(n)$.

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