#include<stdio.h>
#define it register int
#define ct const int
#define il inline
const int N=100005,B=512;
typedef long long ll;
ll f[B+5][N];
int v[N<<4],w[N<<4],n,Q;
il ll Max(const ll p,const ll q){return p>q?p:q;}
il ll solve(ct x,ct V){
	if(V<=0) return 0;
	if(x<=B) return f[x][V];
	return Max(solve(x>>1,V),V>=w[x]?solve(x>>1,V-w[x])+v[x]:0);
}
int main(){
	scanf("%d",&n);it i,j,fa;
	for(i=1;i<=n;++i) scanf("%d%d",&v[i],&w[i]);
	for(i=1;i<=B;++i){
		fa=i>>1;
		for(j=100000;~j;--j) f[i][j]=f[fa][j];
		for(j=100000;j>=w[i];--j)
			f[i][j]=Max(f[i][j],f[i][j-w[i]]+v[i]);
	}
	scanf("%d",&Q);
	while(Q--) scanf("%d%d",&i,&j),printf("%lld\n",solve(i,j));
	return 0;
}
