#include<stdio.h>
long int v[1<<18],w[1<<18],n,q;
long int l[1<<18][1<<9];
long int ns(int i,int j){
  if(i<1<<9)return l[j][i];
  if(w[i]>j)return ns(i/2,j);
  long int x=ns(i/2,j),y=ns(i/2,j-w[i])+v[i];
  return x<y?y:x;
}
int main(){
  int i,j,k;
  scanf("%ld",&n);
  for(i=1;i<=n;i++)scanf("%ld%ld",&v[i],&w[i]);
  for(i=0;i<1<<18;i++)l[1][i]=w[1]>i?0:v[1];
  for(i=2;i<1<<9;i++)if(i<=n)for(j=0;j<1<<18;j++){
    if(w[i]>j)l[j][i]=l[j][i/2];
    else l[j][i]=l[j][i/2]<l[j-w[i]][i/2]+v[i]?l[j-w[i]][i/2]+v[i]:l[j][i/2];
  }
  scanf("%ld",&q);
  for(i=0;i<q;i++){scanf("%d%d",&j,&k);printf("%ld\n",ns(j,k));}
}
