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:
N = int(input())
V = []
W = []
p = 10 ** 5
q = 2 ** 9

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

L = [[-1 for j in range(p + 1)] for j in range(q)]
L[0][0] = 0

for i in range(min(N, q - 1)):
    for j in range(p + 1):
        L[i+1][j] = max(L[i+1][j], L[(i+1)//2][j])
        if j + W[i] <= p:
            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 < q:
        print(L[v][l])
    else:
        ans = 0
        K = []
        while v >= q:
            K.append(v-1)
            v //= 2
        for i in range(len(K) ** 2):
            tmp_v = 0
            tmp_w = 0
            for j in range(len(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: Time Limit Exceeded

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

Solution code:
import math

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)
    M=max(L)
    D= int(math.sqrt(N+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

    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]])



    # 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,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 << 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]
    for _ in range(II()):
        V, L = LI()
        t = dp[V]
        lent = len(t)
        n1 = lent // 2
        n2 = lent - 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 key + w > L: continue
                if d1[key + w] < value + v:
                    d1[key + w] = value + v
        ans = 0
        dv = d[V]
        for w, v in d1.items():
            if dv[L - w] + v > ans:
                ans = dv[L - w] + v
        print(ans)
    return


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

Submission status: Time Limit Exceeded

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
    cnt = 0
    tmp = v
    while tmp > m:
        tmp >>= 1
        cnt += 1
    ret = 0
    for j in range(1 << cnt):
        weight_sum = 0
        value_sum = 0
        tmp = v
        idx = j
        while tmp > m:
            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][L - weight_sum]
            ret = max(ret, value_sum)
    print(ret)

Submission status: Time Limit Exceeded

Solution code:
import math

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)
    M=max(L)
    D= int(math.sqrt(N+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

    for q in range(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
            for a in range(ALL):
                restW=0
                restV=0
                for flag_index in range(k):
                    if (a>>flag_index) & 1==1:
                        ind=rest_v[flag_index]
                        restW+=W[ind]
                        restV+=V[ind]
                if L[q]-restW>=0:
                    res=max(res,restV+dp[parent_node][L[q]-restW])

            print(res)
        else:
            print(dp[v[q]-1][L[q]])



    # 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,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]
    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 key + w > L: continue
                if d1[key + w] < value + v:
                    d1[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: Time Limit Exceeded

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

Solution code:
import sys
MX = 10**5
def main():
    data = map(int, sys.stdin.buffer.read().split())
    N = next(data)
    IV, IW = [], []

    H = min(N + 1, 1 << 10)
    Hb = (H - 1).bit_length()
    dp = [None for _ in range(H)]
    dp[0] = [0] * (MX + 1)
    for i in range(1, min(N + 1, H)):
        v, w = next(data), next(data)
        dpi = dp[i >> 1][:]
        dp[i] = dpi
        for j in range(MX, w - 1, -1):
            dpi[j] = max(dpi[j], dpi[j - w] + v)
    for i in range(min(N + 1, H), N + 1):
        v, w = next(data), next(data)
        IV.append(v)
        IW.append(w)

    Q = next(data)
    for v, L in zip(data, data):
        if v < H:
            print(dp[v][L])
            continue

        item_values = []
        item_weights = []
        while v >= H:
            item_values.append(IV[v - H])
            item_weights.append(IW[v - H])
            v >>= 1

        l = len(item_values)
        V = [0] * (1 << l)
        W = [0] * (1 << l)
        ans = [dp[v][L]]
        for i in range(1, 1 << l):
            msb = i & (-i)
            msbb = msb.bit_length() - 1
            wi = W[i - msb] + item_weights[msbb]
            W[i] = wi
            if wi <= L:
                vi = V[i - msb] + item_values[msbb]
                ans.append(vi + dp[v][L - wi])
                V[i] = vi
        print(max(ans))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
MX = 10**5
def main():
    data = map(int, sys.stdin.buffer.read().split())
    N = next(data)
    IV, IW = [], []

    H = min(N + 1, 1 << 10)
    Hb = (H - 1).bit_length()
    dp = [None for _ in range(H)]
    dp[0] = [0] * (MX + 1)
    i = 1
    for v, w in zip(data, data):
        if i < H:
            dpi = dp[i >> 1][:]
            dp[i] = dpi
            for j in range(MX, w - 1, -1):
                dpi[j] = max(dpi[j], dpi[j - w] + v)
        else:
            IV.append(v)
            IW.append(w)
        i += 1
        if i > N:
            break

    Q = next(data)
    for v, L in zip(data, data):
        if v < H:
            print(dp[v][L])
            continue

        item_values = []
        item_weights = []
        while v >= H:
            item_values.append(IV[v - H])
            item_weights.append(IW[v - H])
            v >>= 1

        l = len(item_values)
        V = [0] * (1 << l)
        W = [0] * (1 << l)
        ans = [dp[v][L]]
        for i in range(1, 1 << l):
            msb = i & (-i)
            msbb = msb.bit_length() - 1
            wi = W[i - msb] + item_weights[msbb]
            W[i] = wi
            if wi <= L:
                vi = V[i - msb] + item_values[msbb]
                ans.append(vi + dp[v][L - wi])
                V[i] = vi
        print(max(ans))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

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

Solution code:
import sys
MX = 10**5
def main():
    data = map(int, sys.stdin.buffer.read().split())
    N = next(data)
    IV, IW = [], []

    H = min(N + 1, 1 << 10)
    Hb = (H - 1).bit_length()
    dp = [[0] * (MX + 1) for _ in range(H)]
    i = 1
    for v, w in zip(data, data):
        if i < H:
            dpi = dp[i]
            dpip = dp[i >> 1]
            for j in range(w):
                dpi[j] = dpip[j]
            for j in range(w, MX + 1):
                dpi[j] = max(dpip[j], dpip[j - w] + v)
        else:
            IV.append(v)
            IW.append(w)
        i += 1
        if i > N:
            break

    Q = next(data)
    for v, L in zip(data, data):
        if v < H:
            print(dp[v][L])
            continue

        item_values = []
        item_weights = []
        while v >= H:
            item_values.append(IV[v - H])
            item_weights.append(IW[v - H])
            v >>= 1

        l = len(item_values)
        V = [0] * (1 << l)
        W = [0] * (1 << l)
        ans = [dp[v][L]]
        for i in range(1, 1 << l):
            msb = i & (-i)
            msbb = msb.bit_length() - 1
            wi = W[i - msb] + item_weights[msbb]
            W[i] = wi
            if wi <= L:
                vi = V[i - msb] + item_values[msbb]
                ans.append(vi + dp[v][L - wi])
                V[i] = vi
        print(max(ans))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:

L = 10 ** 5 + 1

N = int(input())
items = []
for _ in range(N):
	v, w = map(int, input().split())
	items.append((v, w))

#K = 0
#n = 1
#while (n * n) * 2 * 2 < N:
#	K += 1
#	n *= 2

n = min(N, 512)

#print(n, K)

cache = [None] * n
def calc(x, table):
	if x <= n:
		v, w = items[x - 1]
		table = list(table)
		for w0 in range(L - 1, -1, -1):
			v0 = table[w0]
			w1 = w0 + w
			v1 = v0 + v
			if w1 <= L and table[w1] < v1:
				table[w1] = v1
		cache[x - 1] = table
		calc(x * 2, table)
		calc(x * 2 + 1, table)

calc(1, [0] * (L + 1))

#print(cache)

Q = int(input())
for _ in range(Q):
	i, l = map(int, input().split())
	if i <= n:
		print(cache[i - 1][l])
	else:
		j = i
		targets = []
		while j > n:
			targets.append(items[j - 1])
			j //= 2
		table = cache[j - 1]
		topvalue = 0
		for b in range(2 ** len(targets)):
			v0 = 0
			w0 = 0
			x = 0
			while b > 0:
				if b % 2 == 1:
					v0 += targets[x][0]
					w0 += targets[x][1]
				x += 1
				b //= 2
			if w0 <= l:
				v1 = v0 + table[l - w0]
				if v1 > topvalue:
					topvalue = v1
		print(topvalue)

Submission status: Time Limit Exceeded

Solution code:
import sys
MX = 10**5
def main():
    data = map(int, sys.stdin.buffer.read().split())
    N = next(data)
    IV, IW = [], []

    H = min(N + 1, 1 << 10)
    Hb = (H - 1).bit_length()
    dp = [[0] * (MX + 1) for _ in range(H)]
    i = 1
    for v, w in zip(data, data):
        if i < H:
            dpi = dp[i]
            dpip = dp[i >> 1]
            for j in range(w):
                dpi[j] = dpip[j]
            for j in range(w, MX + 1):
                dpi[j] = max(dpip[j], dpip[j - w] + v)
        else:
            IV.append(v)
            IW.append(w)
        i += 1
        if i > N:
            break

    Q = next(data)
    for v, L in zip(data, data):
        if v < H:
            print(dp[v][L])
            continue

        item_values = []
        item_weights = []
        while v >= H:
            item_values.append(IV[v - H])
            item_weights.append(IW[v - H])
            v >>= 1

        l = len(item_values)
        V = [0] * (1 << l)
        W = [0] * (1 << l)
        ans = [dp[v][L]]
        for i in range(1, 1 << l):
            msb = i & (-i)
            msbb = msb.bit_length() - 1
            V[i] = V[i - msb] + item_values[msbb]
            W[i] = W[i - msb] + item_weights[msbb]
            if W[i] <= L:
                ans.append(V[i] + dp[v][L - W[i]])
        print(max(ans))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def main(N, V, W, v, L):
    def solve(values, weights, lim):
        N = len(values)
        if N == 1:
            if weights[0] <= lim:
                return values[0]
            else:
                return 0

        def compute_half(values, weights, lim):
            N = len(values)
            V = np.empty(1 << N, np.int32)
            W = np.empty(1 << N, np.int32)
            V[0], W[0] = 0, 0
            for i in range(N):
                V[1 << i:1 << (i + 1)] = V[:1 << i] + values[i]
                W[1 << i:1 << (i + 1)] = W[:1 << i] + weights[i]
            ind = W.argsort()
            V = V[ind]
            W = W[ind]
            for i in range(1, 1 << N):
                V[i] = max(V[i - 1], V[i])
            ind1 = W <= lim
            V = V[ind1]
            W = W[ind1]
            return V, W

        n = N // 2
        VL, WL = compute_half(values[:n], weights[:n], lim)
        VR, WR = compute_half(values[n:], weights[n:], lim)
        best = 0
        j = len(WR) - 1
        for i in range(len(WL)):
            while WL[i] + WR[j] > lim:
                j -= 1
            x = VL[i] + VR[j]
            best = max(best, x)
        return best
    Q = len(v)
    for i in range(Q):
        n = v[i]
        values = np.empty(18, np.int32)
        weights = np.empty(18, np.int32)
        p = 0
        while n:
            values[p] = V[n]
            weights[p] = W[n]
            p += 1
            n >>= 1
        x = solve(values[:p], weights[:p], L[i])
        print(x)

if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i4,i4[:],i4[:],i4[:],i4[:])')(main)
    cc.compile()
    exit()
from my_module import main

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[:N + N:2]
W[1:] = stdin[1:N + N:2]
query = stdin[N + N + 1:]
v, L = query[::2], query[1::2]

main(N, V, W, v, L)