/**
 *    author:  tourist
 *    created: 13.06.2020 15:28:36       
**/
#include <bits/stdc++.h>

using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> v(n), w(n);
  for (int i = 0; i < n; i++) {
    cin >> v[i] >> w[i];
  }
  const int MAX = 100001;
  int limit = min(512, n);
  vector<vector<int>> dp(limit, vector<int>(MAX));
  for (int j = 0; j < MAX; j++) {
    dp[0][j] = (j >= w[0] ? v[0] : 0);
  }
  for (int i = 1; i < limit; i++) {
    int p = (i - 1) / 2;
    for (int j = 0; j < MAX; j++) {
      dp[i][j] = dp[p][j];
      if (j >= w[i]) {
        dp[i][j] = max(dp[i][j], dp[p][j - w[i]] + v[i]);
      }
    }
  }
  int tt;
  cin >> tt;
  while (tt--) {
    int ver, L;
    cin >> ver >> L;
    --ver;
    vector<int> ids;
    while (ver >= limit) {
      ids.push_back(ver);
      ver = (ver - 1) / 2;
    }
    int sz = (int) ids.size();
    int ans = 0;
    for (int t = 0; t < (1 << sz); t++) {
      int sv = 0;
      int sw = 0;
      for (int i = 0; i < sz; i++) {
        if (t & (1 << i)) {
          sv += v[ids[i]];
          sw += w[ids[i]];
        }
      }
      if (sw <= L) {
        ans = max(ans, dp[ver][L - sw] + sv);
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
