Problem:


Score : 700 points

Problem Statement

We have a rooted binary tree with N vertices, where the vertices are numbered 1 to N.
Vertex 1 is the root, and the parent of Vertex i (i \geq 2) is Vertex \left[ \frac{i}{2} \right].

Each vertex has one item in it. The item in Vertex i has a value of V_i and a weight of W_i.
Now, process the following query Q times:

Given are a vertex v of the tree and a positive integer L.
  Let us choose some (possibly none) of the items in v and the ancestors of v so that their total weight is at most L.
  Find the maximum possible total value of the chosen items.

Here, Vertex u is said to be an ancestor of Vertex v when u is an indirect parent of v, that is, there exists a sequence of vertices w_1,w_2,\ldots,w_k (k\geq 2) where w_1=v, w_k=u, and w_{i+1} is the parent of w_i for each i.

Constraints

All values in input are integers.

1 \leq N < 2^{18}

1 \leq Q \leq 10^5

1 \leq V_i \leq 10^5

1 \leq W_i \leq 10^5

For the values v and L given in each query, 1 \leq v \leq N and 1 \leq L \leq 10^5.

Input

Let v_i and L_i be the values v and L given in the i-th query.
Then, Input is given from Standard Input in the following format:

N
V_1 W_1
:
V_N W_N
Q
v_1 L_1
:
v_Q L_Q

Output

For each integer i from 1 through Q,
the i-th line should contain the response to the i-th query.

Sample Input 1

3
1 2
2 3
3 4
3
1 1
2 5
3 5

Sample Output 1

0
3
3

In the first query, we are given only one choice: the item with (V, W)=(1,2). Since L = 1, we cannot actually choose it, so our response should be 0.

In the second query, we are given two choices: the items with (V, W)=(1,2) and (V, W)=(2,3). Since L = 5, we can choose both of them, so our response should be 3.

Sample Input 2

15
123 119
129 120
132 112
126 109
118 103
115 109
102 100
130 120
105 105
132 115
104 102
107 107
127 116
121 104
121 115
8
8 234
9 244
10 226
11 227
12 240
13 237
14 206
15 227

Sample Output 2

256
255
250
247
255
259
223
253



Sample input:
3
1 2
2 3
3 4
3
1 1
2 5
3 5


Sample output:
0
3
3

Submission status: Time Limit Exceeded

Solution code:
import sys
from operator import itemgetter
readline = sys.stdin.readline

def mergeup(Av, Aw, vw):
    v, w = vw
    rv, rw = [], []
    N = len(Av)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if idx == N:
            if Aw[jdx] + w > limit:
                break
            rw.append(Aw[jdx]+w)
            rv.append(Av[jdx]+v)
            jdx += 1
            continue
        if Aw[idx] <= Aw[jdx] + w:
            rw.append(Aw[idx])
            rv.append(Av[idx])
            idx += 1
        else:
            if Aw[jdx] + w > limit:
                break
            rw.append(Aw[jdx]+w)
            rv.append(Av[jdx]+v)
            jdx += 1
    return rv, rw

def mergedown(A, vw):
    v, w = vw
    res = []
    N = len(A)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if jdx == N:
            res.append(A[idx])
            idx += 1
            continue
        if A[idx][1] <= A[jdx][1] - w:
            res.append(A[idx])
            idx += 1
        else:
            if A[jdx][1] - w < 0:
                jdx += 1
                continue
            res.append((A[jdx][0]+v, A[jdx][1]-w, A[jdx][2]))
            jdx += 1
    return res


def calc(A, B):
    res = []
    N = len(A)
    M = len(B)
    adx = 0
    bdx = 0
    for _ in range(N+M):
        if adx == N:
            res.append(B[bdx])
            bdx += 1
            continue
        if bdx == M:
            res.append(A[adx])
            adx += 1
            continue
        if A[adx][1] < B[bdx][1]:
            res.append(A[adx])
            adx += 1
        else:
            res.append(B[bdx])
            bdx += 1
    return res
  
limit = 10**5
N = int(readline())
VW = [None] + [tuple(map(int, readline().split())) for _ in range(N)]

