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: Runtime Error

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<<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[0][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: Runtime Error

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<<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, 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[0][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: Runtime Error

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<<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, lt, 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[0][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: Runtime Error

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<<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, lt, 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 lt-1 <= j+2*d:
            tv[i][0], tw[i][0], ti[0][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: Runtime Error

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 calc1(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<<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, lt, 2*d):
            tv[i][j], tw[i][j], ti[i][j] = calc1(tv[i][j], tw[i][j], ti[i][j], tv[i][j+1], tw[i][j+1], ti[i][j+1])
        if lt&1:
            tv[i][0], tw[i][0], ti[0][0] = calc1(tv[i][0], tw[i][0], ti[i][0], tv[i][-1], tw[i][-1], ti[i][-1])
        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: Runtime Error

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

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: Runtime Error

Solution code:
n=int(input())
vw=[list(map(int,input().split())) for _ in range(n)]
q=int(input())
vl=[list(map(int,input().split())) for _ in range(q)]
m=max(vl[:][1])
dp=[[0]*(m+1) for _ in range(n+1)]
for i in range(1,n+1):
    v,w=vw[i-1]
    for j in range(m+1):
        if j>=w:
            dp[i][j]=max(dp[i//2][j-w]+v,dp[i//2][j])
        else:
            dp[i][j]=dp[i//2][j]
for i in range(q):
    v,l=vl[i]
    V,W=vw[v-1]
    if l>=W:
        print(max(dp[v//2][l-W]+V,dp[v//2][l]))
    else:
        print(dp[v//2][l])

Submission status: Runtime Error

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

Submission status: Runtime Error

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:
        vws_choose = []
        while V >= n:
            vws_choose.append(vws[V])
            V = (V-1) // 2

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

Submission status: Runtime Error

Solution code:
import sys

int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    mx=10**5
    n=II()
    # 上半分をDP
    pn=min(511,n)
    vw=LLI(n)
    dp=[[0]*(mx+1) for _ in range(pn)]
    v,w=vw[0]
    dp[0][w:]=[v]*(mx+1-w)
    for nu in range(1,pn):
        v,w=vw[nu]
        u=(nu-1)//2
        for j in range(w,mx+1):
            dp[nu][j]=max(dp[u][j],dp[u][j-w]+v)
    #p2D(dp)

    q=II()
    for _ in range(q):
        u,m=MI()
        u-=1
        # 上半分のときはDPから
        if u<pn:print(dp[u][m])
        else:
            #下半分を全列挙
            ss=[(0,0)]
            while u>=pn:
                dv,dw=vw[u]
                for v,w in ss[:]:ss.append((v+dv,w+dw))
                u=(u-1)//2
                #print(u,ss)

            # 下半分を上半分のDPと組み合わせて最大値を求める
            ans=-1
            for v,w in ss:
                cur=v+dp[u][m-w]
                if cur>ans:ans=cur
            print(ans)

main()

Submission status: Runtime Error

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    mx=10**5
    n=II()
    # 上半分をDP
    h=n.bit_length()//2
    pn=(1<<h)-1
    vw=LLI(n)
    dp=[[0]*(mx+1) for _ in range(pn)]
    v,w=vw[0]
    dp[0][w:]=[v]*(mx+1-w)
    for nu in range(1,pn):
        v,w=vw[nu]
        u=(nu-1)//2
        for j in range(w,mx+1):
            dp[nu][j]=max(dp[u][j],dp[u][j-w]+v)
    #p2D(dp)

    q=II()
    for _ in range(q):
        u,m=MI()
        u-=1
        # 上半分のときはDPから
        if u<pn:print(dp[u][m])
        else:
            #下半分を全列挙
            ss=[(0,0)]
            while u>=pn:
                nss=[]
                i=j=0
                sn=len(ss)
                dv,dw=vw[u]
                while i<sn or j<sn:
                    v0=v1=w0=w1=10**9
                    if i<sn:v0,w0=ss[i]
                    if j<sn:v1,w1=ss[j]
                    v1,w1=v1+dv,w1+dw
                    if w0<w1:i+=1;v,w=v0,w0
                    else:j+=1;v,w=v1,w1
                    if w>m:break
                    if nss and nss[-1][1]==w:
                        if nss[-1][0]<v:nss.pop()
                        else:continue
                    if nss and nss[-1][0]>=v:continue
                    nss.append((v,w))
                ss=nss
                u=(u-1)//2
            #print(ss)

            # 下半分を上半分のDPと組み合わせて最大値を求める
            ans=-1
            for v,w in ss:
                cur=v+dp[u][m-w]
                if cur>ans:ans=cur
            print(ans)

main()