#include<bits/stdc++.h>
#define mr make_pair
#define pb emplace_back
#define N 100010
#define fi first
#define se second
using namespace std;
template <typename T> void read(T &x){
	x=0;char ch=getchar();int fh=1;
	while (ch<'0'||ch>'9'){if (ch=='-')fh=-1;ch=getchar();}
	while (ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
	x*=fh;
}
int n,v[300010],w[300010],dp[520][N],q,u,l;
vector<pair<int,int> > s;
int main(){
	read(n);for (int i=1;i<=n;i++)read(v[i]),read(w[i]);
	for (int i=1;i<min(n+1,1<<9);i++){
		for (int j=0;j<=100000;j++)dp[i][j]=dp[i/2][j];
		for (int j=0;j<=100000-w[i];j++)dp[i][j+w[i]]=max(dp[i/2][j+w[i]],dp[i/2][j]+v[i]);
	}
	read(q);
	while (q--){
		read(u);read(l);
		s.clear();s.pb(mr(l,0));
		while (u>=(1<<9)){
			int g=s.size();
			for (int i=0;i<g;i++)if (s[i].fi>=w[u])s.pb(mr(s[i].fi-w[u],s[i].se+v[u]));
			u/=2;
		}
		int g=s.size(),an=0;
		for (int i=0;i<g;i++)an=max(an,s[i].se+dp[u][s[i].fi]);
		printf("%d\n",an);
	}
	return 0;
}