#include <bits/stdc++.h>
using namespace std;
const int maxN = (1 << 18) + 10;
const int MAX = 1e5;
typedef long long ll;

int n, q;
#define pii pair<int,int>
pii a[maxN];
#define V first
#define W second

ll pre[maxN];
ll dp[512][MAX+1];

int main(){
  ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
//  freopen("abc.inp", "r", stdin); freopen("abc.out", "w", stdout);
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> a[i].V >> a[i].W;
  }

  const int limit = 512;
  for (int j = 0; j <= MAX; ++j)
    dp[1][j] = (a[1].W > j ? 0 : a[1].V);

  for (int i = 2; i < min(limit, n+1); ++i) {
    int par = i / 2;
    for (int j = 0; j <= MAX; ++j){
      dp[i][j] = dp[par][j];
      if (j >= a[i].W) dp[i][j] = max(dp[i][j], dp[par][j-a[i].W] + a[i].V);
    }
  }

  cin >> q;
  while (q--) {
    int x, L;
    cin >> x >> L;
    vector<int> node;

    while (x >= limit) {
      node.push_back(x);
      x /= 2;
    }
    ll ans = 0;
    int sz = node.size();
    for (int i = 0; i < (1 << sz); ++i) {
      ll Le = 0; int Ri = 0;
      for (int j = 0; j < sz; j++)
      if ((i >> j) & 1) {
        Le = Le + a[node[j]].V; Ri = Ri + a[node[j]].W;
      }
      if (Ri <= L) ans = max(ans, dp[x][L - Ri] + Le);
    }
    cout << ans << '\n';
  }
  return 0;
}
