#include <bits/stdc++.h>
#pragma GCC target("avx")

using namespace std;

#define REP(i, N) for (int i = 0; i < (int)N; i++)
#define FOR(i, a, b) for (int i = a; i < (int)b; i++)
using ll = long long;

constexpr int SZ = 100000, prs = 10;
ll pre[1 << prs][SZ + 1];

int main() {
  int N;
  cin >> N;
  vector<int> V(N + 1), W(N + 1);
  REP(i, N) cin >> V[i + 1] >> W[i + 1];
  FOR(i, 1, min(N + 1, 1 << prs)) {
    if (i != 1) copy(pre[i / 2], pre[i / 2] + SZ + 1, pre[i]);
    for (int j = SZ; j >= W[i]; --j)
      pre[i][j] = max(pre[i][j], pre[i][j - W[i]] + V[i]);
    REP(j, SZ) pre[i][j + 1] = max(pre[i][j + 1], pre[i][j]);
  }
  int Q;
  cin >> Q;
  while (Q--) {
    int v, L;
    cin >> v >> L;
    if (v < (1 << prs)) {
      cout << pre[v][L] << "\n";
    } else {
      int lvl = 32 - __builtin_clz(v) - prs;
      ll ans = 0;
      REP(b, 1 << lvl) {
        int w = 0;
        ll va = 0;
        REP(i, lvl) {
          if ((b >> i) & 1) {
            w += W[v >> i];
            va += V[v >> i];
          }
          if (w > L) break;
        }
        if (w <= L) ans = max(ans, pre[v >> lvl][L - w] + va);
      }
      cout << ans << "\n";
    }
  }
  return 0;
}
