// 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(2 ^^ 10 + 1, 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 solve(long v, long l)
    {
        long[] I;
        long i = v;
        while (memo.length <= i)
            I ~= i, i /= 2;
        // writeln(I);
        long ans;
        foreach (ulong state; 0UL .. 2UL ^^ I.length + 1)
        {
            long value, weight;
            foreach (j; 0 .. I.length)
                if ((1 << j) & state)
                {
                    value += V[I[j] - 1];
                    weight += W[I[j] - 1];
                }
            if (l < weight)
                continue;
            ans = ans.max(memo[i][l - weight] + value);
        }
        return ans;
    }

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