Thor's Journey
Time limit2sMemory limit512 MB
In a perfect binary tree of up to 2^17-1 nodes with node weights, count for each query (start node A, target sum D) how many nodes B lie on a path from A with sum D.
- Level
Medium7 of 10
- Topics
- Tree, Prefix sum, Hash map, DFS
- Solved
- No attempts yet
Problem
Thor learned which planet holds an Infinity Stone. All planets are connected as a perfect binary tree, and each planet has an energy value .

A perfect binary tree numbers its root , gives every other vertex the parent , and holds vertices when its height is . The figure above shows a perfect binary tree of height . Planets and are connected when travel is possible from to and from to . The path sum from planet to planet is the sum of energies of all planets on the path from to . For instance, the path sum from to equals the energy of planet .
The path sum from the planet where Thor stands to the planet with the Infinity Stone is . Several planets can have path sum from the current position. Find how many planets can hold the Infinity Stone.
Input
The first line gives (). The second line gives the energy () of each planet, numbers in total. The third line gives (). Each of the next lines gives the number () of the planet where Thor stands and a path sum ().
Output
Print lines. Each line prints the number of planets whose path sum from the planet where Thor stands equals .
Hint
In the second query, the planets whose path sum from position equals are planet () and planet (), so the answer is .