BS = min(N+1, 1<<12)
Q = int(readline())
VL = [None] + [tuple(map(int, readline().split())) for _ in range(Q)]

Rv = [None]*(N+1)
Rw = [None]*(N+1)
Rv[0] = [0]
Rw[0] = [0]
for i in range(1, BS):
    Rv[i], Rw[i] = mergeup(Rv[i//2], Rw[i//2], VW[i])

table = [[] for _ in range(N+1)]
for i in range(1, Q+1):
    v, l = VL[i]
    table[v].append((0, l, i))
for i in range(1, N+1):
    table[i].sort(key = itemgetter(1))
cnt = 0
for i in range(N, BS-1, -1):
    if table[i]:
        cnt += 2*len(table[i])
        table[i//2] = calc(mergedown(table[i], VW[i]), table[i//2])

ans = [0]*(Q+1)
for i in range(1, BS):
    if table[i]:
        rv = [Rv[i][0]]
        rw = [Rw[i][0]]
        for j in range(1, len(Rv[i])):
            if rv[-1] < Rv[i][j]:
                rv.append(Rv[i][j])
                rw.append(Rw[i][j])
        for k in range(len(table[i])-1, -1, -1):
            v, rew, idx = table[i][k]
            while rw[-1] > rew:
                rw.pop()
                rv.pop()
            ans[idx] = max(ans[idx], v+rv[-1])
print('\n'.join(map(str, ans[1:])))

Submission status: Time Limit Exceeded

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

def mergeup(A, vw):
    v, w = vw
    res = []
    N = len(A)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if idx == N:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
            continue
        if A[idx][1] <=  A[jdx][1] + w:
            res.append(A[idx])
            idx += 1
        else:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
    return res

def mergedown(Av, Aw, vw):
    v, w = vw
    resv, resw = [], []
    N = len(Av)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if jdx == N:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
            continue
        if Aw[idx] <= Aw[jdx] - w:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
        else:
            if Aw[jdx] - w < 0:
                jdx += 1
                continue
            resv.append(Av[jdx] + v)
            resw.append(Aw[jdx] - w)
            jdx += 1
    return resv, resw


def calc(Av, Aw, Ai, Bv, Bw, Bi):
    rv, rw, ri = [], [], []
    N = len(Av)
    M = len(Bv)
    adx = 0
    bdx = 0
    for _ in range(N+M):
        if adx == N:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
            continue
        if bdx == M:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
            continue
        if Aw[adx] < Bw[bdx]:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
        else:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
    return rv, rw, ri
  
  
limit = 10**5
N = int(readline())
VW = [None] + [tuple(map(int, readline().split())) for _ in range(N)]
BS = min(N, 1<<9)
Q = int(readline())
VL = [None] + [tuple(map(int, readline().split())) for _ in range(Q)]


R = [None]*(N+1)
R[0] = [(0, 0)]
for i in range(1, BS+1):
    R[i] = mergeup(R[i//2], VW[i])
    
ans = [0]*(Q+1)
for i in range(1, Q+1):
    v, l = VL[i]
    Kv, Kw = [0], [l]
    while v >= BS:
        Kv, Kw = mergedown(Kv, Kw, VW[v])
        v >>= 1
    Kv1, Kw1 = [Kv[-1]], [Kw[-1]]
    for j in range(len(Kv)-2, -1, -1):
        if Kv1[-1] < Kv[j]:
            Kv1.append(Kv[j])
            Kw1.append(Kw[j])
    for j in range(len(R[v])):
        vj, wj = R[v][j]
        if wj > l:
            break
        while wj > Kw1[-1]:
            Kw1.pop()
            Kv1.pop()
        ans[i] = max(ans[i], vj+Kv1[-1])

print('\n'.join(map(str, ans[1:])))

Submission status: Time Limit Exceeded

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

def mergeup(A, vw):
    v, w = vw
    res = []
    N = len(A)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if idx == N:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
            continue
        if A[idx][1] <=  A[jdx][1] + w:
            res.append(A[idx])
            idx += 1
        else:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
    return res

def mergedown(Av, Aw, vw):
    v, w = vw
    resv, resw = [], []
    N = len(Av)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if jdx == N:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
            continue
        if Aw[idx] <= Aw[jdx] - w:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
        else:
            if Aw[jdx] - w < 0:
                jdx += 1
                continue
            resv.append(Av[jdx] + v)
            resw.append(Aw[jdx] - w)
            jdx += 1
    return resv, resw


def calc(Av, Aw, Ai, Bv, Bw, Bi):
    rv, rw, ri = [], [], []
    N = len(Av)
    M = len(Bv)
    adx = 0
    bdx = 0
    for _ in range(N+M):
        if adx == N:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
            continue
        if bdx == M:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
            continue
        if Aw[adx] < Bw[bdx]:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
        else:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
    return rv, rw, ri
  
  
limit = 10**5
N = int(readline())
VW = [None] + [tuple(map(int, readline().split())) for _ in range(N)]
BS = min(N, 1<<10)
Q = int(readline())
VL = [None] + [tuple(map(int, readline().split())) for _ in range(Q)]


R = [None]*(N+1)
R[0] = [(0, 0)]
for i in range(1, BS+1):
    R[i] = mergeup(R[i//2], VW[i])
    
ans = [0]*(Q+1)
for i in range(1, Q+1):
    v, l = VL[i]
    Kv, Kw = [0], [l]
    while v >= BS:
        Kv, Kw = mergedown(Kv, Kw, VW[v])
        v >>= 1
    Kv1, Kw1 = [Kv[-1]], [Kw[-1]]
    for j in range(len(Kv)-2, -1, -1):
        if Kv1[-1] < Kv[j]:
            Kv1.append(Kv[j])
            Kw1.append(Kw[j])
    for j in range(len(R[v])):
        vj, wj = R[v][j]
        if wj > l:
            break
        while wj > Kw1[-1]:
            Kw1.pop()
            Kv1.pop()
        ans[i] = max(ans[i], vj+Kv1[-1])

print('\n'.join(map(str, ans[1:])))

Submission status: Time Limit Exceeded

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

def mergeup(A, vw):
    v, w = vw
    res = []
    N = len(A)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if idx == N:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
            continue
        if A[idx][1] <=  A[jdx][1] + w:
            res.append(A[idx])
            idx += 1
        else:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
    return res

def mergedown(Av, Aw, vw):
    v, w = vw
    resv, resw = [], []
    N = len(Av)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if jdx == N:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
            continue
        if Aw[idx] <= Aw[jdx] - w:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
        else:
            if Aw[jdx] - w < 0:
                jdx += 1
                continue
            resv.append(Av[jdx] + v)
            resw.append(Aw[jdx] - w)
            jdx += 1
    return resv, resw


def calc(Av, Aw, Ai, Bv, Bw, Bi):
    rv, rw, ri = [], [], []
    N = len(Av)
    M = len(Bv)
    adx = 0
    bdx = 0
    for _ in range(N+M):
        if adx == N:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
            continue
        if bdx == M:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
            continue
        if Aw[adx] < Bw[bdx]:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
        else:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
    return rv, rw, ri
  
  
limit = 10**5
N = int(readline())
VW = [None] + [tuple(map(int, readline().split())) for _ in range(N)]
BS = min(N, 1<<11)
Q = int(readline())
VL = [None] + [tuple(map(int, readline().split())) for _ in range(Q)]


R = [None]*(N+1)
R[0] = [(0, 0)]
for i in range(1, BS+1):
    R[i] = mergeup(R[i//2], VW[i])
    
ans = [0]*(Q+1)
for i in range(1, Q+1):
    v, l = VL[i]
    Kv, Kw = [0], [l]
    while v >= BS:
        Kv, Kw = mergedown(Kv, Kw, VW[v])
        v >>= 1
    Kv1, Kw1 = [Kv[-1]], [Kw[-1]]
    for j in range(len(Kv)-2, -1, -1):
        if Kv1[-1] < Kv[j]:
            Kv1.append(Kv[j])
            Kw1.append(Kw[j])
    for j in range(len(R[v])):
        vj, wj = R[v][j]
        if wj > l:
            break
        while wj > Kw1[-1]:
            Kw1.pop()
            Kv1.pop()
        ans[i] = max(ans[i], vj+Kv1[-1])

print('\n'.join(map(str, ans[1:])))

Submission status: Time Limit Exceeded

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

def mergeup(A, vw):
    v, w = vw
    res = []
    N = len(A)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if idx == N:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
            continue
        if A[idx][1] <=  A[jdx][1] + w:
            res.append(A[idx])
            idx += 1
        else:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
    return res

def mergedown(Av, Aw, vw):
    v, w = vw
    resv, resw = [], []
    N = len(Av)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if jdx == N:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
            continue
        if Aw[idx] <= Aw[jdx] - w:
            resv.append(Av[idx])
            resw.append(Aw[idx])
            idx += 1
        else:
            if Aw[jdx] - w < 0:
                jdx += 1
                continue
            resv.append(Av[jdx] + v)
            resw.append(Aw[jdx] - w)
            jdx += 1
    return resv, resw


def calc(Av, Aw, Ai, Bv, Bw, Bi):
    rv, rw, ri = [], [], []
    N = len(Av)
    M = len(Bv)
    adx = 0
    bdx = 0
    for _ in range(N+M):
        if adx == N:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
            continue
        if bdx == M:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
            continue
        if Aw[adx] < Bw[bdx]:
            rv.append(Av[adx])
            rw.append(Aw[adx])
            ri.append(Ai[adx])
            adx += 1
        else:
            rv.append(Bv[bdx])
            rw.append(Bw[bdx])
            ri.append(Bi[bdx])
            bdx += 1
    return rv, rw, ri
  
  
limit = 10**5
N = int(readline())
VW = [None] + [tuple(map(int, readline().split())) for _ in range(N)]
BS = min(1, N, 1<<12)
Q = int(readline())
VL = [None] + [tuple(map(int, readline().split())) for _ in range(Q)]


R = [None]*(N+1)
R[0] = [(0, 0)]
for i in range(1, BS+1):
    R[i] = mergeup(R[i//2], VW[i])
    
tv = [[] for _ in range(N+1)]
tw = [[] for _ in range(N+1)]
ti = [[] for _ in range(N+1)]
for i in range(1, Q+1):
    v, l = VL[i]
    Kv, Kw = [0], [l]
    while v > BS:
        Kv, Kw = mergedown(Kv, Kw, VW[v])
        v >>= 1
    tv[v].append(Kv)
    tw[v].append(Kw)
    ti[v].append([i]*len(Kv))
    
for i in range(1, N+1):
    lt = len(tv[i])
    if lt == 0:
        continue
    if lt == 1:
        tv[i], tw[i], ti[i] = tv[i][0], tw[i][0], ti[i][0]
        continue
    d = 1
    while 2*d <= lt:
        for j in range(0, 1+lt-2*d, 2*d):
            tv[i][j], tw[i][j], ti[i][j] = calc(tv[i][j], tw[i][j], ti[i][j], tv[i][j+d], tw[i][j+d], ti[i][j+d])
        if j+2*d < lt:
            tv[i][0], tw[i][0], ti[i][0] = calc(tv[i][0], tw[i][0], ti[i][0], tv[i][j+2*d], tw[i][j+2*d], ti[i][j+2*d])
        d <<= 1
    tv[i], tw[i], ti[i] = tv[i][0], tw[i][0], ti[i][0]

ans = [0]*(Q+1)
for i in range(1, BS+1):
    if tv[i]:
        res = [R[i][0]]
        for j in range(1, len(R[i])):
            if res[-1][0] < R[i][j][0]:
                res.append(R[i][j])
        
        for k in range(len(tv[i])-1, -1, -1):
            v, rw, idx = tv[i][k], tw[i][k], ti[i][k]
            while res[-1][1] > rw:
                res.pop()
            ans[idx] = max(ans[idx], v+res[-1][0])

print('\n'.join(map(str, ans[1:])))

Submission status: Time Limit Exceeded

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

def mergeup(A, vw):
    v, w = vw
    res = []
    N = len(A)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if idx == N:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
            continue
        if A[idx][1] <=  A[jdx][1] + w:
            res.append(A[idx])
            idx += 1
        else:
            if A[jdx][1] + w > limit:
                break
            res.append((A[jdx][0] + v, A[jdx][1] + w))
            jdx += 1
    return res

def mergedown(A, vw):
    v, w = vw
    res = []
    N = len(A)
    idx = 0
    jdx = 0
    for _ in range(2*N):
        if jdx == N:
            res.append(A[idx])
            idx += 1
            continue
        if A[idx][1] <=  A[jdx][1] - w:
            res.append(A[idx])
            idx += 1
        else:
            if A[jdx][1] - w < 0:
                jdx += 1
                continue
            res.append((A[jdx][0] + v, A[jdx][1] - w))
            jdx += 1
    return res

def calc(A, B):
    res = []
    N = len(A)
    M = len(B)
    adx = 0
    bdx = 0
    for _ in range(N+M):
        if adx == N:
            res.append(B[bdx])
            bdx += 1
            continue
        if bdx == M:
            res.append(A[adx])
            adx += 1
            continue
        if A[adx][1] < B[bdx][1]:
            res.append(A[adx])
            adx += 1
        else:
            res.append(B[bdx])
            bdx += 1
    return res

limit = 10**5
N = int(readline())
BS = min(N, 1<<12)
VW = [None] + [tuple(map(int, readline().split())) for _ in range(N)]
Q = int(readline())
VL = [None] + [tuple(map(int, readline().split())) for _ in range(Q)]

R = [None]*(N+1)
R[0] = [(0, 0)]
for i in range(1, BS+1):
    R[i] = mergeup(R[i//2], VW[i])

table = [[] for _ in range(N+1)]

for i in range(1, Q+1):
    v, l = VL[i]
    K = [(0, l)]
    while v > BS:
        K = mergedown(K, VW[v])
        v >>= 1
    K = [(v, rw, i) for v, rw in K]
    table[v] = calc(table[v], K)    

ans = [0]*(Q+1)
for i in range(1, BS+1):
    if table[i]:
        res = [R[i][0]]
        for j in range(1, len(R[i])):
            if res[-1][0] < R[i][j][0]:
                res.append(R[i][j])
        
        for k in range(len(table[i])-1, -1, -1):
            v, rw, idx = table[i][k]
            while res[-1][1] > rw:
                res.pop()
            ans[idx] = max(ans[idx], v+res[-1][0])

print('\n'.join(map(str, ans[1:])))

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
vw=[list(map(int,input().split())) for i in range(n)]
#vmax=max(i[0] for i in vw)
#前計算用のDPを用意する
#1~2^10までは計算で先に求めておく
dp=[[0]*(10**5+1) for i in range(2**10)]
#前計算
def dfs(i):
    global n,vw,dp,vmax
    j=i//2
    for k in range(10**5,-1,-1):
        if dp[j-1][k]!=0 or k==0:
            if k+vw[i-1][1]<=10**5:
                dp[i-1][k+vw[i-1][1]]=max(dp[j-1][k]+vw[i-1][0],dp[i-1][k+vw[i-1][1]])
            dp[i-1][k]=max(dp[j-1][k],dp[i-1][k])
    if i*2<=2**10 and i*2<=n:
        dfs(i*2)
        if i*2+1<=2**10 and i*2+1<=n:
            dfs(i*2+1)
dfs(1)
for i in range(2**10):
    for j in range(10**5):
        dp[i][j+1]=max(dp[i][j],dp[i][j+1])
q=int(input())
for i in range(q):
    #それぞれの部分木をたどる
    #こっちで残りを全探索
    v,l=map(int,input().split())
    cand=[]
    while v>2**10:
        cand.append(v//2)
        v=v//2
    r=len(cand)
    ans=0
    for j in range(2**r):
        v_sub=0
        w_sub=0
        for k in range(r):
            v_sub+=vw[cand[k]-1][0]*(j>>k)&1
            w_sub+=vw[cand[k]-1][1]*(j>>k)&1
        if w_sub>l:
            continue
        else:
            ans=max(ans,dp[v-1][l-w_sub]+v_sub)
    print(ans)

Submission status: Time Limit Exceeded

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

N = int(input())
vws = np.array([tuple(map(int, input().split())) for _ in range(N)], np.int32)

n = min(2**11, N)

@njit("i4[:, :](i4[:, :], )", cache = True)
def precompute(vws):
    dp = np.zeros((n, 10**5+1), np.int32)
    dp[0, vws[0, 1]:] = vws[0, 0]
    for i in range(1, n):
        v, w = vws[i]
        dp[i] = dp[(i-1)//2]
        dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])
    return dp

@njit("i4(i4[:], i4[:], i4, i4[:])", cache = True)
def func(vs, ws, L, dp_):
    bits = np.arange(1 << len(vs))
    values = np.zeros_like(bits, np.int32)
    weights = np.zeros_like(bits, np.int32)
    for i in range(len(vs)):
        indices = np.nonzero(np.bitwise_and(bits, 1<<i))
        values[indices] += vs[i]
        weights[indices] += ws[i]

    mask = (weights <= L)     
    return np.amax(dp_[L - weights[mask]] + values[mask])

dp = precompute(vws)

Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V, L])
    else:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws[Vs, 0]
        ws = vws[Vs, 1]
        print(func(np.array(vs, np.int32), np.array(ws, np.int32), L, dp[V]))

Submission status: Time Limit Exceeded

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

N = int(input())
vws = np.array([tuple(map(int, input().split())) for _ in range(N)], np.int32)

n = min(2**1, N)

@njit("i4[:, :](i4[:, :], )", cache = True)
def precompute(vws):
    dp = np.zeros((n, 10**5+1), np.int32)
    dp[0, vws[0, 1]:] = vws[0, 0]
    for i in range(1, n):
        v, w = vws[i]
        dp[i] = dp[(i-1)//2]
        dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])
    return dp

@njit("i4(i4[:], i4[:], i4, i4[:])", cache = True)
def func(vs, ws, L, dp_):
    bits = np.arange(1 << len(vs))
    values = np.zeros_like(bits, np.int32)
    weights = np.zeros_like(bits, np.int32)
    for i in range(len(vs)):
        indices = np.nonzero(np.bitwise_and(bits, 1<<i))
        values[indices] += vs[i]
        weights[indices] += ws[i]

    mask = (weights <= L)     
    return np.amax(dp_[L - weights[mask]] + values[mask])

dp = precompute(vws)

Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V, L])
    else:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws[Vs, 0]
        ws = vws[Vs, 1]
        print(func(np.array(vs, np.int32), np.array(ws, np.int32), L, dp[V]))

Submission status: Time Limit Exceeded

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

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]

n = min(2**10, N)

dp = np.zeros((n, 10**5+1), np.int32)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, n):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

@njit("(i4[::], i4[::], i4, i4)", cache = True)
def func(vs, ws, V, L):
    bits = np.arange(1 << len(vs))
    values = np.zeros_like(bits, np.int32)
    weights = np.zeros_like(bits, np.int32)
    for i in range(len(vs)):
        indices = np.nonzero(np.bitwise_and(bits, 1<<i))
        values[indices] += vs[i]
        weights[indices] += ws[i]

    mask = (weights <= L)     
    print(np.amax(dp[V][L - weights[mask]] + values[mask]))


Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V][L])
    else:
        vws_choose = []
        while V >= n:
            vws_choose.append(vws[V])
            V = (V-1) // 2
        vs, ws = zip(*vws_choose)
        func(np.array(vs, np.int32), np.array(ws, np.int32), V, L)

Submission status: Time Limit Exceeded

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

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]

n = min(2**1, N)

dp = np.zeros((n, 10**5+1), np.int32)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, n):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

@njit("(i4[::], i4[::], i4, i4)", cache = True)
def func(vs, ws, V, L):
    bits = np.arange(1 << len(vs))
    values = np.zeros_like(bits, np.int32)
    weights = np.zeros_like(bits, np.int32)
    for i in range(len(vs)):
        indices = np.nonzero(np.bitwise_and(bits, 1<<i))
        values[indices] += vs[i]
        weights[indices] += ws[i]

    mask = (weights <= L)     
    print(np.amax(dp[V][L - weights[mask]] + values[mask]))


Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V][L])
    else:
        vws_choose = []
        while V >= n:
            vws_choose.append(vws[V])
            V = (V-1) // 2
        vs, ws = zip(*vws_choose)
        func(np.array(vs, np.int32), np.array(ws, np.int32), V, L)

