#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e5 + 10;
int v[maxn],w[maxn],n,q;
int dp[529][100005],ans = 0;
vector<int> g;
void dfs(int &ans,int val,int weight,int limit,int pos,int fa) {
	if (weight > limit) return;
	if (pos == g.size()) {
		//printf("*****%d %d %d\n",val,limit - weight,dp[fa][limit - weight]);
		ans = max(ans,val + dp[fa][limit - weight]);
		return ;
	}
	dfs(ans,val + v[g[pos]],weight + w[g[pos]],limit,pos + 1,fa);
	dfs(ans,val,weight,limit,pos + 1,fa);
}
int main() {
	scanf("%d",&n);
	for (int i = 1; i <= n; i++) {
		scanf("%d%d",&v[i],&w[i]);
	}
	int N = sqrt(n), T = 100000;
	for (int i = 1; i <= N; i++) {
		for (int j = 0; j <= T; j++) {
			dp[i][j] = dp[i / 2][j];
			if (j >= w[i])
				dp[i][j] = max(dp[i][j],dp[i / 2][j - w[i]] + v[i]);
		}
	} 
	scanf("%d",&q);
	while (q--) {
		int v, L;
		scanf("%d%d",&v,&L);
		if (v <= N) printf("%d\n",dp[v][L]);
		else {
			ans = 0;
			g.clear();
			while (v > N) {
				g.push_back(v);
				v /= 2;
			}
			//printf("****%d %d\n",g.size(),v);
			dfs(ans,0,0,L,0,v);
			printf("%d\n",ans);
		}
	}
	return 0;
}