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



Sample input:
3
1 2
2 3
3 4
3
1 1
2 5
3 5


Sample output:
0
3
3

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#solve
def solve():
    n = II()
    vw = LIR(n)
    nbit = 1 << n.bit_length()
    b = [i.bit_length() for i in range(nbit)]
    dp = [[None] * b[i] for i in range(nbit)]
    dp[1] = [(vw[0][0], vw[0][1])]
    for i in range(1 , nbit >> 1):
        dpi = dp[i]
        if 2 * i + 1 <= n:
            v1, w1 = vw[2 * i]
            v0, w0 = vw[2 * i - 1]
            dp21 = dp[2 * i + 1]
            dp20 = dp[2 * i]
            for i, j in enumerate(dpi):
                dp21[i] = j
                dp20[i] = j
            dp21[i + 1] = (v1, w1)
            dp20[i + 1] = (v0, w0)
        elif 2 * i <= n:
            v0, w0 = vw[2 * i - 1]
            dp20 = dp[2 * i]
            for i, j in enumerate(dpi):
                dp20[i] = j
            dp20[i + 1] = (v0, w0)
    M = 10 ** 5 + 1
    d = [[0] * M for _ in range(1 << n.bit_length() // 2)]
    for i in range(1, 1 << n.bit_length() // 2):
        d1 = defaultdict(int)
        d1[0] = 0
        di = d[i]
        for v, w in dp[i]:
            for key, value in list(d1.items()):
                keyw = key + w
                valuev = value + v
                if keyw >= M: continue
                if d1[keyw] < valuev:
                    d1[keyw] = valuev
                    di[keyw] = valuev
        for j in range(M - 1):
            if di[j + 1] < di[j]:
                di[j + 1] = di[j]
    for _ in range(II()):
        V, L = LI()
        t = dp[V]
        lent = V.bit_length()
        n1 = lent // 2
        n2 = lent - n1
        vw2 = t[n1:]
        V = V >> n2
        d1 = defaultdict(int)
        d1[0] = 0
        ans = 0
        dv = d[V]
        for v, w in vw2:
            for key, value in list(d1.items()):
                keyw = key + w
                valuev = value + v
                if keyw > L: continue
                if d1[keyw] < valuev:
                    d1[keyw] = valuev
                    if dv[L - keyw] + valuev > ans:
                        ans = dv[L - keyw] + valuev
        print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
N = int(input())
V = []
W = []

for _ in range(N):
    v, w = map(int,input().split())
    V.append(v)
    W.append(w)

L = [[-1 for j in range(10 ** 5 + 1)] for j in range(2 ** 9)]
L[0][0] = 0

for i in range(min(N, 2 ** 9 - 1)):
    for j in range(10 ** 5 + 1):
        L[i+1][j] = max(L[i+1][j], L[(i+1)//2][j])
        if j + W[i] <= 10 ** 5:
            L[i+1][j+W[i]] = max(L[(i+1)//2][j] + V[i], L[i+1][j+W[i]])
        if j != 0:
            L[i+1][j] = max(L[i+1][j], L[i+1][j-1])

Q = int(input())
for _ in range(Q):
    v, l = map(int,input().split())
    if v < 2 ** 9:
        print(L[v][l])
    else:
        ans = 0
        K = []
        while v >= 2 ** 9:
            K.append(v-1)
            v //= 2
        for i in range(len(K) ** 2):
            tmp_v = 0
            tmp_w = 0
#             for j in range(K):
#                 if i & 1:
#                     tmp_v += V[K[j]]
#                     tmp_w += W[K[j]]
#                 i >>= 1
            if l - tmp_w >= 0:
                ans = max(ans, L[v][l-tmp_w] + tmp_v)
        print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
V = []
W = []

for _ in range(N):
    v, w = map(int,input().split())
    V.append(v)
    W.append(w)

L = [[-1 for j in range(10 ** 5 + 1)] for j in range(2 ** 9)]
L[0][0] = 0

for i in range(min(N, 2 ** 9 - 1)):
    for j in range(10 ** 5 + 1):
        L[i+1][j] = max(L[i+1][j], L[(i+1)//2][j])
        if j + W[i] <= 10 ** 5:
            L[i+1][j+W[i]] = max(L[(i+1)//2][j] + V[i], L[i+1][j+W[i]])
        if j != 0:
            L[i+1][j] = max(L[i+1][j], L[i+1][j-1])

Q = int(input())
for _ in range(Q):
    v, l = map(int,input().split())
    if v < 2 ** 9:
        print(L[v][l])
    else:
        ans = 0
        K = []
        while v >= 2 ** 9:
            K.append(v-1)
            v //= 2
        for i in range(len(K) ** 2):
            tmp_v = 0
            tmp_w = 0
#             for j in range(K):
#                 if i & 1:
#                     tmp_v += V[j]
#                     tmp_w += W[j]
#                 i >>= 1
            if l - tmp_w >= 0:
                ans = max(ans, L[v][l-tmp_w] + tmp_v)
        print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline


# 入力
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]


tree_height = n.bit_length()
half_height = tree_height // 2
half_n = 2 ** half_height

items = [[] for i in range(n)]
items[0].append((0, 0))
items[0].append((info[0][1], info[0][0]))

for i in range(1, half_n):
    val, wei = info[i]
    for w, v in items[(i + 1) // 2 - 1]:
        items[i].append((w, v))
        items[i].append((w + wei, v + val))
    items[i].sort()

for i in range(half_n, n):
    if (i + 1) // 2 - 1 < half_n:
        items[i].append((info[i][1], info[i][0]))
        items[i].append((0, 0))
    else:
        val, wei = info[i]
        for w, v in items[(i + 1) // 2 - 1]:
            items[i].append((w, v))
            items[i].append((w + wei, v + val))
        items[i].sort(reverse=True)


for i, l in query:
    ans = 0
    if i <= half_n:
        i -= 1
        for w, v in items[i]:
            if w <= l:
                ans = max(ans, v)
        print(ans)
    else:
        ind = i
        while ind > half_n:
            ind //= 2
        ind -= 1
        i -= 1
        max_ = 0
        left = 0
        for w, v in items[i]:
            while left < len(items[ind]):
                w2, v2 = items[ind][left]
                if w2 + w > l:
                    break
                max_ = max(max_, v2)
                left += 1
            ans = max(max_ + v, ans)
        print(ans)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.buffer.readline


# 入力
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
q = int(input())
query = [list(map(int, input().split())) for i in range(q)]


tree_height = n.bit_length()
half_height = tree_height // 2
half_n = 2 ** half_height

items = [[] for i in range(n)]
items[0].append((0, 0))
items[0].append((info[0][1], info[0][0]))

for i in range(1, half_n):
    val, wei = info[i]
    for w, v in items[(i + 1) // 2 - 1]:
        items[i].append((w, v))
        items[i].append((w + wei, v + val))
    items[i].sort()

for i in range(half_n, n):
    if (i + 1) // 2 - 1 < half_n:
        items[i].append((info[i][1], info[i][0]))
        items[i].append((0, 0))
    else:
        val, wei = info[i]
        for w, v in items[(i + 1) // 2 - 1]:
            items[i].append((w, v))
            items[i].append((w + wei, v + val))
        items[i].sort(reverse=True)


for i, l in query:
    ans = 0
    if i <= half_n:
        i -= 1
        for w, v in items[i]:
            if w <= l:
                ans = max(ans, v)
        print(ans)
    else:
        ind = i
        while ind > half_n:
            ind //= 2
        ind -= 1
        i -= 1
        max_ = 0
        left = 0
        print(items[i], items[ind])
        for w, v in items[i]:
            while left < len(items[ind]):
                w2, v2 = items[ind][left]
                if w2 + w > l:
                    break
                max_ = max(max_, v2)
                left += 1
            ans = max(max_ + v, ans)
        print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
V = []
W = []
for _ in range(n):
    v, w = LI()
    V.append(v)
    W.append(w)

q = I()
vl = []
maxL = 0
for _ in range(q):
    v, l = LI()
    maxL = max(maxL, l)
    vl.append([v,l])

m = min(n, 1 << 10)
dp = [[0]*(maxL + 1) for _ in range(m + 1)]

for i in range(1, m+1):
    v, w = V[i-1], W[i-1]
    for j in range(maxL+1):
        if j < w:
            dp[i][j] = dp[i>>1][j]
        else:
            dp[i][j] = max(dp[i>>1][j], dp[i>>1][j - w] + v)


for i in range(q):
    v, L = vl[i]
    if v <= m:
        print(dp[v][L])
        continue
    x = v.bit_length() - m.bit_length()
    ret = 0
    for j in range(1 << x):
        weight_sum = 0
        value_sum = 0
        tmp = v
        idx = j
        for _ in range(x):
            if idx & 1:
                weight_sum += W[tmp - 1]
                if weight_sum > L:
                    break
                value_sum += V[tmp - 1]
            tmp >>= 1
            idx >>= 1
        else:
            value_sum += dp[tmp>>1][L - weight_sum]
            ret = max(ret, value_sum)
    print(ret)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#solve
def solve():
    n = II()
    vw = LIR(n)
    dp = [[i] for i in range(1 << n.bit_length())]
    for i in range(1, 1 << n.bit_length() - 1):
        dp[2 * i] = dp[i] + dp[2 * i]
        dp[2 * i + 1] = dp[i] + dp[2 * i + 1]
    for i in range(1, n + 1):
        t = dp[i]
        dp[i] = []
        dpi = dp[i]
        for j in t:
            if j <= n:
                v, w = vw[j - 1]
                dpi.append((v, w))
    M = 10 ** 5 + 1
    d = [[0] * M for _ in range(1 << len(dp[n]) // 2)]
    for i in range(1, (1 << len(dp[n]) // 2)):
        d1 = defaultdict(int)
        d1[0] = 0
        di = d[i]
        for v, w in dp[i]:
            for key, value in list(d1.items()):
                if key + w >= M: continue
                if d1[key + w] < value + v:
                    d1[key + w] = value + v
                    di[key + w] = value + v
        for j in range(M - 1):
            if di[j + 1] < di[j]:
                di[j + 1] = di[j]
    return
    for _ in range(II()):
        V, L = LI()
        t = dp[V]
        n1 = len(t) // 2
        n2 = len(t) - n1
        vw2 = t[n1:]
        V = V >> n2
        d1 = defaultdict(int)
        d1[0] = 0
        for v, w in vw2:
            for key, value in list(d1.items()):
                if d1[key + w] < value + v:
                    d1[key + w] = value + v
                    di[key + w] = value + v
        ans = 0
        dv = d[V]
        for w, v in d1.items():
            if L - w < 0: continue
            if dv[L - w] + v > ans:
                ans = dv[L - w] + v
        print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
from decimal import Decimal


INF = 10 ** 13
sys.setrecursionlimit(2147483647)
def TI(): return tuple(map(int, sys.stdin.buffer.readline().split()))
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


def merge(a, b):
    i, j = 0, 0
    res = []
    while i < len(a) or j < len(b):
        if i < len(a) and (j >= len(b) or a[i][0] < b[j][0]):
            w, v = a[i]
            i += 1
        else:
            w, v = b[j]
            j += 1
        if v > 10 ** 5:
            break
        if not res or res[-1][1] < v:
            res += [(w, v)]
        elif res[-1][0] == w and res[-1][1] <= v:
            res[-1] = (w, v)
    return res

def best(L, a, b):
    res = 0
    i = 0
    j = len(b) - 1
    while i < len(a):
        w, v = a[i]
        if j < 0:
            break
        if b[j][0] + w > L:
            j -= 1
            continue
        res = max(res, v + b[j][1])
        i += 1
    return res

def main():
    n = I()
    VW = [(-1, -1)]
    for _ in range(n):
        VW += [TI()]

    q = I()
    query = tuple(TI() for _ in range(q))
    dp = [[] for _ in range(2048)]
    dp[0] = [(0, 0)]
    for i in range(1, min(n + 1, 2048)):
        vi, wi = VW[i]
        a1 = dp[i // 2]
        a2 = [(w + wi, v + vi) for w, v in a1]
        dp[i] = merge(a1, a2)

    for m, l in query:
        a = [(0, 0)]
        while m >= 2048:
            vi, wi = VW[m]
            b = [(w + wi, v + vi) for w, v in a]
            a = merge(a, b)
            n //= 2
        print(best(l, a, dp[m]))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
from numba import njit
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit('(i4,i4[:],i4[:])',cache=True)
def precompute(n,v,w):
    dp = np.zeros((1024,10**5+1),np.int32)
    for i in range(1,min(1024,n+1)):
        vi = v[i]
        wi = w[i]
        p = i//2
        dp[i]=dp[p]
        for j in range(wi,10**5+1):
            dp[i][j] = max(dp[i][j],dp[p][j-wi]+vi)
    return dp

@njit('(i4,i4[:],i4[:],i4[:],i4[:])',cache=True)
def main(n,v,w,vq,lq):
    dp = precompute(n,v,w)
    values = np.empty(1024,np.int32)
    weights = np.empty(1024,np.int32)

    def solve(V,L,values,weights,dp):
        if V < 1024:
            return dp[V][L]
        values[0] = 0
        weights[0] = 0
        p = 0
        while V >= 1024:
            for j in range(1 << p):
                values[j + (1 << p)] = values[j]+ v[V]
                weights[j + (1 << p)] = weights[j] + w[V]
            p += 1
            V >>= 1
            ans = 0
        for i in range(1 << p):
            if weights[i] <= L:
                x = dp[V][L-weights[i]] + values[i]
                ans = max(ans,x)
            return ans
    q = len(vq)
    for i in range(q):
        x = solve(vq[i],lq[i],values,weights,dp)
        print(x)
       
n = int(readline())
stdin = np.array(read().split(),np.int32)
v = np.zeros(n+1,np.int32)
w = np.zeros(n+1,np.int32)
v[1:] = stdin[:2*n:2]
w[1:] = stdin[1:2*n:2]
query = stdin[2*n+1:]
vq = query[::2]
lq = query[1::2]

main(n,v,w,vq,lq)

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.readline

    n = int(input())

    L_MAX = 10**5
    D_TH = 9
    V_MAX = (1 << D_TH) + 50 - 1
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]
    # items = []
    items_v = []
    items_w = []

    for i in range(n):
        val, w = map(int, input().split())
        if i < V_MAX:
            i1 = i + 1
            i0 = (i - 1) // 2 + 1
            for j in range(L_MAX + 1):
                if j < w:
                    dp[i1][j] = dp[i0][j]
                else:
                    dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)
        else:
            # items.append((val, w))
            items_v.append(val)
            items_w.append(val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v < V_MAX:
            ans = dp[v + 1][l]
        else:
            vv = []
            ww = []
            while v >= V_MAX:
                # vv.append(items[v - V_MAX][0])
                # ww.append(items[v - V_MAX][1])
                vv.append(items_v[v - V_MAX])
                ww.append(items_w[v - V_MAX])
                v = (v - 1) >> 1

            ans = dp[v + 1][l]
            # m = len(vv)
            m2 = 1 << len(vv)
            v_sub = [0] * m2
            w_sub = [0] * m2
            for bit in range(1, m2):
                bit_min = bit & (-bit)
                x = bit_min.bit_length() - 1

                s_w = w_sub[bit - bit_min] + ww[x]
                w_sub[bit] = s_w
                if s_w <= l:
                    s_val = v_sub[bit - bit_min] + vv[x]
                    v_sub[bit] = s_val
                    ans = max(ans, dp[v + 1][l - s_w] + s_val)
            # print(w_sub)
            # print(v_sub)
            # print([dp[v + 1][l - w_sub[i]] + v_sub[i] for i in range(1 << m)])

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
import bisect
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)


def merge(a, b):
    res = []
    i, j = 0, 0
    while i < len(a) or j < len(b):
        if j >= len(b) or (i < len(a) and a[i][0] < b[j][0]):
            w, v = a[i]
            i += 1
        else:
            w, v = b[j]
            j += 1
        if not res or (res[-1][1]) < v:
            res.append((w, v))
        elif res[-1][0] == w and res[-1][1] <= v:
            res.pop()
            res.append((w, v))
    return res


def best(L, a, b):
    res = 0
    i = 0
    j = len(b) - 1
    # for w, v in a:
    while i < len(a):
        w, v = a[i]
        if j < 0:
            break
        if b[j][0] + w > L:
            j -= 1
            continue
        res = max(res, v + b[j][1])
        i += 1
    return res


def main():
    N = int(input())
    VW = [(-1, -1)] + [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    query = tuple(tuple(map(int, input().split())) for _ in range(Q))

    dp = [[] for _ in range(4)]
    dp[0] = [(0, 0)]
    for i in range(1, min(N + 1, 4)):
        vi, wi = VW[i]
        a1 = dp[i // 2]
        a2 = [(w + wi, v + vi) for w, v in a1]
        dp[i] = merge(a1, a2)

    for i in range(4):
        print(dp[i])

    for n, L in query:
        if n < 4:
            w, v = zip(*dp[n])
            i = bisect.bisect_right(w, L) - 1
            print(v[i])
        else:
            a = [(0, 0)]
            while n >= 4:
                vi, wi = VW[n]
                b = [(w + wi, v + vi) for w, v in a]
                a = merge(a, b)
                n //= 2
            print(best(L, a, dp[n]))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  import math
  from collections import deque
  N = int(input())
  VW = [list(map(int,input().split())) for _ in range(N)]
  Q = int(input())
  vL = [list(map(int,input().split())) for _ in range(Q)]
  M = 0
  for v,L in vL:
    M = max(L,M)
    
  D = int(math.log2(N)) + 1
  K = D//2
  multiplier = 2**K
  M_plu = M+1
  Ddp = tuple([[0] * (M_plu) for _ in range(multiplier)])
  
  mi_mul = multiplier-1
  tmp = VW[:mi_mul]
  for i,(V,W) in enumerate(tmp,1):
    x = i//2
    for j in range(M_plu):
      if W<=j:
        Ddp[i][j] = max(Ddp[x][j-W] + V, Ddp[x][j])
      else:
        Ddp[i][j] = Ddp[x][j]

main()

Submission status: Wrong Answer

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  import math
  from collections import deque
  N = int(input())
  VW = [list(map(int,input().split())) for _ in range(N)]
  Q = int(input())
  vL = [list(map(int,input().split())) for _ in range(Q)]
  M = 0
  for v,L in vL:
    M = max(L,M)
    
  D = int(math.log2(N)) + 1
  K = D//2
  multiplier = 2**K
  M_plu = M+1
  Ddp = [[0] * (M_plu) for _ in range(multiplier)]
  
  mi_mul = multiplier-1
  tmp = VW[:mi_mul]
  for i,(V,W) in enumerate(tmp,1):
    x = i//2
    for j in range(M_plu):
      if W<=j:
        Ddp[i][j] = max(Ddp[x][j-W] + V, Ddp[x][j])
      else:
        Ddp[i][j] = Ddp[x][j]
        
  for v,L in vL:
    if v<=mi_mul:
      print(Ddp[v][L])
      continue
      
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      x_K = x-K
      for i in range(x_K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      
      for i in range(2**length):
        a,b = 0,0

    print(ans)
main()

Submission status: Wrong Answer

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  import math
  from collections import deque
  N = int(input())
  VW = [list(map(int,input().split())) for _ in range(N)]
  Q = int(input())
  vL = [list(map(int,input().split())) for _ in range(Q)]
  M = 0
  for v,L in vL:
    M = max(L,M)
    
  D = int(math.log2(N)) + 1
  K = D//2
  multiplier = 2**K
  M_plu = M+1
  Ddp = [[0] * (M_plu) for _ in range(multiplier)]
  
  mi_mul = multiplier-1
  tmp = VW[:mi_mul]
  for i,(V,W) in enumerate(tmp,1):
    x = i//2
    for j in range(M_plu):
      if W<=j:
        Ddp[i][j] = max(Ddp[x][j-W] + V, Ddp[x][j])
      else:
        Ddp[i][j] = Ddp[x][j]
        
  for v,L in vL:
    if v<=mi_mul:
      print(Ddp[v][L])
      continue
      
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      x_K = x-K
      for i in range(x_K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      mul = 2**length
      for i in range(mul):
        z = [0,0]

    print(ans)
main()

Submission status: Wrong Answer

Solution code:
import sys
import bisect
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)


def merge(a, b):
    res = []
    i, j = 0, 0
    while i < len(a) or j < len(b):
        if j >= len(b) or (i < len(a) and a[i][0] < b[j][0]):
            w, v = a[i]
            i += 1
        else:
            w, v = b[j]
            j += 1
        if not res or (res[-1][1]) < v:
            res.append((w, v))
        elif res[-1][0] == w and res[-1][1] <= v:
            res.pop()
            res.append((w, v))
    return res


def best(L, a, b):
    res = 0
    i = len(b) - 1
    for w, v in a:
        if i < 0:
            break
        if b[i][0] + w > L:
            i -= 1
            continue
        res = max(res, v + b[i][1])
    return res


def main():
    N = int(input())
    VW = [(-1, -1)] + [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    query = tuple(tuple(map(int, input().split())) for _ in range(Q))

    dp = [[] for _ in range(1024)]
    dp[0] = [(0, 0)]
    for i in range(1, min(N + 1, 1024)):
        vi, wi = VW[i]
        a1 = dp[i // 2]
        a2 = [(w + wi, v + vi) for w, v in a1]
        dp[i] = merge(a1, a2)

    for n, L in query:
        if n < 1024:
            w, v = zip(*dp[n])
            i = bisect.bisect_right(w, L) - 1
            print(v[i])
        else:
            a = [(0, 0)]
            while n >= 1024:
                vi, wi = VW[n]
                b = [(w + wi, v + vi) for w, v in a]
                a = merge(a, b)
                n //= 2
            print(best(L, a, dp[n]))


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  import math
  from collections import deque
  N = int(input())
  VW = [list(map(int,input().split())) for _ in range(N)]
  Q = int(input())
  vL = [list(map(int,input().split())) for _ in range(Q)]
  M = 0
  for v,L in vL:
    M = max(L,M)
    
  D = int(math.log2(N)) + 1
  K = D//2
  multiplier = 2**K
  M_plu = M+1
  Ddp = [[0] * (M_plu) for _ in range(multiplier)]
  
  mi_mul = multiplier-1
  tmp = VW[:mi_mul]
  for i,(V,W) in enumerate(tmp,1):
    x = i//2
    for j in range(M_plu):
      if W<=j:
        Ddp[i][j] = max(Ddp[x][j-W] + V, Ddp[x][j])
      else:
        Ddp[i][j] = Ddp[x][j]
        
  for v,L in vL:
    if v<=mi_mul:
      print(Ddp[v][L])
      continue
      
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      x_K = x-K
      for i in range(x_K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      
      for i in range(2**length):
        z = [0,0]
        for j in range(length):
          continue

    print(ans)
main()

Submission status: Wrong Answer

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  import math
  from collections import deque
  N = int(input())
  VW = [list(map(int,input().split())) for _ in range(N)]
  Q = int(input())
  vL = [list(map(int,input().split())) for _ in range(Q)]
  M = 0
  for v,L in vL:
    M = max(L,M)
    
  D = int(math.log2(N)) + 1
  K = D//2
  multiplier = 2**K
  M_plu = M+1
  Ddp = [[0] * (M_plu) for _ in range(multiplier)]
  
  mi_mul = multiplier-1
  tmp = VW[:mi_mul]
  for i,(V,W) in enumerate(tmp,1):
    x = i//2
    for j in range(M_plu):
      if W<=j:
        Ddp[i][j] = max(Ddp[x][j-W] + V, Ddp[x][j])
      else:
        Ddp[i][j] = Ddp[x][j]
        
  for v,L in vL:
    if v<=mi_mul:
      print(Ddp[v][L])
      continue
      
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      x_K = x-K
      for i in range(x_K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      mul = 2**length
      for i in range(2**mul):
        z = [0,0]

    print(ans)
main()

Submission status: Wrong Answer

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  import math
  from collections import deque
  N = int(input())
  VW = [list(map(int,input().split())) for _ in range(N)]
  Q = int(input())
  vL = [list(map(int,input().split())) for _ in range(Q)]
  M = 0
  for v,L in vL:
    M = max(L,M)
    
  D = int(math.log2(N)) + 1
  K = D//2
  multiplier = 2**K
  M_plu = M+1
  Ddp = [[0] * (M_plu) for _ in range(multiplier)]
  
  mi_mul = multiplier-1
  tmp = VW[:mi_mul]
  for i,(V,W) in enumerate(tmp,1):
    x = i//2
    for j in range(M_plu):
      if W<=j:
        Ddp[i][j] = max(Ddp[x][j-W] + V, Ddp[x][j])
      else:
        Ddp[i][j] = Ddp[x][j]
        
  for v,L in vL:
    if v<=mi_mul:
      print(Ddp[v][L])
      continue
      
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      x_K = x-K
      for i in range(x_K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      
      for i in range(2**length):
        z = [0,0]

    print(ans)
main()

Submission status: Wrong Answer

Solution code:
def main():
  import sys
  input = sys.stdin.readline
  import math
  from collections import deque
  N = int(input())
  VW = [list(map(int,input().split())) for _ in range(N)]
  Q = int(input())
  vL = [list(map(int,input().split())) for _ in range(Q)]
  M = 0
  for v,L in vL:
    M = max(L,M)
    
  D = int(math.log2(N)) + 1
  K = D//2
  multiplier = 2**K
  M_plu = M+1
  Ddp = [[0] * (M_plu) for _ in range(multiplier)]
  
  mi_mul = multiplier-1
  tmp = VW[:mi_mul]
  for i,(V,W) in enumerate(tmp,1):
    x = i//2
    for j in range(M_plu):
      if W<=j:
        Ddp[i][j] = max(Ddp[x][j-W] + V, Ddp[x][j])
      else:
        Ddp[i][j] = Ddp[x][j]
        
  for v,L in vL:
    if v<=mi_mul:
      print(Ddp[v][L])
      continue
      
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      x_K = x-K
      for i in range(x_K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
main()