#include <bits/stdc++.h>

using namespace std;

const int N = 1 << 18, L = 1e5 + 5, S = 1 << 9;

int n, q, v[N], w[N];

int dp[S][L];
pair<int, int> val[22];

int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d %d", v+i, w+i);
  }
  for (int i = 1; i < S; ++i) {
    int vv = v[i], ww = w[i];
    int par = i / 2;
    for (int j = 0; j < L; ++j)
      dp[i][j] = dp[par][j];
    for (int j = 0; j + ww < L; ++j)
      dp[i][j+ww] = max(dp[i][j+ww], dp[par][j] + vv);
  }
  scanf("%d", &q);
  while (q--) {
    int u, l;
    scanf("%d %d", &u, &l);
    int ans = 0;
    if (u < S) {
      ans = dp[u][l];
    } else {
      int len = 0;
      while (u >= S) {
        val[len++] = {v[u], w[u]};
        u /= 2;
      }
      int nmask = 1 << len;
      ans = 0;
      for (int mask = 0; mask < nmask; ++mask) {
        int ww = 0;
        int vv = 0;
        for (int i = 0; i < len; ++i)
          if ((mask >> i) & 1)
            vv += val[i].first, ww += val[i].second;
        if (ww <= l)
          ans = max(ans, vv + dp[u][l - ww]);
      }
    }
    printf("%d\n", ans);
  }
  return 0;
}
