#include <stdio.h>

typedef struct {
	long long key, id;
} data;

void merge_sort(data x[], int n)
{
	static data y[10001] = {};
	if (n <= 1) return;
	merge_sort(&(x[0]), n/2);
	merge_sort(&(x[n/2]), (n+1)/2);
	
	int i, p, q;
	for (i = 0, p = 0, q = n/2; i < n; i++) {
		if (p >= n/2) y[i] = x[q++];
		else if (q >= n) y[i] = x[p++];
		else y[i] = (x[p].key < x[q].key)? x[p++]: x[q++];
	}
	for (i = 0; i < n; i++) x[i] = y[i];
}

int main()
{
	int i, N, Q, V[300000], W[300000];
	scanf("%d", &N);
	for (i = 1; i <= N; i++) scanf("%d %d", &(V[i]), &(W[i]));
	scanf("%d", &Q);
	
	int j, k, l, m, size[512];
	const int bit[10] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
	data d[512][512];
	for (i = 0; i < 511 && i < N; i++) {
		for (k = 0; bit[k] <= i + 1; k++);
		for (j = 0; j < bit[k]; j++) {
			d[i][j].key = 0;
			d[i][j].id = 0;
			for (l = 0, m = i + 1; l <= k; l++, m >>= 1) {
				if ((j & bit[l]) != 0) {
					d[i][j].key += W[m];
					d[i][j].id += V[m];
				}
			}
		}
		merge_sort(d[i], bit[k]);
		for (j = 1, size[i] = 1; j < bit[k]; j++) if (d[i][j].id > d[i][size[i]-1].id) d[i][size[i]++] = d[i][j];
	}
	
	int q, v, L;
	long long ans;
	data tmp[512];
	for (q = 1; q <= Q; q++) {
		scanf("%d %d", &v, &L);
		if (v < 512) {
			v--;
			for (j = 0, ans = 0; j < size[v] && d[v][j].key <= L; j++) ans = d[v][j].id;
			printf("%lld\n", ans);
			continue;
		}
		
		i = v / 512 - 1;
		for (k = 0; bit[k] <= i + 1; k++);
		for (j = 0; j < bit[k]; j++) {
			tmp[j].key = 0;
			tmp[j].id = 0;
			for (l = 0, m = v; l <= k; l++, m >>= 1) {
				if ((j & bit[l]) != 0) {
					tmp[j].key += W[m];
					tmp[j].id += V[m];
				}
			}
		}
		merge_sort(tmp, bit[k]);
		
		for (j = 0, m = v / bit[k] - 1, l = size[m] - 1, ans = 0; j < bit[k] && tmp[j].key <= L; j++) {
			for (; l >= 0 && tmp[j].key + d[m][l].key > L; l--);
			if (l < 0) break;
			if (tmp[j].id + d[m][l].id > ans) ans = tmp[j].id + d[m][l].id;
		}
		printf("%lld\n", ans);
	}
	
	fflush(stdout);
	return 0;
}