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 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,2))+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]

    dp = [[filter(w, W[0], V[0]) for w in range(M+1)]]
    for i in range(1, pow(2, D)-1):
        dp.append([])
        for w in range(0, M + 1):
            if (w >= W[i]):
                dp[i].append(max(dp[(i - 1) // 2][w - W[i]] + V[i], dp[(i - 1) // 2][w]))
            else:
                dp[i].append(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: 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 = []
    for i in range(n):
        v, w = LI()
        vw.append((v, w))
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    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 = []
        while i:
            dpi.append((vw[i - 1][0], vw[i - 1][1]))
            i //= 2
        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)
    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 // 2)
dp = [[0] * MAX for _ in range(n)]


def all_search(vw, p, l, m, v, w):
    if w > l:
        return 0
    if m == len(vw):
        return dp[p][l - w] + v
    x = all_search(vw, p, l, m + 1, v + vw[m][0], w + vw[m][1])
    y = all_search(vw, p, l, m + 1, v, w)
    return max(x, y)


def solve(v, l):
    if v < n:
        return dp[v][l]
    vw = []
    while v >= n:
        vw.append(VW[v - 1])
        v = v // 2
    ans = all_search(vw, v, l, 0, 0, 0)
    return ans


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, l)
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
import numpy as np
from numba import njit

@njit()
def solve_dp(l_max, k):
    dp = [[0] * (l_max + 1) for _ in  range(2 ** k)]
    for i in range(1, 2 ** k):
        for j in range(l_max + 1):
            if j >= weight[i]:
                dp[i][j] = max(dp[i//2][j], 
                               dp[i//2][j-weight[i]] + value[i])
            else:
                dp[i][j] = dp[i//2][j]
    return dp

@njit()
def main(n, k, value, weight, query_v, query_l):
    # 木全体の半分の深さまでdpテーブルを作っておく
    l_max = max(query_l)
    dp = solve_dp(l_max, k)

    # 残りの半分についてはクエリ毎に処理
    for v, l in zip(query_v, query_l):
        if v < 2 ** k:
            print(dp[v][l])
            continue

        indices = []
        tmp = v
        while tmp >= 2 ** k:
            indices.append(tmp)
            tmp //= 2
        li = len(indices)
        
        ans = 0
        for num in range(1<<li):
            item = [(num >> i) & 1 for i in range(li)]
            v_sum, w_sum = 0, 0
            for i in range(li):
                if item[i]:
                    idx = indices[i]
                    v_sum += value[idx]
                    w_sum += weight[idx]
            if w_sum > l:
                continue
            ans = max(ans, v_sum + dp[tmp][l-w_sum])
        print(ans)


n = int(input())
k = (n-1).bit_length() // 2
value = [-1]
weight = [-1]
for _ in range(n):
    v, w = map(int, input().split())
    value.append(v)
    weight.append(w)

q = int(input())
query_v, query_l = [], []
for _ in range(q):
    v, l = map(int, input().split())
    query_v.append(v)
    query_l.append(l)

value, weight = np.array(value), np.array(weight)
query_v, query_l = np.array(query_v), np.array(query_l)

main(n, k, value, weight, query_v, query_l)

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()
    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
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    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]
        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)
    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: Time Limit Exceeded

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
    M = 10 ** 5 + 1
    M0 = [0] * M
    d = [M0]
    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]
        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)
    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: Time Limit Exceeded

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
    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[:]
        n2 = i.bit_length()
        lw = [0] * (1 << n2)
        lv = [0] * (1 << n2)
        for mask in range(1, 1 << n2):
            a = mask & -mask
            b = a.bit_length() - 1
            v, w = dp[i][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)
    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: Time Limit Exceeded

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
    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: 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=[]
    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,2))+1#bound of tree
    if D>=2:
        D=D*2//3

    #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: 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=[]
    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,2))+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: Time Limit Exceeded

Solution code:
import sys
import numpy as np

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 = [np.zeros(weight_limit + 1, dtype=np.int64)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    parent_dp = precalc[u >> 1]
    dp = parent_dp.copy()
    dp[w:] = np.maximum(parent_dp[w:], parent_dp[:-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: 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=[]
    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
    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: 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の先祖を全列挙
        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: 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=[]
    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
    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.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: 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=[]
    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
    if D>=3:
        D=D//3

    #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()