#include <algorithm>
#include <cstdio>
#include <map>
#include <vector>

using namespace std;

const int M = 512;
const int L = 100000;

int main()
{
    int n; scanf("%d", &n);

    vector<int> v(n + 1), w(n + 1);
    static int m[M][L+1];

    for (int i = 1; i <= n; i++) {
        scanf("%d%d", &v[i], &w[i]);
        if (i >= M) continue;

        for (int j = 0; j < w[i]; j++) {
            m[i][j] = m[i / 2][j];
        }
        for (int j = w[i]; j <= L; j++) {
            m[i][j] = max(m[i / 2][j], m[i / 2][j - w[i]] + v[i]);
        }
    }

    int q; scanf("%d", &q);

    for (int i = 0; i < q; i++) {
        int u, l; scanf("%d%d", &u, &l);
        int ans = 0;
        int bits = 0;
        while ((u >> bits) >= M)
            ++bits;
        const int t = u >> bits;
        for (int j = 0; j < (1 << bits); j++) {
            int vv = 0, ww = 0;
            for (int k = 0; k < bits; k++) {
                if ((j >> k) & 1) {
                    vv += v[u >> k];
                    ww += w[u >> k];
                }
            }
            if (ww > l) continue;
            ans = max(ans, vv + m[t][l - ww]);
        }
        printf("%d\n", ans);
    }

    return 0;
}
