Блог пользователя svg_af

Автор svg_af, история, 9 лет назад, По-английски

Hello there

so i found this problem on spoj

we have a tree where each node has an integer weight and two types of queries

1- print sum of weights in subtree of given node

2- change root to given node

now first type of queries is no issue if the root is fixed ... i would solve it with segment tree, but changing the root kinda ruins everything

any hints about how i should think about this would be really appreciated :D

  • Проголосовать: нравится
  • +6
  • Проголосовать: не нравится

»
9 лет назад, # |
Rev. 2   Проголосовать: нравится +1 Проголосовать: не нравится

The answer is always size of subtree or size of all tree minus subtree.

For each query you just need to determine edge that goes to current root.

More spoilers in previous revision

»
9 лет назад, # |
Rev. 5   Проголосовать: нравится +6 Проголосовать: не нравится

Fix the root with 1.

If the root is changed to X, we can determine node Y's subtree size as -

  • if X is Y, answer is N.

  • if X is an ancestor of Y, answer is N — (Y's child's subtree size which contains node X)

  • otherwise, answer is Y's subtree size.

solving case #1 and #3 are trivial.

case #2 can be solved by binary searching the child of Y.

time = O(N + QlgN)