#include <bits/stdc++.h>
using namespace std;
#define int long long 

int32_t main() {
  ios::sync_with_stdio(0);
  cout.tie(0);
  cin.tie(0);

  int n;
  cin >> n;
  
  int lim = log2(n) / 2;
  vector<int> c(n + 1), w(n + 1);
  vector<vector<int>> dp(1<<lim, vector<int> (1e5+5, 0));
  for (int i = 1; i <= n; ++i) cin >> c[i] >> w[i];

  for (int i = 1; i < min((1ll<<lim), n+1); ++i) {
    for (int j = 1; j <= 1e5; ++j) {
      dp[i][j] = max(dp[i][j-1], dp[i/2][j]);
      if (j >= w[i]) dp[i][j] = max(dp[i][j], dp[i/2][j - w[i]] + c[i]);
    }
  }

  int q;
  cin >> q;
  
  while (q--) {
    int v, l;
    cin >> v >> l;
  
    vector<pair<int, int>> p;
    p.emplace_back(0, 0);

    while (v >= (1<<lim)) {
      int s = p.size();
      for (int i = 0; i < s; ++i) {
        if (p[i].second + w[v] <= l)
          p.emplace_back(p[i].first + c[v], p[i].second + w[v]);
      }
      v /= 2;
    }

    int ans = 0;
    for (int i = 0; i < (int)p.size(); ++i) {
      int wt = p[i].second;
      ans = max(ans, p[i].first + dp[v][l - wt]);
    }
    cout << ans << '\n';
  }
}
