#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef pair<ll,ll> p2;
ll a[(1<<18)],w[(1<<18)],dp[(1<<9)][100005],dep[(1<<18)];
void solve(){
	ll n,q;
	cin>>n;
	for(ll i=1;i<=n;i++)
	cin>>a[i]>>w[i];
	for(ll i=2;i<=n;i++){
		dep[i]=dep[i-1];
		if(!(i&(i-1)))
		dep[i]++;
	}
	for(ll i=1;i<=min(ll((1<<9)-1),n);i++){
		for(ll j=1;j<=100000;j++){
			dp[i][j]=dp[i/2][j];
			if(j>=w[i])
			dp[i][j]=max(dp[i][j],dp[i/2][j-w[i]]+a[i]);
		}
	}
	cin>>q;
	for(ll qc=0;qc<q;qc++){
		ll v,l,res=0;
		cin>>v>>l;
		if(dep[v]<9)
		res=dp[v][l];
		else{
			vector<ll> g;
			while(dep[v]>=9){
				g.push_back(v);
				v>>=1;
			}
			ll m=ll(g.size());
			for(ll i=0;i<(1<<m);i++){
				ll sum=0,tot=0,tr=i,c=0;
				while(tr>0){
					if(tr&1){
						tot+=w[g[c]];
						sum+=a[g[c]];
					}
					tr>>=1;
					c++;
				}
				if(tot<=l)
				res=max(res,sum+dp[v][l-tot]);
			}
		}
		cout<<res<<"\n";
	}
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll qc=1;
    //cin>>qc;
    for(ll i=1;i<=qc;i++)
    solve();		
}
