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

typedef long long ll;

ll N;
vector<ll> V, W;
ll Q;
const ll K = 9, L = 100000;
vector<vector<ll>> Dp;
ll I;

ll solve(ll i, ll l) {
  if (i <= I) return Dp[i][l];
  ll res = solve(i / 2, l);
  if (l >= W[i]) res = max(res, V[i] + solve(i / 2, l - W[i]));
  return res;
}
int main() {
  cin >> N;
  V.resize(N + 1);
  W.resize(N + 1);
  for (ll i = 1; i <= N; ++i) cin >> V[i] >> W[i];
  I = min(N, (1ll << K) - 1);
  Dp.resize(I + 1);
  for (auto &dp : Dp) dp.resize(L + 1);
  for (ll i = 1; i <= I; ++i) {
    for (ll l = 0; l <= L; ++l) {
      Dp[i][l] = Dp[i / 2][l];
      if (W[i] <= l) Dp[i][l] = max(Dp[i][l], Dp[i / 2][l - W[i]] + V[i]);
    }
  }
  cin >> Q;
  for (ll q = 0; q < Q; ++q) {
    ll i, l;
    cin >> i >> l;
    cout << solve(i, l) << endl;
  }
  return 0;
}
