#include <bits/stdc++.h>
using namespace std;
const int MAX=1e5+10;

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int N; cin >> N;
    vector<int> V(N+1),W(N+1);
    for (int i=1;i<=N;++i) cin >> V[i] >> W[i];
    int half=1<<10;
    vector<vector<int>> dp(half,vector<int>(MAX,0));
    for (int i=1;i<min(N+1,half);++i){
        int p=i/2;
        for (int j=0;j<MAX;++j){
            dp[i][j]=max(dp[i][j],dp[p][j]);
            if (j+W[i]<MAX) dp[i][j+W[i]]=max(dp[i][j+W[i]],dp[p][j]+V[i]);
        }
        for (int j=0;j<MAX-1;++j) dp[i][j+1]=max(dp[i][j+1],dp[i][j]);
    }
    int Q; cin >> Q;
    for (;Q--;){
        int v,L; cin >> v >> L;
        if (v<half){
            cout << dp[v][L] << '\n';
            continue;
        }
        vector<int> pv,pw;
        for (;v>=half;v>>=1){
            pv.emplace_back(V[v]);
            pw.emplace_back(W[v]);
        }
        int n=pv.size(),ans=0;
        for (int mask=0;mask<(1<<n);++mask){
            int sv=0,sw=0;
            for (int i=0;i<n;++i){
                if (mask&1<<i){
                    sv+=pv[i]; sw+=pw[i];
                }
            }
            if (sw>L) continue;
            ans=max(ans,sv+dp[v][L-sw]);
        }
        cout << ans << '\n';
    }
}