#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;

vector<int> dp[1ll << 10];
int v[1ll << 18];
int w[1ll << 18];

int n, q;

const int INF = 1ll << 28ll;

void f(int pos, int depth) {
    if (pos > n) return;
    if (pos >= (1ll << 10)) return;

    dp[pos].resize(100001, 0);
    for (int i = 100000; i > 0; i--) {
        dp[pos][i] = dp[pos / 2][i];
        if (i >= w[pos]) {
            dp[pos][i] = max(dp[pos][i], dp[pos / 2][i - w[pos]] + v[pos]);
        }
    }

    f(pos * 2, depth + 1);
    f(pos * 2 + 1, depth + 1);
}

int dfs(int pos, int lim) {
    if (lim < 0) return -INF;
    if (pos < (1ll << 10)) {
        return dp[pos][lim];
    }

    return max(dfs(pos / 2, lim), dfs(pos / 2, lim - w[pos]) + v[pos]);
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> v[i] >> w[i];
    }

    dp[0].resize(100001, 0);
    f(1, 0);

    cin >> q;
    while (q--) {
        int u, lim;
        cin >> u >> lim;
        cout << dfs(u, lim) << '\n';
    }
}