// 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 sw = new long[](N + 1);
    auto sv = new long[](N + 1);
    auto mw = new long[](N + 1);
    mw[0] = long.max;
    foreach (i; 1 .. N + 1)
    {
        sw[i] = sw[i / 2] + W[i - 1];
        sv[i] = sv[i / 2] + V[i - 1];
        mw[i] = min(mw[i / 2], W[i - 1]);
    }

    long solve(long v, long L)
    {
        if (v == 0)
            return 0;
        if (sw[v] <= L)
        {
            return sv[v];
        }
        if (L < mw[v])
        {
            return 0;
        }
        if (L - W[v - 1] < 0)
            return memoize!solve(v / 2, L);
        return max(memoize!solve(v / 2, L - W[v - 1]) + V[v - 1], memoize!solve(v / 2, L));
    }

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

}
