#include <math.h>
#include <stdio.h>
int value[1 << 18], weight[1 << 18];
int dp[23][100010];
int max(int x, int y) {
	return x > y ? x : y;
}
int main() {
	int n, q;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		scanf("%d%d", &value[i], &weight[i]);
	}
	scanf("%d", &q);
	for (int _ = 0; _ < q; _++) {
		for (int i = 0; i < 23; i++) {
			for (int j = 0; j < 100010; j++) {
				dp[i][j] = 0;
			}
		}
		int v, l;
		scanf("%d%d", &v, &l);
		int i;
		for (i = 0; v != 0; i++) {
			for (int j = 0; j <= l; j++) {
				if (j >= weight[v]) {
					dp[i + 1][j] =
						max(dp[i][j], dp[i][j - weight[v]] + value[v]);
				}
				dp[i + 1][j] = max(dp[i + 1][j], dp[i][j]);
			}
			v /= 2;
		}
		printf("%d\n", dp[i][l]);
	}
	return 0;
}