Problem:
Score : 700 points

Problem Statement

We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N.
Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].

Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i.
Now, process the following query Q times:

Given are a vertex v of the tree and a positive integer L.
Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L.
Find the maximum possible total value of the chosen items.

Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k (k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i.

Constraints

All values in input are integers.

1 \leq N < 2^{18}

1 \leq Q \leq 10^5

1 \leq V_i \leq 10^5

1 \leq W_i \leq 10^5

For the values v and L given in each query, 1 \leq v \leq N and 1 \leq L \leq 10^5.

Input

Let v_i and L_i be the values v and L given in the i-th query.
Then, Input is given from Standard Input in the following format:

N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q

Output

For each integer i from 1 through Q,
the i-th line should contain the response to the i-th query.

Sample Input 1

3
1 2
2 3
3 4
3
1 1
2 5
3 5

Sample Output 1

0
3
3

In the first query, we are given only one choice: the item with (V, W)=(1,2). Since L = 1, we cannot actually choose it, so our response should be 0.

In the second query, we are given two choices: the items with (V, W)=(1,2) and (V, W)=(2,3). Since L = 5, we can choose both of them, so our response should be 3.

Sample Input 2

15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227

Sample Output 2

256
255
250
247
255
259
223
253

Solution in C# (Mono-mcs 6.8.0.105) (judge verdict: Time Limit Exceeded)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using static System.Math;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using Library;

namespace Program
{
    public static class ProblemD
    {
        static bool SAIKI = false;
        static public int numberOfRandomCases = 0;
        static public void MakeTestCase(List<string> _input, List<string> _output, ref Func<string[], bool> _outputChecker)
        {
        }
        static public void Solve()
        {
            var N = NN;
            var VW = Repeat(0, N).Select(_ => new { V = NN, W = NN }).ToArray();
            var Q = NN;
            var vL = Repeat(0, Q).Select(_ => new { v = NN, L = NN }).ToArray();
            var vToQIdx = Repeat(0, N).Select(_ => new List<long>()).ToArray();
            for (var i = 0; i < Q; i++) vToQIdx[vL[i].v - 1].Add(i);
            var deq = new LIB_Deque<Dictionary<long, long>>();
            var dic = new Dictionary<long, long>();
            dic[0] = 0;
            deq.PushBack(dic);
            var ans = new long[Q];
            Action<long> act = null;
            act = vtx =>
            {
                if (vtx > N) return;
                var newDic = new Dictionary<long, long>();
                foreach (var item in deq.Back)
                {
                    var newW = item.Key + VW[vtx - 1].W;
                    if (newDic.ContainsKey(newW))
                    {
                        newDic[newW] = Max(newDic[newW], item.Value + VW[vtx - 1].V);
                    }
                    else
                    {
                        newDic[newW] = item.Value + VW[vtx - 1].V;
                    }
                    if (newDic.ContainsKey(item.Key))
                    {
                        newDic[item.Key] = Max(newDic[item.Key], item.Value);
                    }
                    else
                    {
                        newDic[item.Key] = item.Value;
                    }
                }
                deq.PushBack(newDic);
                foreach (var item in vToQIdx[vtx - 1])
                {
                    foreach (var item2 in deq.Back)
                    {
                        if (item2.Key <= vL[item].L)
                        {
                            ans[item] = Max(ans[item], item2.Value);
                        }
                    }
                }
                act(vtx << 1);
                act((vtx << 1) + 1);
                deq.PopBack();
            };
            act(1);
            foreach (var item in ans)
            {
                Console.WriteLine(item);
            }
        }
        class Printer : StreamWriter
        {
            public override IFormatProvider FormatProvider { get { return CultureInfo.InvariantCulture; } }
            public Printer(Stream stream) : base(stream, new UTF8Encoding(false, true)) { base.AutoFlush = false; }
            public Printer(Stream stream, Encoding encoding) : base(stream, encoding) { base.AutoFlush = false; }
        }
        static LIB_FastIO fastio = new LIB_FastIODebug();
        static public void Main(string[] args) { if (args.Length == 0) { fastio = new LIB_FastIO(); Console.SetOut(new Printer(Console.OpenStandardOutput())); } if (SAIKI) { var t = new Thread(Solve, 134217728); t.Start(); t.Join(); } else Solve(); Console.Out.Flush(); }
        static long NN => fastio.Long();
        static double ND => fastio.Double();
        static string NS => fastio.Scan();
        static long[] NNList(long N) => Repeat(0, N).Select(_ => NN).ToArray();
        static double[] NDList(long N) => Repeat(0, N).Select(_ => ND).ToArray();
        static string[] NSList(long N) => Repeat(0, N).Select(_ => NS).ToArray();
        static long Count<T>(this IEnumerable<T> x, Func<T, bool> pred) => Enumerable.Count(x, pred);
        static IEnumerable<T> Repeat<T>(T v, long n) => Enumerable.Repeat<T>(v, (int)n);
        static IEnumerable<int> Range(long s, long c) => Enumerable.Range((int)s, (int)c);
        static IOrderedEnumerable<T> OrderByRand<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x, _ => xorshift);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x) => Enumerable.OrderBy(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderBy<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderBy(x.OrderByRand(), selector);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x) => Enumerable.OrderByDescending(x.OrderByRand(), e => e);
        static IOrderedEnumerable<T1> OrderByDescending<T1, T2>(this IEnumerable<T1> x, Func<T1, T2> selector) => Enumerable.OrderByDescending(x.OrderByRand(), selector);
        static IOrderedEnumerable<string> OrderBy(this IEnumerable<string> x) => x.OrderByRand().OrderBy(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderBy<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderBy(selector, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<string> OrderByDescending(this IEnumerable<string> x) => x.OrderByRand().OrderByDescending(e => e, StringComparer.OrdinalIgnoreCase);
        static IOrderedEnumerable<T> OrderByDescending<T>(this IEnumerable<T> x, Func<T, string> selector) => x.OrderByRand().OrderByDescending(selector, StringComparer.OrdinalIgnoreCase);
        static uint xorshift { get { _xsi.MoveNext(); return _xsi.Current; } }
        static IEnumerator<uint> _xsi = _xsc();
        static IEnumerator<uint> _xsc() { uint x = 123456789, y = 362436069, z = 521288629, w = (uint)(DateTime.Now.Ticks & 0xffffffff); while (true) { var t = x ^ (x << 11); x = y; y = z; z = w; w = (w ^ (w >> 19)) ^ (t ^ (t >> 8)); yield return w; } }
    }
}
namespace Library {
    class LIB_FastIO
    {
        public LIB_FastIO() { str = Console.OpenStandardInput(); }
        readonly Stream str;
        readonly byte[] buf = new byte[1024];
        int len, ptr;
        public bool isEof = false;
        public bool IsEndOfStream { get { return isEof; } }
        byte read()
        {
            if (isEof) throw new EndOfStreamException();
            if (ptr >= len)
            {
                ptr = 0;
                if ((len = str.Read(buf, 0, 1024)) <= 0)
                {
                    isEof = true;
                    return 0;
                }
            }
            return buf[ptr++];
        }
        char Char()
        {
            byte b = 0;
            do b = read();
            while (b < 33 || 126 < b);
            return (char)b;
        }
        virtual public string Scan()
        {
            var sb = new StringBuilder();
            for (var b = Char(); b >= 33 && b <= 126; b = (char)read())
                sb.Append(b);
            return sb.ToString();
        }
        virtual public long Long()
        {
            long ret = 0; byte b = 0; var ng = false;
            do b = read();
            while (b != '-' && (b < '0' || '9' < b));
            if (b == '-') { ng = true; b = read(); }
            for (; true; b = read())
            {
                if (b < '0' || '9' < b)
                    return ng ? -ret : ret;
                else ret = ret * 10 + b - '0';
            }
        }
        virtual public double Double() { return double.Parse(Scan(), CultureInfo.InvariantCulture); }
    }
    class LIB_FastIODebug : LIB_FastIO
    {
        Queue<string> param = new Queue<string>();
        string NextString() { if (param.Count == 0) foreach (var item in Console.ReadLine().Split(' ')) param.Enqueue(item); return param.Dequeue(); }
        public LIB_FastIODebug() { }
        public override string Scan() => NextString();
        public override long Long() => long.Parse(NextString());
        public override double Double() => double.Parse(NextString());
    }
    class LIB_Deque<T>
    {
        T[] array;
        int front, cap;
        public int Count;
        public T this[long i]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get { return array[GetIndex((int)i)]; }
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            set { array[GetIndex((int)i)] = value; }
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public LIB_Deque(long cap = 16)
        {
            array = new T[this.cap = (int)cap];
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        int GetIndex(int i)
        {
            if (i >= cap) throw new Exception();
            var r = front + i;
            return r >= cap ? r - cap : r;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void PushFront(T x)
        {
            if (Count == cap) Extend();
            if (--front < 0) front += array.Length;
            array[front] = x;
            ++Count;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T PopFront()
        {
            if (Count-- == 0) throw new Exception();
            var r = array[front++];
            if (front >= cap) front -= cap;
            return r;
        }
        public T Front => array[front];
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void PushBack(T x)
        {
            if (Count == cap) Extend();
            var i = front + Count++;
            array[i >= cap ? i - cap : i] = x;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T PopBack()
        {
            if (Count == 0) throw new Exception();
            return array[GetIndex(--Count)];
        }
        public T Back => array[GetIndex(Count - 1)];
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        void Extend()
        {
            T[] nb = new T[cap << 1];
            if (front > cap - Count)
            {
                var l = array.Length - front; Array.Copy(array, front, nb, 0, l);
                Array.Copy(array, 0, nb, l, Count - l);
            }
            else Array.Copy(array, front, nb, 0, Count);
            array = nb; front = 0; cap <<= 1;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void Insert(long i, T x)
        {
            if (i > Count) throw new Exception();
            this.PushFront(x);
            for (int j = 0; j < i; j++) this[j] = this[j + 1];
            this[i] = x;
        }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public T RemoveAt(long i)
        {
            if (i < 0 || i >= Count) throw new Exception();
            var r = this[i];
            for (var j = i; j > 0; j--) this[j] = this[j - 1];
            this.PopFront();
            return r;
        }
    }
}