#include<bits/stdc++.h>
using namespace std;
using ll=long long;

constexpr int C=9;

int N,V[(1<<18)+1],W[(1<<18)+1],Q;
vector<pair<int,int>>WV[(1<<C)+1];

int main(){
	cin>>N;
	for(int i=1;i<=N;i++){
		cin>>V[i]>>W[i];
	}
	WV[1].push_back({0,0});
	WV[1].push_back({W[1],V[1]});
	for(int i=2;i<(1<<C);i++){
		WV[i]=WV[i/2];
		for(auto p:WV[i/2]){
			WV[i].push_back({p.first+W[i],p.second+V[i]});
		}
		sort(WV[i].begin(),WV[i].end());
		for(int j=0;j<WV[i].size()-1;j++){
			WV[i][j+1].second=max(WV[i][j].second,WV[i][j+1].second);
		}
	}
	cin>>Q;
	while(Q--){
		int v,L;
		cin>>v>>L;
		vector<pair<int,int>>vp;
		vp.push_back({0,0});
		while(v>=(1<<C)){
			for(int i=vp.size()-1;i>=0;i--){
				vp.push_back({vp[i].first+W[v],vp[i].second+V[v]});
			}
			v/=2;
		}
		int res=0;
		for(auto a:vp){
			if(a.first>L)continue;
			auto it=lower_bound(WV[v].begin(),WV[v].end(),pair<int,int>{L-a.first+1,-1});
			it--;
			res=max(res,a.second+it->second);
		}
		cout<<res<<endl;
	}
}
