This page is still under construction.

Parts of this page are still being built. What you see may change.

Thor's Journey

Time limit2sMemory limit512 MB

Summary
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 EE.

A perfect binary tree numbers its root 11, gives every other vertex vv the parent (v/2)(v/2), and holds (2N)−1(2^N)-1 vertices when its height is NN. The figure above shows a perfect binary tree of height 33. Planets AA and BB are connected when travel is possible from AA to BB and from BB to AA. The path sum from planet AA to planet BB is the sum of energies of all planets on the path from AA to BB. For instance, the path sum from AA to AA equals the energy of planet AA.

The path sum from the planet where Thor stands to the planet with the Infinity Stone is DD. Several planets can have path sum DD from the current position. Find how many planets can hold the Infinity Stone.

Input

The first line gives NN (1≤N≤171 \le N \le 17). The second line gives the energy EiE_i (−1,000,000,000≤Ei≤1,000,000,000-1{,}000{,}000{,}000 \le E_i \le 1{,}000{,}000{,}000) of each planet, (2N)−1(2^N)-1 numbers in total. The third line gives QQ (1≤Q≤100,0001 \le Q \le 100{,}000). Each of the next QQ lines gives the number AA (1≤A≤2N−11 \le A \le 2^N-1) of the planet where Thor stands and a path sum DD (−1,000,000,000≤D≤1,000,000,000-1{,}000{,}000{,}000 \le D \le 1{,}000{,}000{,}000).

Output

Print QQ lines. Each line prints the number of planets whose path sum from the planet where Thor stands equals DD.

Hint

In the second query, the planets whose path sum from position 44 equals 55 are planet 55 (E[4]+E[2]+E[5]=5E[4] + E[2] + E[5] = 5) and planet 33 (E[4]+E[2]+E[1]+E[3]=5E[4] + E[2] + E[1] + E[3] = 5), so the answer is 22.

Examples2

  1. Example 1

    Input
    2
    5 0 0
    2
    1 5
    2 5
    
    Expected output
    3
    2
    
  2. Example 2

    Input
    3
    0 2 2 1 2 -1 2
    1
    4 5
    
    Expected output
    2