#include <cstdio>
#include <algorithm>
using namespace std;
int N, V[1 << 18], W[1 << 18];
int dptable[1024][100001];
int dp(int i, int j) {
	if (i < 1024) return dptable[i][j];
	if (j < W[i]) return dp(i / 2, j);
	return max(dp(i / 2, j - W[i]) + V[i], dp(i / 2, j));
}
int main() {
	int Q, v, L;
	scanf("%d", &N);
	for (int i = 1; i <= N; ++i) scanf("%d %d", &V[i], &W[i]);
	fill_n(dptable[0], 100001, 0);
	for (int i = 1; i < 1024; ++i) {
		for (int j = 0; j <= 100000; ++j) {
			if (j < W[i]) dptable[i][j] = dptable[i >> 1][j];
			else dptable[i][j] = max(dptable[i >> 1][j], dptable[i >> 1][j - W[i]] + V[i]);
		}
	}
	scanf("%d", &Q);
	for (int i = 0; i < Q; ++i) {
		scanf("%d %d", &v, &L);
		printf("%d\n", dp(v, L));
	}
	return 0;
}