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