// dfmt off
T lread(T=long)(){return readln.chomp.to!T;}T[] lreads(T=long)(long n){return iota(n).map!((_)=>lread!T).array;}
T[] aryread(T=long)(){return readln.split.to!(T[]);}void arywrite(T)(T a){a.map!text.join(' ').writeln;}
void scan(L...)(ref L A){auto l=readln.split;foreach(i,T;L){A[i]=l[i].to!T;}}alias sread=()=>readln.chomp();
void dprint(L...)(lazy L A){debug{auto l=new string[](L.length);static foreach(i,a;A)l[i]=a.text;arywrite(l);}}
static immutable MOD=10^^9+7;alias PQueue(T,alias l="b<a")=BinaryHeap!(Array!T,l);import std;
// dfmt on

void main()
{
    long N = lread();
    auto V = new long[](N);
    auto W = new long[](N);
    foreach (i; 0 .. N)
        scan(V[i], W[i]);
    auto memo = new long[][](min(1025, N + 1), 10 ^^ 5 + 2);
    foreach (i; 1 .. memo.length)
    {
        foreach (j; 0 .. 10 ^^ 5 + 1)
        {
            memo[i][j] = memo[i][j].max(memo[i / 2][j]);
            memo[i][min(j + W[i - 1], 10 ^^ 5 + 1)] = memo[i][min(j + W[i - 1], 10 ^^ 5 + 1)].max(
                    memo[i / 2][j] + V[i - 1]);
        }
    }
    long Q = lread();
    long solve(long v, long l)
    {
        if (v < memo.length)
            return memo[v][l];
        if (l - W[v - 1] < 0)
            return memoize!solve(v / 2, l);
        return max(memoize!solve(v / 2, l), memoize!solve(v / 2, l - W[v - 1])) + V[v - 1];
    }

    foreach (_; 0 .. Q)
    {
        long v, l;
        scan(v, l);
        solve(v, l).writeln();
    }
}
