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

#define REP(i,n) for(int i=0;i<n;i++)

int dp[1025][100001];
struct P{int w,v;};
template<typename T>
void chmax(T &a,T b){
  if(a<b)a=b;
}

int main(){
  int n;cin>>n;
  vector<int> v(n),w(n);
  REP(i,n)cin>>v[i]>>w[i];
  REP(i,min(n,1<<10))
    REP(j,100001){
      dp[i+1][j]=dp[(i+1)/2][j];
      if(j-w[i]>=0)chmax(dp[i+1][j],dp[(i+1)/2][j-w[i]]+v[i]);
      if(j>0)chmax(dp[i+1][j],dp[i+1][j-1]);
    }
  int q;cin>>q;
  while(q--){
    int a,l,ans=0;cin>>a>>l;
    vector<P> S;
    S.push_back({0,0});
    while(a>1024){
      int t=S.size();
      REP(i,t)if(S[i].w+w[a-1]<=l)S.push_back({S[i].w+w[a-1],S[i].v+v[a-1]});
      a>>=1;
    }
    for(P p:S)chmax(ans,dp[a][l-p.w]+p.v);
    cout<<ans<<endl;
  }
}