Submission status: Time Limit Exceeded

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

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]

n = min(2**10, N)

dp = np.zeros((n, 10**5+1), np.int32)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, n):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

@njit(cache = True)
def func(vws_choose, L):
    bits = np.arange(1 << len(vws_choose))
    values = np.zeros_like(bits, np.int32)
    weights = np.zeros_like(bits, np.int32)
    for i in range(len(vws_choose)):
        indices = np.nonzero(np.bitwise_and(bits, 1<<i))
        values[indices] += vws_choose[i][0]
        weights[indices] += vws_choose[i][1]

    mask = (weights <= L)     
    print(np.amax(dp[V][L - weights[mask]] + values[mask]))


Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V][L])
    else:
        vws_choose = []
        while V >= n:
            vws_choose.append(vws[V])
            V = (V-1) // 2

        func(np.array(vws_choose), L)

Submission status: Time Limit Exceeded

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

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]

n = min(2**9, N)

dp = np.zeros((n, 10**5+1), np.int64)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, n):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

@njit(parallel = True, cache = True)
def func(vws_choose, L):
    bits = np.arange(1 << len(vws_choose))
    values = np.zeros_like(bits, np.int64)
    weights = np.zeros_like(bits, np.int64)
    for i in prange(len(vws_choose)):
        indices = np.nonzero(np.bitwise_and(bits, 1<<i))
        values[indices] += vws_choose[i][0]
        weights[indices] += vws_choose[i][1]

    mask = (weights <= L)     
    print(np.amax(dp[V][L - weights[mask]] + values[mask]))


Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V][L])
    else:
        vws_choose = []
        while V >= n:
            vws_choose.append(vws[V])
            V = (V-1) // 2

        func(np.array(vws_choose), L)

