#TOKIOMARINE2020D. Knapsack Queries on a tree

Knapsack Queries on a tree

Score : 700700 points

Problem Statement

We have a rooted binary tree with NN vertices, where the vertices are numbered 11 to NN. Vertex 11 is the root, and the parent of Vertex ii (i2i \geq 2) is Vertex [i2]\left[ \frac{i}{2} \right].

Each vertex has one item in it. The item in Vertex ii has a value of ViV_i and a weight of WiW_i. Now, process the following query QQ times:

  • Given are a vertex vv of the tree and a positive integer LL. Let us choose some (possibly none) of the items in vv and the ancestors of vv so that their total weight is at most LL. Find the maximum possible total value of the chosen items.

Here, Vertex uu is said to be an ancestor of Vertex vv when uu is an indirect parent of vv, that is, there exists a sequence of vertices w1,w2,,wkw_1,w_2,\ldots,w_k (k2k\geq 2) where w1=vw_1=v, wk=uw_k=u, and wi+1w_{i+1} is the parent of wiw_i for each ii.

Constraints

  • All values in input are integers.
  • 1N<2181 \leq N < 2^{18}
  • 1Q1051 \leq Q \leq 10^5
  • 1Vi1051 \leq V_i \leq 10^5
  • 1Wi1051 \leq W_i \leq 10^5
  • For the values vv and LL given in each query, 1vN1 \leq v \leq N and 1L1051 \leq L \leq 10^5.

Input

Let viv_i and LiL_i be the values vv and LL given in the ii-th query. Then, Input is given from Standard Input in the following format:

NN

V1V_1 W1W_1

::

VNV_N WNW_N

QQ

v1v_1 L1L_1

::

vQv_Q LQL_Q

Output

For each integer ii from 11 through QQ, the ii-th line should contain the response to the ii-th query.

3
1 2
2 3
3 4
3
1 1
2 5
3 5
0
3
3

In the first query, we are given only one choice: the item with (V,W)=(1,2)(V, W)=(1,2). Since L=1L = 1, we cannot actually choose it, so our response should be 00.

In the second query, we are given two choices: the items with (V,W)=(1,2)(V, W)=(1,2) and (V,W)=(2,3)(V, W)=(2,3). Since L=5L = 5, we can choose both of them, so our response should be 33.

15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227
256
255
250
247
255
259
223
253