"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(String(myOut));

function main(){
  var n = next();
  const aa = 10;
  var mn = Math.min(n,1<<aa);
  const mx = 1e5+1;
  var dp = Array(mn);
  var V = nextm(n,2);
  var q = next();
  var need = xArray("[]",n);
  for(var i = 0; i < q; i++){
    var u = next()-1, l = next();
    if(need[u][0] === -1)need[u] = [i,l];else need[u].push(i,l);
    while(u){
      u = u-1>>1;
      if(need[u].length)break;
      need[u].push(-1);
    }
  }
  var v = V[0][0], w = V[0][1];
  dp[0] = Array(mx).fill(0,0,w).fill(v,w);
  var ans = xArray(0,q);
  solve(0);
  for(var i = 1; i < mn; i++){
    if(need[i].length === 0)continue;
    var p = i-1>>1;
    v = V[i][0], w = V[i][1];
    dp[i] = (i&1) ? dp[p].concat() : dp[p];
    for(var j = mx-1; w <= j; j--)if(dp[i][j] < dp[i][j-w]+v)dp[i][j] = dp[i][j-w]+v;
    solve(i);
  }
  for(var i = mn; i < n; i++){
    if(need[i].length === 0)continue;
    var d = 31-Math.clz32(i);
    var p = i-1>>1;
    var v = V[i][0], w = V[i][1];
    if(d === aa){
      dp[i] = [v,w];
    }else{
      dp[i] = (i&1) ? dp[p].concat() : dp[p];
      var ln = dp[i].length;
      for(var j = 0; j < ln; j+=2)if(dp[i][j+1]+w < mx)dp[i].push(dp[i][j]+v,dp[i][j+1]+w);
    }
    while(mn <= p)p = p-1>>1;
    for(var j = need[i].length&1; j < need[i].length; j+=2){
      var id = need[i][j], l = need[i][j+1];
      for(var k = 0; k < dp[i].length; k+=2){
        var v = dp[i][k], w = dp[i][k+1];
        if(l < w)continue;
        if(ans[id] < dp[p][l-w]+v)ans[id] = dp[p][l-w]+v;
      }
    }
  }

  return ans.join("\n");

  function solve(k){
    var a = need[k];
    for(var i = a.length & 1; i < a.length; i+=2){
      ans[a[i]] = dp[k][a[i+1]];
    }
  }
}