#include <bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
const long long inf = mod * mod;
const long long d2 = (mod + 1) / 2;
const double EPS = 1e-11;
const double INF = 1e+10;
const double PI = acos(-1.0);
const int C_SIZE = 11100000;
const int UF_SIZE = 3100000;
int p[310000];
int q[310000];
int dp[128][101000];
int dfs(int a, int b) {
  if (a < 128 && dp[a][b] != -1) return dp[a][b];
  if (a == 1) {
    if (b >= q[1])
      return dp[a][b] = p[1];
    else
      return dp[a][b] = 0;
  }
  int ret = dfs(a / 2, b);
  if (b >= q[a]) {
    ret = max(ret, dfs(a / 2, b - q[a]) + p[a]);
  }
  if (a < 128) dp[a][b] = ret;
  return ret;
}
int main() {
  int a;
  scanf("%d", &a);
  for (int i = 0; i < a; i++) {
    scanf("%d%d", p + i + 1, q + i + 1);
  }
  for (int i = 0; i < 128; i++)
    for (int j = 0; j < 101000; j++) dp[i][j] = -1;
  int b;
  scanf("%d", &b);
  for (int i = 0; i < b; i++) {
    int s, t;
    scanf("%d%d", &s, &t);
    int ret = dfs(s, t);
    printf("%d\n", ret);
  }
}
