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


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


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

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

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

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

Submission status: Time Limit Exceeded

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

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


solve()

Submission status: Time Limit Exceeded

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

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


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

Submission status: Time Limit Exceeded

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


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


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

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

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

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

Submission status: Time Limit Exceeded

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

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


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

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

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 ** 10)]
L[0][0] = 0

for i in range(min(N, 2 ** 10 - 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 ** 10:
        print(L[v][l])
    else:
        ans = 0
        K = []
        while v >= 2 ** 10:
            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:
                    break
            if l - tmp_w < 0:
                continue
            ans = max(ans, L[v][l-tmp_w] + tmp_v)
        print(ans)

Submission status: Time Limit Exceeded

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

import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def main():
    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 << 11)
    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)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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


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

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]

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 ** 10)]
L[0][0] = 0

for i in range(min(N, 2 ** 10 - 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 ** 10:
        print(L[v][l])
    else:
        ans = 0
        K = []
        while v >= 2 ** 10:
            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:
#!/usr/bin/env python3

import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

def main():
    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)
    return

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 << n.bit_length() // 2)]
    for i in range(1, 1 << n.bit_length() // 2):
        d1 = defaultdict(int)
        d1[0] = 0
        di = d[i]
        for v, w in dp[i]:
            for key, value in list(d1.items()):
                keyw = key + w
                valuev = value + v
                if keyw >= M: continue
                if d1[keyw] < valuev:
                    d1[keyw] = valuev
                    di[keyw] = valuev
        for j in range(M - 1):
            if di[j + 1] < di[j]:
                di[j + 1] = di[j]
    for _ in range(II()):
        V, L = LI()
        t = dp[V]
        lent = V.bit_length()
        n1 = lent // 2
        n2 = lent - n1
        vw2 = t[n1:]
        V = V >> n2
        d1 = defaultdict(int)
        d1[0] = 0
        dv = d[V]
        ans = dv[L]
        for v, w in vw2:
            for key, value in list(d1.items()):
                keyw = key + w
                if keyw > L: continue
                valuev = value + v
                if d1[keyw] < valuev:
                    d1[keyw] = valuev
                    if dv[L - keyw] + valuev > ans:
                        ans = dv[L - keyw] + valuev
        print(ans)
    return


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

Submission status: Time Limit Exceeded

Solution code:
import math
#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//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()

    R=[]

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

            R.append(res)
        else:
            R.append(dp[v[q]-1][L[q]])

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

    # 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

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
    v_ = []
    w_ = []
    while tmp > m:
        v_.append(V[tmp-1])
        w_.append(W[tmp-1])
        tmp >>= 1
        cnt += 1
    ret = dp[tmp][L]
    for j in range(1, 1 << cnt):
        weight_sum = 0
        value_sum = 0
        for v, w in zip(v_, w_):
            if j & 1:
                weight_sum += w
                value_sum += v
                if weight_sum > L:
                    break
            j >>= 1
        else:
            value_sum += dp[tmp][L - weight_sum]
            ret = max(ret, value_sum)
    print(ret)

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 ** 10)]
L[0][0] = 0

for i in range(min(N, 2 ** 10 - 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 ** 10:
        print(L[v][l])
    else:
        ans = 0
        K = []
        while v >= 2 ** 10:
            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 ** 11)]
L[0][0] = 0

for i in range(min(N, 2 ** 11 - 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 ** 11:
        print(L[v][l])
    else:
        ans = 0
        K = []
        while v >= 2 ** 11:
            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:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

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