Submission status: Time Limit Exceeded

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

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]

n = min(2**10, N)

dp = np.zeros((n, 10**5+1), np.int64)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, n):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

@njit(cache = True)
def func(vws_choose, L):
    bits = np.arange(1 << len(vws_choose))
    values = np.zeros_like(bits, np.int64)
    weights = np.zeros_like(bits, np.int64)
    for i in range(len(vws_choose)):
        indices = np.nonzero(np.bitwise_and(bits, 1<<i))
        values[indices] += vws_choose[i][0]
        weights[indices] += vws_choose[i][1]

    mask = (weights <= L)     
    print(np.amax(dp[V][L - weights[mask]] + values[mask]))


Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V][L])
    else:
        vws_choose = []
        while V >= n:
            vws_choose.append(vws[V])
            V = (V-1) // 2

        func(vws_choose, L)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
input = sys.stdin.buffer.readline

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]

n = min(2**10, N)

dp = np.zeros((n, 10**5+1), np.int64)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, n):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V][L])
    else:
        d = {0: 0}
        while V >= n:
            v, w = vws[V]
            iterator = list(d.items())
            for w_sum, v_sum in iterator:
                if w_sum + w not in d:
                    d[w_sum + w] = v_sum + v
                else:
                    d[w_sum + w] = max(v_sum + v, d[w_sum + w])
            V = (V-1) // 2

        v_max = 0
        for w1, v1 in d.items():
            if 0 <= L-w1:            
                v_max = max(v_max, v1 + dp[V][L-w1])
        print(v_max)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
input = sys.stdin.buffer.readline

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]

n = min(2**12, N)

dp = np.zeros((n, 10**5+1), np.int64)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, n):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    V -= 1
    if V < n:
        print(dp[V][L])
    else:
        d = {0: 0}
        while V >= n:
            v, w = vws[V]
            iterator = list(d.items())
            for w_sum, v_sum in iterator:
                if w_sum + w not in d:
                    d[w_sum + w] = v_sum + v
                else:
                    d[w_sum + w] = max(v_sum + v, d[w_sum + w])
            V = (V-1) // 2

        v_max = 0
        for w1, v1 in d.items():
            if 0 <= L-w1:            
                v_max = max(v_max, v1 + dp[V][L-w1])
        print(v_max)