#include <bits/stdc++.h>
using namespace std;
typedef vector<int> VI;
typedef pair <int,int> ii;
typedef long long LL;
#define pb push_back
const int INF = 2147483647;
const int N = 263000;
const int MAXX = 100000;

int n, v[N], w[N], q, a, b, i, best, act, j, m, res[512][MAXX + 4];
vector<ii> v1, v2;

int get(int i, int lim, int maxx) {
	v1.clear();
	v1.pb(ii(0, 0));
	int j;
	for (j=i;j>=lim;j/=2) {
		v2.clear();
		for (auto& ww : v1) if (w[j] + ww.second <= maxx) v2.pb(ii(ww.first + v[j], ww.second + w[j]));
		for (auto& ww : v2) v1.pb(ww);
	}
	return j;
}

int main() {
scanf("%d", &n);
for (i=1;i<=n;i++) scanf("%d %d", &v[i], &w[i]);
m = min((1<<9) - 1, n);
for (i=1;i<=m;i++) {
	get(i, 1, MAXX);
	//printf("%d\n", v1.size());
	for (auto& ww : v1) if (res[i][ww.second] < ww.first) res[i][ww.second] = ww.first;
	best = 0;
	for (j=0;j<=MAXX;j++) if (res[i][j] < best) res[i][j] = best; else best = res[i][j];
}
scanf("%d", &q);
while (q--) {
	scanf("%d %d", &a, &b);
	if (a <= m) {
		printf("%d\n", res[a][b]);
		continue;
	}
	act = get(a, m + 1, b);
	//printf("%d\n", act);
	best = 0;
	for (auto& ww : v1) best = max(best, ww.first + res[act][b - ww.second]);
	printf("%d\n", best);
}
return 0;
}