#include <bits/stdc++.h>
using namespace std;
const int maxw = 1e5 + 10;
const int maxn = (1 << 18) + 10;
const int magic = 1 << 9;
int v[maxn], w[maxn];
int dp[magic][maxw];

int query(int x, int L) {
  if(x < magic) return dp[x][L];
  vector <pair <int, int>> cont;
  while(x >= magic) {
    cont.emplace_back(w[x], v[x]);
    x >>= 1;
  }
  int ans = 0;
  for(int i = 0; i < (1 << cont.size()); i++) {
    int totalW = 0, totalV = 0;
    for(int j = 0; j < cont.size(); j++) {
      if((i >> j) & 1) {
        totalW += cont[j].first;
        totalV += cont[j].second;
      }
    }
    if(totalW <= L) {
      ans = max(ans, totalV + dp[x][L - totalW]);
    }
  }
  return ans;
}
int main() {
  int n;
  scanf("%d", &n);
  for(int i = 1; i <= n; i++) {
    scanf("%d %d", &v[i], &w[i]);
  }
  for(int i = 1; i < magic && i <= n; i++) {
    for(int j = 1; j < maxw; j++) {
      dp[i][j] = dp[i >> 1][j];
      if(w[i] <= j) {
        dp[i][j] = max(dp[i][j], v[i] + dp[i >> 1][j - w[i]]);
      }
    }
  }
  int q;
  scanf("%d", &q);
  while(q--) {
    int x, L;
    scanf("%d %d", &x, &L);
    printf("%d\n", query(x, L));
  }
  return 0;
}
