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:
import sys
input = sys.stdin.buffer.readline

MAX = (1<<11)

def main():
    N = int(input())
    VW = [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    dp = [[] for _ in range(MAX+1)]
    dp[0] = [(0, 0)]
    for k in range(min(MAX, N)):
        nv, nw = VW[k]
        k += 1
        ndp = []
        for v, w in dp[k//2]:
            ndp.append((v+nv, w+nw))
        ind = 0
        for v, w in dp[k//2]:
            while ind < len(ndp) and ndp[ind][1] < w:
                dp[k].append(ndp[ind])
                ind += 1
            if ind < len(ndp) and ndp[ind][1] == w:
                if ndp[ind][0] > v:
                    dp[k].append(ndp[ind])
                else:
                    dp[k].append((v, w))
                ind += 1
            else:
                dp[k].append((v, w))
        while ind < len(ndp):
            dp[k].append(ndp[ind])
            ind += 1

    for s, L in Query:
        dp2 = [(0, 0)]
        # make new dp
        while s >= MAX:
            nv, nw = VW[s-1]
            ndp = []
            for v, w in dp2:
                if w + nw <= L:
                    ndp.append((v+nv, w+nw))
            ind = 0
            new = []
            for v, w in dp2:
                while ind < len(ndp) and ndp[ind][1] < w:
                    new.append(ndp[ind])
                    ind += 1
                if ind < len(ndp) and ndp[ind][1] == w:
                    if ndp[ind][0] > v:
                        new.append(ndp[ind])
                    else:
                        new.append((v, w))
                    ind += 1
                else:
                    new.append((v, w))
            while ind < len(ndp):
                new.append(ndp[ind])
                ind += 1
            dp2 = new
            s = s//2
        
        # merge
        ind2 = len(dp2)-1
        ans = 0
        for v, w in dp[s]:
            while ind2 > 0 and dp2[ind2][1] + w > L:
                ind2 -= 1
            if ind2 == 0 and dp2[ind2][1] + w > L: break
            score = dp2[ind2][0] + v
            if score > ans:
                ans = score
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

#solve
def solve():
    input = sys.stdin.buffer.readline
    LI = lambda: map(int, input().split())
    II = lambda: int(input())
    n = II()
    vw = [[]] * n
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    XX = 1 << n.bit_length() // 2
    d = [[]] * XX
    d[0] = M0
    for i in range(1, XX):
        v, w = LI()
        vw[i - 1] = (v, w)
        di = d[i // 2][:]
        for j in range(M - 1, w - 1, -1):
            if di[j] < di[j - w] + v:
                di[j] = di[j - w] + v
        d[i] = di
    for i in range(XX, n + 1):
        v, w = LI()
        vw[i - 1] = (v, w)
    return
    n = [pow(2, i) for i in range(18)]
    lentl = [i - i // 2 for i in range(19)]
    for _ in range(II()):
        V, L = LI()
        if V < XX:
            print(d[V][L])
            continue
        n2 = lentl[V.bit_length()]
        vw2 = [None] * n2
        for i in range(n2):
            vw2[i] = (vw[V - 1][0], vw[V - 1][1])
            V //= 2
        lw = [0] * n[n2]
        lv = [0] * n[n2]
        dv = d[V]
        ans = dv[L]
        for mask in range(1, n[n2]):
            a = mask & -mask
            b = a.bit_length() - 1
            v, w = vw2[b]
            maska = mask - a
            ww = lw[maska] + w
            Lww = L - ww
            lw[mask] = ww
            if Lww < 0: continue
            vv = lv[maska] + v
            lv[mask] = vv
            tmp = dv[Lww] + vv
            if tmp > ans:
                ans = tmp
        print(ans)
    return

if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

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

def main():
    import sys
    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
        cnt = 0
        tmp = v
        v_ = []
        w_ = []
        while tmp > m:
            v_.append(V[tmp-1])
            w_.append(W[tmp-1])
            tmp >>= 1
            cnt += 1
        ret = 0
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
V = [None]*n
W = [None]*n
for i in range(n):
    V[i],W[i] = map(int, input().split())

from queue import deque
q = deque([0])
d = [None]*n
d[0] = [(0,0), (W[0], V[0])]

until = min(n, 2**12-1)

def sub0(l, w, v):
#     ll = list((ww+w, vv+v) for ww,vv in l)
    nl = [(0,0)]
    i1 = 0
    i2 = 0
    length = len(l)
    pv = 0
    while i1<length or i2<length:
        if i1<length and l[i1][0]<l[i2][0]+w:
            if l[i1][1]>pv:
                nl.append(l[i1])
                pv = l[i1][0]
            i1 += 1
        elif i2<length:
            w2, v2 = l[i2][0]+w, l[i2][1]+v
            if v2>pv:
                nl.append((w2,v2))
                pv = v2
            i2 += 1      
    return nl


# def sub0(l, w, v):
#     ll = tuple((ww+w, vv+v) for ww,vv in l)
#     nl = [(0,0)]
#     i1 = 0
#     i2 = 0
#     length = len(l)
#     while i1<length or i2<length:
#         if i1<length and (i2>=length or l[i1][0]<ll[i2][0]):
#             if l[i1][1]>nl[-1][1]:
#                 nl.append(l[i1])
#             i1 += 1
#         elif i2<length:
#             if ll[i2][1]>nl[-1][1]:
#                 nl.append(ll[i2])
#             i2 += 1      
#     return nl

# until = n
while q:
    u = q.pop()
    l = d[u]
    for v in (2*u+1, 2*u+2):
        if v>=until:
            continue
        nl = sub0(l, W[v], V[v])
        d[v] = nl
#         print(l, ll, nl)
        q.appendleft(v)

from bisect import bisect_right as br
def sub(vv, L):
    if d[vv] is None:
        ll = [(0,0)]
        while d[vv] is None:
            ll = sub0(ll, W[vv], V[vv])
            vv = (vv-1)//2
        tmp = ll
    else:
        tmp = [(0,0)]
    l = d[vv]
    ans = -1
    
    for w1,v1 in tmp:
        if w1>L:
            continue
        out = br(l, (L-w1, float("inf")))
        ans = max(ans, l[out-1][1]+v1)
    return ans
        
q = int(input())
ans = [None]*q
for i in range(q):
    vv, ll = map(int, input().split())
    vv -= 1
    ans[i] = sub(vv, ll)
write("\n".join(map(str, ans)))

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


n = int(input())
V = [None]*n
W = [None]*n
for i in range(n):
    V[i],W[i] = map(int, input().split())

from queue import deque
q = deque([0])
d = [None]*n
d[0] = [(0,0), (W[0], V[0])]

until = min(n, 2**12-1)

def sub0(l, w, v):
#     ll = list((ww+w, vv+v) for ww,vv in l)
    nl = [(0,0)]
    i1 = 0
    i2 = 0
    length = len(l)
    while i1<length or i2<length:
        if i1<length and l[i1][0]<l[i2][0]+w:
            if l[i1][1]>nl[-1][1]:
                nl.append(l[i1])
            i1 += 1
        elif i2<length:
            if l[i2][1]+v>nl[-1][1]:
                nl.append((l[i2][0]+w, l[i2][1]+v))
            i2 += 1      
    return nl

# until = n
while q:
    u = q.pop()
    l = d[u]
    for v in (2*u+1, 2*u+2):
        if v>=until:
            continue
        nl = sub0(l, W[v], V[v])
        d[v] = nl
#         print(l, ll, nl)
        q.appendleft(v)

from bisect import bisect_right as br

def sub(vv, L):
    if d[vv] is None:
        ll = [(0,0), (W[vv], V[vv])]
        while d[vv] is None:
            vv = (vv-1)//2
            ll = sub0(ll, W[vv], V[vv])
#             ll.extend(list((wt+W[vv], vt+V[vv]) for wt,vt in ll))
        tmp = ll
    else:
        tmp = [(0,0)]
    l = d[vv]
    ans = -1
    
    for w1,v1 in tmp:
        if w1>L:
            continue
        out = br(l, (L-w1, float("inf")))
        ans = max(ans, l[out-1][1]+v1)
    return ans
        
q = int(input())
ans = [None]*q
for i in range(q):
    vv, ll = map(int, input().split())
    vv -= 1
    ans[i] = sub(vv, ll)
write("\n".join(map(str, ans)))

Submission status: Wrong Answer

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 9, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1].copy()
    for x in range(weight_limit, w - 1, -1):
        dp[x] = max(dp[x], dp[x - w] + v)
    precalc.append(dp)

# time debug
exit()

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp = {0: 0}
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for cw, cv in list(dp.items()):
            nw = cw + w
            nv = cv + v
            if nw > weight_limit:
                continue
            if nw not in dp or dp[nw] < nv:
                dp[nw] = nv
        u >>= 1
    ans = max(v + precalc[u][l - w] for w, v in dp.items())
    buf.append(ans)

print('\n'.join(map(str, buf)))

Submission status: Wrong Answer

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 10, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1].copy()
    for x in range(weight_limit, w - 1, -1):
        dp[x] = max(dp[x], dp[x - w] + v)
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp = {0: 0}
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for cw, cv in list(dp.items()):
            nw = cw + w
            nv = cv + v
            if nw > weight_limit:
                continue
            if nw not in dp or dp[nw] < nv:
                dp[nw] = nv
        u >>= 1
    ans = max(v + precalc[u][l - w] for w, v in dp.items())
    buf.append(ans)

print('\n'.join(map(str, buf)))

Submission status: Wrong Answer

Solution code:
import sys
from math import log2
def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    item = [(0, 0)]
    for _ in range(N):
        v, w = map(int, input().split())
        item.append((v, w))
    queri = []
    L = 0 # L = max(l_i)
    Q = int(input())
    for _ in range(Q):
        v, l = map(int, input().split())
        queri.append((v, l))
        L = max(L, l)

    """
    各クエリごとにナップサックをやったら間に合わないが、
    本問ではこれを木の上半分のみに適用し、下半分は全探索をおこなう。
    すると計算量はO(2^9 * L + 2^9 * Q)に落ちて間に合う！！！
    「半分全探索」の一種？
    """

    # 木の高さをnとして求めておく（N <= 2^n - 1）
    n = 0
    while 2 ** n <= N: n += 1
    halfN = 2 ** (n // 2)

    # 木の上半分にいつものナップサックを行い事前計算。
    # dp[v][w] = (頂点1から頂点vまで辿った時、重さがw以下となるようにアイテムを選んだ時の価値の最大値)
    dp = [[0] * (L + 1) for _ in range(halfN)]
    for v in range(1, halfN):
        value, weight = item[v]
        for w in range(L + 1):
            if w >= weight:
                dp[v][w] = max(dp[v // 2][w], dp[v // 2][w - weight] + value)
            else:
                dp[v][w] = dp[v // 2][w]

    # クエリに回答
    for v, l in queri:
        if v < halfN:
            print(dp[v][l])
            continue

        # 木の下半分にいるvの先祖を全列挙。
        # 同時に後々bitDPする都合上itemも先祖列上に取り直す。
        num = 0
        ancestor = []
        item_temp = []
        current = v
        while current >= halfN:
            num += 1
            ancestor.append(current)
            item_temp.append(item[current])
            current //= 2

        # それらの中から選び方を全列挙し、各選びかたに対して最大価値を導出する。
        # ここでビット全探索する中で立っているビットを検索すると計算量が*10倍になるので、
        # 全探索した各結果（価値を重さ）は配列に記録してbitDPを行う。
        ans = dp[current][l]
        value_list = [0] * (1 << num)
        weight_list = [0] * (1 << num)
        for state in range(1, 1 << num):
            lowest_bit = state & (-state) # これで最下位ビットのみ立っている数が得られる
            x = lowest_bit.bit_length() - 1 # lowest_bitのビット位置を0-indexedで求める
            weight_list[state] = weight_list[state - x] + item_temp[x][1]
            if l >= weight_list[state]:
                value_list[state] = value_list[state - x] + item_temp[x][0]
                ans = max(ans, value_list[state] + dp[current][l - weight_list[state]])
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 9, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1].copy()
    for x in range(weight_limit, w - 1, -1):
        dp[x] = max(dp[x], dp[x - w] + v)
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp = {0: 0}
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for cw, cv in list(dp.items()):
            nw = cw + w
            nv = cv + v
            if nw > weight_limit:
                continue
            if nw not in dp or dp[nw] < nv:
                dp[nw] = nv
        u >>= 1
    ans = max(v + precalc[u][l - w] for w, v in dp.items())
    buf.append(ans)

print('\n'.join(map(str, buf)))

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from numba import njit


@njit('i8[:](i8,i8[:],i8[:],i8,i8[:],i8[:])', cache=True)
def solve(n, vvv, www, q, uuu, lll):
    weight_limit = 10 ** 5
    precalc_limit = min(1 << 9, n + 1)
    precalc = np.zeros((precalc_limit, weight_limit + 1), dtype=np.int64)

    for u in range(1, precalc_limit):
        v = vvv[u]
        w = www[u]
        p = u >> 1
        precalc[u, :w] = precalc[p, :w]
        precalc[u, w:] = np.maximum(precalc[p, w:], precalc[p, :-w] + v)

    buf = np.zeros(q, dtype=np.int64)
    for i in range(q):
        u = uuu[i]
        l = lll[i]
        if u < precalc_limit:
            buf[i] = precalc[u, l]
            continue
        dp = {0: 0}
        while u >= precalc_limit:
            v = vvv[u]
            w = www[u]
            for cw, cv in list(dp.items()):
                nw = cw + w
                nv = cv + v
                if nw > weight_limit:
                    continue
                if nw not in dp or dp[nw] < nv:
                    dp[nw] = nv
            u >>= 1
        ans = 0
        for w, v in dp.items():
            ans = max(ans, v + precalc[u, l - w])
        buf[i] = ans

    return buf


n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = np.array([0] + inp[0:n * 2:2], dtype=np.int64)
www = np.array([0] + inp[1:n * 2:2], dtype=np.int64)
q = inp[n * 2]
uuu = np.array(inp[n * 2 + 1::2], dtype=np.int64)
lll = np.array(inp[n * 2 + 2::2], dtype=np.int64)
ans = solve(n, vvv, www, q, uuu, lll)
print('\n'.join(map(str, ans)))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
import sys
input = sys.stdin.buffer.readline
def LI(): return map(int, input().split())
def II(): return int(input())

#solve
def solve():
    n = II()
    v,w = LI()
    nbit = 1 << n.bit_length()
    dp = [[]] * (nbit)
    dp[1] = [(v, w)]
    for i in range(1, nbit >> 1):
        dpi = dp[i]
        if 2 * i + 1 <= n:
            v0, w0 = LI()
            v1, w1 = LI()
            dp21 = dpi[:]
            dp20 = dpi[:]
            dp21.append((v1, w1))
            dp20.append((v0, w0))
            dp[2 * i + 1] = dp21
            dp[2 * i] = dp20
        elif 2 * i <= n:
            v0, w0 = LI()
            dp20 = dpi[:]
            dp20.append((v0, w0))
            dp[2 * i] = dp20
        else:
            break
    return
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    for i in range(1, 1 << n.bit_length() // 2):
        d1 = defaultdict(int)
        d1[0] = 0
        di = M0[:]
        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]
        d.append(di)
    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
        lw = [0] * (1 << n2)
        lv = [0] * (1 << n2)
        dv = d[V]
        ans = dv[L]
        for mask in range(1, 1 << n2):
            a = mask & -mask
            b = a.bit_length() - 1
            v, w = vw2[b]
            ww = lw[mask - a] + w
            lw[mask] = ww
            if ww > L: continue
            vv = lv[mask - a] + v
            lv[mask] = vv
            if dv[L - ww] + vv > ans:
                ans = dv[L - ww] + vv
        print(ans)
    return


solve()

Submission status: Wrong Answer

Solution code:
import math
from collections import deque
import time

def filter(w1,w2,v):
    if w2<=w1:
        return v
    else:
        return 0

def main():
    N=int(input())
    V=[]
    W=[]
    for i in range(N):
        v,w=map(int,input().split())
        V.append(v)
        W.append(w)
    Q=int(input())
    v=[]
    L=[]
    for i in range(Q):
        v_,l=map(int,input().split())
        v.append(v_)
        L.append(l)

    #start=time.time()

    M=pow(10,5)
    D= int(math.log(N+1))#bound of tree
    if D>=2:
        D=D//2

    #knapsack DP
    dp=[[filter(w,W[v],V[v]) for w in range(M+1)] for v in range(N)]
    for i in range(1, pow(2, D) - 1):
        for w in range(1,M+1):
            if (w>=W[i]):
                dp[i][w]=max(dp[(i-1)//2][w-W[i]]+V[i],dp[(i-1)//2][w])
            else:
                dp[i][w]=dp[(i-1)//2][w]
    BoundIndex=pow(2,D)-2

    #start2=time.time()


    for q in range(Q):
        v_q=v[q]
        if v_q-1>BoundIndex:
            d=int(math.log(v_q,2))+1
            k=d-D
            ALL=pow(2,k)
            rest_v=[v_q-1]
            v_=v_q-1
            for _ in range(k-1):
                v_=(v_-1)//2
                rest_v.append(v_)

            parent_node=(v_-1)//2
            res=0
            parent_dp=dp[parent_node]
            for a in range(ALL):
                restW=0
                restV=0
                #bit search
                for flag_index in range(k):
                    if a & 1==1:
                        ind=rest_v[flag_index]
                        restW+=W[ind]
                        restV+=V[ind]
                    a=a>>1
                if L[q]-restW>=0:
                    res=max(res,restV+parent_dp[L[q]-restW])
            print(res)
        else:
            print(dp[v[q]-1][L[q]])

    # exeTime=time.time()-start
    # exeTime2 = time.time() - start2
    #
    # print("time:{}[ms]".format(exeTime*1000))
    # print("bit time:{}[ms]".format(exeTime2*1000))

    # for q in range(Q):
    #     print(dp[v[q]-1][L[q]])





if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
from math import log2
def input(): return sys.stdin.readline().strip()


def main():
    N = int(input())
    item = [(0, 0)]
    for _ in range(N):
        v, w = map(int, input().split())
        item.append((v, w))
    queri = []
    L = 0 # L = max(l_i)
    Q = int(input())
    for _ in range(Q):
        v, l = map(int, input().split())
        queri.append((v, l))
        L = max(L, l)

        """
        各クエリごとにナップサックをやったら間に合わないが、
        本問ではこれを木の上半分のみに適用し、下半分は全探索をおこなう。
        すると計算量はO(2^9 * L + 2^9 * Q)に落ちて間に合う！！！
        「半分全探索」の一種？
        """

        # 木の高さをnとして求めておく（N <= 2^n - 1）
        n = 0
        while 2 ** n <= N: n += 1
        halfN = 2 ** (n // 2)

        # 木の上半分にいつものナップサックを行い事前計算
        # dp[v][w] = (頂点1から頂点vまで辿った時、重さがw以下となるようにアイテムを選んだ時の価値の最大値)
        dp = [[0] * (L + 1) for _ in range(halfN)]
        for v in range(1, halfN):
            value, weight = item[v]
            for w in range(L + 1):
                if w >= weight:
                    dp[v][w] = max(dp[v // 2][w], dp[v // 2][w - weight] + value)
                else:
                    dp[v][w] = dp[v // 2][w]

        # クエリに回答
        for v, l in queri:
            if v < halfN:
                print(dp[v][l])
                continue

            # 木の下半分にいるvの先祖を全列挙
            num = 0
            ancestor = []
            current = v
            while current >= halfN:
                num += 1
                ancestor.append(current)
                current //= 2

            # それらの選び方を全列挙し、各々に対して最大価値を導出
            ans = 0
            for state in range(1 << num):
                tot_val = 0
                tot_wgt = 0
                for i, x in enumerate(ancestor):
                    if state & (1 << i):
                        tot_val += item[x][0]
                        tot_wgt += item[x][1]
                if l >= tot_wgt:
                    ans = max(ans, tot_val + dp[current][l - tot_wgt])
            print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import math
from collections import deque
import time

def filter(w1,w2,v):
    if w2<=w1:
        return v
    else:
        return 0

def main():
    N=int(input())
    V=[]
    W=[]
    for i in range(N):
        v,w=map(int,input().split())
        V.append(v)
        W.append(w)
    Q=int(input())
    v=[]
    L=[]
    for i in range(Q):
        v_,l=map(int,input().split())
        v.append(v_)
        L.append(l)

    #start=time.time()

    M=pow(10,5)
    D= int(math.sqrt(N+1))#bound of tree
    
    #knapsack DP
    dp=[[filter(w,W[v],V[v]) for w in range(M+1)] for v in range(N)]
    for i in range(1, pow(2, D) - 1):
        for w in range(1,M+1):
            if (w>=W[i]):
                dp[i][w]=max(dp[(i-1)//2][w-W[i]]+V[i],dp[(i-1)//2][w])
            else:
                dp[i][w]=dp[(i-1)//2][w]
    BoundIndex=pow(2,D)-2

    #start2=time.time()


    for q in range(Q):
        v_q=v[q]
        if v_q-1>BoundIndex:
            d=int(math.sqrt(v_q))+1
            k=d-D
            ALL=pow(2,k)
            rest_v=[v_q-1]
            v_=v_q-1
            for _ in range(k-1):
                v_=(v_-1)//2
                rest_v.append(v_)

            parent_node=(v_-1)//2
            res=0
            parent_dp=dp[parent_node]
            for a in range(ALL):
                restW=0
                restV=0
                #bit search
                for flag_index in range(k):
                    if a & 1==1:
                        ind=rest_v[flag_index]
                        restW+=W[ind]
                        restV+=V[ind]
                    a=a>>1
                if L[q]-restW>=0:
                    res=max(res,restV+parent_dp[L[q]-restW])
            print(res)
        else:
            print(dp[v[q]-1][L[q]])

    # exeTime=time.time()-start
    # exeTime2 = time.time() - start2
    #
    # print("time:{}[ms]".format(exeTime*1000))
    # print("bit time:{}[ms]".format(exeTime2*1000))

    # for q in range(Q):
    #     print(dp[v[q]-1][L[q]])





if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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


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


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

dp = [[0] * (10 ** 5 + 1) for i in range(half_n + 1)]
for i in range(half_n):
    val, wei = info[i]
    par_i = (i + 1) // 2
    for w in range(10 ** 5 + 1):
        if w - wei >= 0:
            dp[i + 1][w] = max(dp[par_i][w - wei] + val, dp[par_i][w])
        else:
            dp[i + 1][w] = dp[par_i][w]

items = [[] for i in range(n)]
for i in range(half_n, n):
    if (i + 1) // 2 - 1 < half_n:
        items[i].append(info[i])
        items[i].append((0, 0))
    else:
        val, wei = info[i]
        for v, w in items[(i + 1) // 2 - 1]:
            items[i].append((v, w))
            items[i].append((v + val, w + wei))
"""
for i, l in query:
    ans = 0
    if i <= half_n:
        print(dp[i][l])
    else:
        ans = 0
        ind = i
        while ind > half_n:
            ind = ind // 2
            
        for v, w in items[i - 1]:
            if l - w >= 0:
                ans = max(ans, dp[ind][l - w] + v)
        print(ans)"""

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
from collections import defaultdict
import sys, itertools
input = sys.stdin.buffer.readline
def LI(): return list(map(int, input().split()))
def II(): return int(input())
def LIR(n): return [LI() for _ in range(n)]

#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)
        else:
            break
    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]:
            d2 = defaultdict(int)
            for key, value in d1.items():
                if d2[key] < value:
                    d2[key] = value
                keyw = key + w
                valuev = value + v
                if keyw >= M: continue
                if d2[keyw] < valuev:
                    d2[keyw] = valuev
                    d2[keyw] = valuev
            d1 = d2
        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
        dv = d[V]
        ans = dv[L]
        for v, w in vw2:
            d2 = defaultdict(int)
            for key, value in d1.items():
                if d2[key] < value:
                    d2[key] = value
                keyw = key + w
                if keyw > L: continue
                valuev = value + v
                if d2[keyw] < valuev:
                    d2[keyw] = valuev
                    if dv[L - keyw] + valuev > ans:
                        ans = dv[L - keyw] + valuev
            d1 = d2
        print(ans)
    return


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