#include <stdio.h>
#include <stdlib.h>
#define max(x, y) ((x)<(y) ? (y) : (x))

int main(){
  int n;  scanf("%d", &n);
  int v, w;
  int **dp;
  dp = (int**)malloc(sizeof(int*)*((1<<18)+22));
  for(int i=0; i<(1<<18)+22; i++)
    dp[i] = (int*)malloc(sizeof(int)*((1<<18)+22));
  
  for(int i=1; i<=n; i++){
    scanf("%d %d", &v, &w);
    for(int vi=(1<<18)+22; vi>=w; vi--){
      dp[i][vi] = max(dp[i/2][vi], dp[i/2][vi-w]+v);
    }
  }




  int q;  scanf("%d", &q);
  for(int i=0; i<q; i++){
    int u, l;  scanf("%d %d", &u, &l);
    printf("%d\n", dp[u][l]);
  }
  free(dp);
  return 0;
}
