#include <bits/stdc++.h>
#define rep(i,l,r) for (int i=l;i<=r;++i)
#define per(i,r,l) for (int i=r;i>=l;--i)
#define rep0(i,r) for (int i=0;i<r;++i)
#define pr pair<int,int>
#define mp make_pair
#define fi first
#define se second
#define ll long long
using namespace std;
const int N=1e6+6,T=(1<<9)-1,M=1e5;
ll f[1003][M+5]; int hei[N],v[N],w[N],v0[N],w0[N];
int main(){
    int n; cin>>n;
    rep(i,1,n) scanf("%d%d",&v[i],&w[i]);
    rep(i,1,n) hei[i]=hei[i>>1]+1;
    rep(i,1,min(n,T)){
        rep(j,1,M) f[i][j]=f[i>>1][j];
        per(j,M,w[i]) f[i][j]=max(f[i][j],f[i][j-w[i]]+v[i]);
    }
    int q; cin>>q;
    while (q--){
        int u,m; scanf("%d%d",&u,&m);
        if (hei[u]<=9) printf("%lld\n",f[u][m]);
        else{
            int c=0; ll ans=0;
            for (;hei[u]>9;u>>=1) v0[++c]=v[u],w0[c]=w[u];
            rep(s,0,(1<<c)-1){
                int l=m; ll sum=0;
                rep(i,1,c) if (s>>i-1&1) l-=w0[i],sum+=v0[i];
                if (l>=0) ans=max(ans,sum+f[u][l]);
            }
            printf("%lld\n",ans);
        }
    }
    return 0;
}
