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: Time Limit Exceeded

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


# 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: Time Limit Exceeded

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

items=10**5
def calc():
  n=int(input())
  arr=[list(map(int,input().split())) for _ in range(n)]
  dp=[[0]*(items+1) for _ in range(1<<10+1)]
  for i in range(1,min(n,1<<10)+1):
    v,w=arr[i-1]
    dp[i]=dp[i>>1][:]
    for j in range(items,w-1,-1):
      dp[i][j]=max(dp[i][j],dp[i>>1][j-w]+v)
  q=int(input())
  for _ in range(q):
    v,l=map(int,input().split())
    if v<=1<<10:
      print(dp[v][l])
    else:
      vs=[]
      cnt=0
      while v>1<<10:
        vs.append(v)
        v>>=1
        cnt+=1
      ans=0
      for i in range(1<<cnt):
        weight=0
        value=0
        for j in range(cnt):
          if i&(1<<j):
            weight+=arr[vs[j]][1]
            value+=arr[vs[j]][0]
        if weight>l:
          continue
        ans=max(ans,dp[v][l-weight]+value)
      print(ans)
calc()

Submission status: Time Limit Exceeded

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

#solve
def solve():
    n = II()
    vw = []
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    dp = [[]]
    XX = 1 << n.bit_length() // 2
    for i in range(1, n + 1):
        v, w = LI()
        vw.append((v, w))
        if i < XX:
            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.append(di)
    n = [1 << i for i in range(18)]
    for _ in range(II()):
        V, L = LI()
        lent = V.bit_length()
        if V < XX:
            print(d[V][L])
            continue
        n1 = lent // 2
        n2 = lent - n1
        vw2 = []
        for _ in range(n2):
            vw2.append((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
            if dv[Lww] + vv > ans:
                ans = dv[Lww] + vv
        print(ans)
    return


solve()

Submission status: Time Limit Exceeded

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=[]

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

    dp=[]

    BoundIndex = pow(2, D) - 2

    for i in range(N):
        v,w=map(int,input().split())
        if i==0:
            dp.append([filter(w_, w, v) for w_ in range(M + 1)])
        elif i<pow(2,D)-1:
            dp.append([])
            for w_ in range(M+1):
                if (w_>=w):
                    dp[i].append(max(dp[(i - 1) // 2][w_ - w] + v, dp[(i - 1) // 2][w_]))
                else:
                    dp[i].append(dp[(i-1)//2][w_])

        V.append(v)
        W.append(w)
    Q=int(input())
    v=[]
    L=[]
    R=[]
    for i in range(Q):
        v_q,l = map(int,input().split())
        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 - restW >= 0:
                    res = max(res, restV + parent_dp[l - restW])
            R.append(res)
        else:
            res=dp[v_q - 1][l]
            R.append(res)

    for i in range(Q):
        print(R[i])



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

#solve
def solve():
    n = II()
    vw = []
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    dp = [[]]
    XX = 1 << n.bit_length() // 2
    for i in range(1, n + 1):
        v, w = LI()
        vw.append((v, w))
        if i < XX:
            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.append(di)

    for _ in range(II()):
        V, L = LI()
        lent = V.bit_length()
        if V < XX:
            print(d[V][L])
            continue
        n1 = lent // 2
        n2 = lent - n1
        vw2 = []
        for _ in range(n2):
            vw2.append((vw[V - 1][0], vw[V - 1][1]))
            V //= 2
        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: Time Limit Exceeded

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 0 != N:
        n += 1
        N //= 2
    halfN = 1 << (n // 2) # *2, //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 >>= 1

        # それらの中から選び方を全列挙し、各選びかたに対して最大価値を導出する。
        # ここでビット全探索する中で立っているビットを検索すると計算量が*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で求める
            w_temp = weight_list[state - lowest_bit] + item_temp[x][1]
            weight_list[state] = w_temp # 変数を分離させた。キャッシュに乗りやすくなって高速化なるか！？
            if l >= w_temp:
                v_temp = value_list[state - lowest_bit] + item_temp[x][0]
                value_list[state] = v_temp
                ans = max(ans, v_temp + dp[current][l - w_temp])
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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**9-1)

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)

def merge(l1, l2, L):
    right = len(l2)-1
    ans = -1
    for left in range(len(l1)):
        w1, v1 = l1[left]
        while right>0 and w1+l2[right][0]>L:
            right -= 1
        if w1+l2[right][0]<=L:
            ans = max(ans, v1+l2[right][1])
        else:
            break
    return ans
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 = merge(l, tmp, L)
    
    
#     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: Time Limit Exceeded

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

#solve
def solve():
    n = II()
    vw = []
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    dp = [[]]
    XX = 1 << n.bit_length() // 2
    for i in range(1, n + 1):
        v, w = LI()
        vw.append((v, w))
        if i < XX:
            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.append(di)

    for _ in range(II()):
        V, L = LI()
        lent = V.bit_length()
        n1 = lent // 2
        n2 = lent - n1
        vw2 = []
        for _ in range(n2):
            vw2.append((vw[V - 1][0], vw[V - 1][1]))
            V //= 2
        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: Time Limit Exceeded

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で求める
            w_temp = weight_list[state - lowest_bit] + item_temp[x][1]
            weight_list[state] = w_temp # 変数を分離させた。キャッシュに乗りやすくなって高速化なるか！？
            if l >= w_temp:
                v_temp = value_list[state - lowest_bit] + item_temp[x][0]
                value_list[state] = v_temp
                ans = max(ans, v_temp + dp[current][l - w_temp])
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
arr=[list(map(int,input().split())) for _ in range(n)]
dp=[[0]*(10**5+1) for _ in range(2**9+1)]
for i in range(1,min(n,2**9)+1):
  v,w=arr[i-1]
  for j in range(10**5,w-1,-1):
    dp[i][j]=max(dp[i//2][j],dp[i//2][j-w]+v)
  for j in range(w-1,-1,-1):
    dp[i][j]=dp[i//2][j]
q=int(input())
for _ in range(q):
  v,l=map(int,input().split())
  if v<=2**9:
    print(dp[v][l])
  else:
    vs=[]
    cnt=0
    while v>2**9:
      vs.append(v)
      v//=2
      cnt+=1
    ans=0
    for i in range(2**cnt):
      weight=0
      value=0
      for j in range(cnt):
        if i&(1<<j):
          weight+=arr[vs[j]][1]
          value+=arr[vs[j]][0]
      if weight>l:
        continue
      ans=max(ans,dp[v][l-weight]+value)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

def solve(N, W, item):
    item.sort(key = lambda vw: vw[0]/ vw[1], reverse = True)
    v_max = 0

    def solve_relax(i, cap):
        ans = 0
        for v, w in item[i:]:
            if not cap: 
                break
            if w <= cap:
                cap -= w
                ans += v
            else:
                ans += v * (cap / w)
                return ans, False
        return ans, True
 
    def dfs(i, v_now, w_now):
        nonlocal v_max
        if i == N:
            v_max = max(v_max, v_now)
            return v_max
        relax, relax_ok = solve_relax(i, W - w_now)
        relax += v_now
        if relax_ok:
            v_max = max(v_max, relax)
            return v_max
        if relax < v_max:
            return v_max
        ans = 0
        v, w = item[i]
        if w_now + w <= W:
            ans = max(ans, dfs(i + 1, v_now + v, w_now + w))
        ans = max(ans, dfs(i + 1, v_now, w_now))
        return ans
 
    print(dfs(0, 0, 0))

def main():
    N = int(input())
    item = [tuple(map(int,input().split())) for _ in range(N)]
    Q = int(input())
    for _ in range(Q):
        V,L = map(int,input().split())
        items = []
        while V > 0:
            items.append(item[V - 1])
            V >>= 1
        M = len(items)
        solve(M,L,items)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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 - lowest_bit] + item_temp[x][1]
            if l >= weight_list[state]:
                value_list[state] = value_list[state - lowest_bit] + item_temp[x][0]
                ans = max(ans, value_list[state] + dp[current][l - weight_list[state]])
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

#solve
def solve():
    n = II()
    vw = []
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    dp = [[]]
    XX = 1 << n.bit_length() // 2
    for i in range(n):
        v, w = LI()
        vw.append((v, w))
        i += 1
        if i < XX:
            di = M0[:]
            n2 = i.bit_length()
            lw = [0] * (1 << n2)
            lv = [0] * (1 << n2)
            if i & 1:
                dpi = dp[i // 2]
            else:
                dpi = dp[i // 2][:]
            dpi.append((vw[i - 1][0], vw[i - 1][1]))
            for mask in range(1, 1 << n2):
                a = mask & -mask
                b = a.bit_length() - 1
                v, w = dpi[b]
                ww = lw[mask - a] + w
                lw[mask] = ww
                if ww >= M: continue
                vv = lv[mask - a] + v
                lv[mask] = vv
                if di[ww] < vv:
                    di[ww] = vv
            for j in range(M - 1):
                if di[j + 1] < di[j]:
                    di[j + 1] = di[j]
            d.append(di)
            dp.append(dpi)
    for _ in range(II()):
        V, L = LI()
        lent = V.bit_length()
        n1 = lent // 2
        n2 = lent - n1
        vw2 = []
        for _ in range(n2):
            vw2.append((vw[V - 1][0], vw[V - 1][1]))
            V //= 2
        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: Time Limit Exceeded

Solution code:
#!python3

LI = lambda: list(map(int, input().split()))

# input
N = int(input())
VW = [LI() for _ in range(N)]
Q = int(input())
VL = [LI() for _ in range(Q)]

MAX = 10 ** 5 + 1
k = N.bit_length()
n = 1 << (k >> 1)
dp = [[0] * MAX for _ in range(n)]


def solve(i, v, l):
    if l < 0:
        return 0
    if i < n:
        return dp[i][l] + v
    x = solve(i >> 1, v + VW[i - 1][0], l - VW[i - 1][1])
    y = solve(i >> 1, v, l)
    return max(x, y)


def main():
    dp[0][0] = 0
    for i in range(1, n):
        p = i // 2
        v, w = VW[i - 1]
        dp[i][0] = 0
        for j in range(MAX):
            dp[i][j] = max(dp[p][j], dp[i][j - 1])
            if j >= w:
                dp[i][j] = max(dp[i][j], dp[p][j - w] + v)
    
    for v, l in VL:
        ans = solve(v, 0, l)
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

#solve
def solve():
    n = II()
    vw = []
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    for i in range(n):
        v, w = LI()
        vw.append((v, w))
    dp = [[]]
    for i in range(1, 1 << n.bit_length() // 2):
        di = M0[:]
        n2 = i.bit_length()
        lw = [0] * (1 << n2)
        lv = [0] * (1 << n2)
        if i & 1:
            dpi = dp[i // 2]
        else:
            dpi = dp[i // 2][:]
        dpi.append((vw[i - 1][0], vw[i - 1][1]))
        for mask in range(1, 1 << n2):
            a = mask & -mask
            b = a.bit_length() - 1
            v, w = dpi[b]
            ww = lw[mask - a] + w
            lw[mask] = ww
            if ww >= M: continue
            vv = lv[mask - a] + v
            lv[mask] = vv
            if di[ww] < vv:
                di[ww] = vv
        for j in range(M - 1):
            if di[j + 1] < di[j]:
                di[j + 1] = di[j]
        d.append(di)
        dp.append(dpi)
    for _ in range(II()):
        V, L = LI()
        lent = V.bit_length()
        n1 = lent // 2
        n2 = lent - n1
        vw2 = []
        for _ in range(n2):
            vw2.append((vw[V - 1][0], vw[V - 1][1]))
            V //= 2
        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: Time Limit Exceeded

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

#solve
def solve():
    n = II()
    vw = []
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    for i in range(n):
        v, w = LI()
        vw.append((v, w))
    dp = [[]]
    for i in range(1, 1 << n.bit_length() // 2):
        di = M0[:]
        n2 = i.bit_length()
        lw = [0] * (1 << n2)
        lv = [0] * (1 << n2)
        dpi = dp[i // 2][:]
        dpi.append((vw[i - 1][0], vw[i - 1][1]))
        for mask in range(1, 1 << n2):
            a = mask & -mask
            b = a.bit_length() - 1
            v, w = dpi[b]
            ww = lw[mask - a] + w
            lw[mask] = ww
            if ww >= M: continue
            vv = lv[mask - a] + v
            lv[mask] = vv
            if di[ww] < vv:
                di[ww] = vv
        for j in range(M - 1):
            if di[j + 1] < di[j]:
                di[j + 1] = di[j]
        d.append(di)
        dp.append(dpi)
    for _ in range(II()):
        V, L = LI()
        lent = V.bit_length()
        n1 = lent // 2
        n2 = lent - n1
        vw2 = []
        for _ in range(n2):
            vw2.append((vw[V - 1][0], vw[V - 1][1]))
            V //= 2
        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()