Problem:
Score : 700 points

Problem Statement

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

Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i.
Now, process the following query Q times:

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

Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k (k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i.

Constraints

All values in input are integers.

1 \leq N < 2^{18}

1 \leq Q \leq 10^5

1 \leq V_i \leq 10^5

1 \leq W_i \leq 10^5

For the values v and L given in each query, 1 \leq v \leq N and 1 \leq L \leq 10^5.

Input

Let v_i and L_i be the values v and L given in the i-th query.
Then, Input is given from Standard Input in the following format:

N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q

Output

For each integer i from 1 through Q,
the i-th line should contain the response to the i-th query.

Sample Input 1

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

Sample Output 1

0
3
3

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

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

Sample Input 2

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

Sample Output 2

256
255
250
247
255
259
223
253

Solution in Rust (1.42.0) (judge verdict: Accepted)

use proconio::*;

// https://atcoder.jp/contests/tokiomarine2020/submissions/14270733
// ほぼこちらの写経

const MAX: usize = 1 << 18;
const MID: usize = 12;

fn chmax<T: Ord>(x: &mut T, a: T) {
    if *x < a {
        *x = a;
    }
}

fn merge<T: Ord + Copy>(mut a: Vec<T>, mut b: Vec<T>) -> Vec<T> {
    let mut c = Vec::with_capacity(a.len() + b.len());
    while !a.is_empty() && !b.is_empty() {
        if *a.last().unwrap() >= *b.last().unwrap() {
            c.push(a.pop().unwrap());
        } else {
            c.push(b.pop().unwrap());
        }
    }
    for a in a.into_iter().chain(b.into_iter()).rev() {
        c.push(a);
    }
    c.reverse();
    c
}

#[fastout]
fn run() {
    input! {
        n: usize,
        mut item: [(i32, i32); n],
        q: usize,
        ask: [(usize, i32); q],
    }
    while item.len() < MAX {
        item.push((0, 0));
    }
    item.insert(0, (0, 0));
    let mut query = vec![Some(vec![]); MAX + 1];
    for (i, &(v, w)) in ask.iter().enumerate() {
        query[v].as_mut().unwrap().push((w, 0, i));
    }
    for q in query.iter_mut() {
        q.as_mut().unwrap().sort();
    }
    let mut ans = vec![0; q];
    let mut stack = vec![(1, vec![(0, 0)])];
    while let Some((k, dp)) = stack.pop() {
        let (v, w) = item[k];
        let dp2 = dp.iter().map(|p| (p.0 + w, p.1 + v)).collect::<Vec<_>>();
        let dp = merge(dp, dp2);
        if 2 * k >= 1 << MID {
            let mut stack = vec![(2 * k, 0), (2 * k + 1, 0)];
            while let Some((k, op)) = stack.pop() {
                if op == 1 {
                    let (v, w) = item[k];
                    let a = query[k].take().unwrap();
                    let b = a.iter().map(|a| (a.0 - w, a.1 + v, a.2)).collect::<Vec<_>>();
                    let c = merge(a, b);
                    query[k / 2] = Some(merge(query[k / 2].take().unwrap(), c));
                } else {
                    stack.push((k, 1));
                    if 2 * k < MAX {
                        stack.push((2 * k, 0));
                        stack.push((2 * k + 1, 0));
                    }
                }
            }
        }
        let q = query[k].take().unwrap();
        let mut val = std::i32::MIN / 2;
        let mut p = 0;
        for (rem, v, k) in q.into_iter() {
            while p < dp.len() && dp[p].0 <= rem {
                val = std::cmp::max(val, dp[p].1);
                p += 1;
            }
            chmax(&mut ans[k], val + v);
        }
        if 2 * k < 1 << MID {
            stack.push((2 * k, dp.clone()));
            stack.push((2 * k + 1, dp));
        }
    }
    for a in ans {
        println!("{}", a);
    }
}

fn main() {
    run();
}