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
import numpy as np
from numba import njit

input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

@njit(cache = True)
def pre(vws):
    dp = np.zeros((n, 10**5+1), np.int32)
    for i in range(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[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[L - weights[mask]] + values[mask])

@njit(cache = True)
def query(dp, VLs, vws):
    for V, L in VLs:
        V -= 1
        if V < n:
            print(dp[V, L])
        else:
            vs = []
            ws = []
            while V >= n:
                vs.append(vws[V][0])
                ws.append(vws[V][1])
                V = (V-1) // 2
            print(func(np.array(vs, np.int32), np.array(ws, np.int32), L, dp[V]))

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]
Q = int(input())
VLs = list(map(lambda s: tuple(map(int, s.split())), readlines()))

n = min(2**10, N)

dp = pre(vws)
query(dp, VLs, vws)

Submission status: Time Limit Exceeded

Solution code:
import sys
import numpy as np
from numba import njit

input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]
Q = int(input())
VLs = list(map(lambda s: tuple(map(int, s.split())), readlines()))

n = min(2**10, N)

@njit(cache = True)
def pre(vws):
    dp = np.zeros((n, 10**5+1), np.int32)
    for i in range(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

dp = pre(vws)

@njit("i4(i4[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[L - weights[mask]] + values[mask])

for V, L in VLs:
    V -= 1
    if V < n:
        print(dp[V, L])
    else:
        vs = []
        ws = []
        while V >= n:
            vs.append(vws[V][0])
            ws.append(vws[V][1])
            V = (V-1) // 2
        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
readlines = sys.stdin.buffer.readlines

N = int(input())
vws = [tuple(map(int, input().split())) for _ in range(N)]
Q = int(input())
VLs = list(map(lambda s: tuple(map(int, s.split())), readlines()))

n = min(2**10, N)

dp = np.zeros((n, 10**5+1), np.int32)
for i in range(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[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[L - weights[mask]] + values[mask])

for V, L in VLs:
    V -= 1
    if V < n:
        print(dp[V, L])
    else:
        vs = []
        ws = []
        while V >= n:
            vs.append(vws[V][0])
            ws.append(vws[V][1])
            V = (V-1) // 2
        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, prange

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[::1], i4[::1], i4, i4[::1])", cache = True, parallel = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in prange(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        vs = []
        ws = []
        while V >= n:
            vs.append(vws[V][0])
            ws.append(vws[V][1])
            V = (V-1) // 2
        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[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        vs = []
        ws = []
        while V >= n:
            vs.append(vws[V][0])
            ws.append(vws[V][1])
            V = (V-1) // 2
        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)
vws_arr = np.array(vws, np.int32)

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[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(vs, ws, 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)
vws_arr = np.array(vws, np.int32)

@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

dp = precompute(vws_arr)

@njit("i4(i4[:], i4[:], i4, i4[:])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(vs, ws, 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)
vws_arr = np.array(vws, np.int32)

@njit(cache = True)
def pre(n, 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

dp = pre(n, vws)
  
@njit("i4(i4[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(vs, ws, 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**9, N)
vws_arr = np.array(vws, np.int32)

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[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(vs, ws, 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)
vws_arr = np.array(vws, np.int32)

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[::1], i4[::1], i4, i4[::1])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for i in range(len(vs)):
        for bits in range(1 << len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(vs, ws, 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)
vws_arr = np.array(vws, np.int32)

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, i4[:])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for bits in range(1 << len(vs)):
        for i in range(len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(vs, ws, 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**2, N)
vws_arr = np.array(vws, np.int32)

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, i4[:])", cache = True)
def func(vs, ws, L, dp_):
    values = np.zeros(1 << len(vs), np.int32)
    weights = np.zeros(1 << len(vs), np.int32)
    for bits in range(1 << len(vs)):
        for i in range(len(vs)):
            if bits & (1 << i):
                values[bits] += vs[i]
                weights[bits] += ws[i]
    mask = (weights <= L)     
    return np.amax(dp_[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:
        Vs = []
        while V >= n:
            Vs.append(V)
            V = (V-1) // 2
        vs = vws_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(vs, ws, 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 = 2 ** 18
vws = [(1, i%10 + 1) for i in range(N)]
#'''

n = min(2**10, N)
vws_arr = np.array(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:])


@njit("i4(i4[:], i4[:], i4, i4[:], i4[:])", cache = True)
def func(vs, ws, L, dp_, bits):
    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])


bits = np.arange(1 << 8).astype(np.int32)

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_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(np.array(vs, np.int32), np.array(ws, np.int32), L, dp[V], bits[:1 << len(Vs)]))

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)
vws_arr = np.array(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:])


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

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_arr[Vs, 0]
        ws = vws_arr[Vs, 1]
        print(func(np.array(vs, np.int32), np.array(ws, np.int32), L, dp[V]))

Submission status: Time Limit Exceeded

Solution code:
# D - Knapsack Queries on a tree

n = int(input())
vw = [tuple(map(int, input().split())) for _ in range(n)]
q = int(input())
vl = [tuple(map(int, input().split())) for _ in range(q)]

tables = [None] * n

def dfs(u, table):
    "u: vertex; table: weight -> max value"
    if u >= n:
        return
    val, wgt = vw[u]
    tables[u] = table.copy()
    for w in table:
        v1 = table[w] + val
        v2 = table[w + wgt] if w + wgt in table else 0
        tables[u][w + wgt] = max(v1, v2)
    dfs(u * 2 + 1, tables[u])
    dfs(u * 2 + 2, tables[u])

dfs(0, {0: 0})

for v, l in vl:
    if l not in tables[v - 1]:
        tables[v - 1][l] = 0

for v in range(n):
    m = 0
    for k in sorted(tables[v].keys()):
        m = max(m, tables[v][k])
        tables[v][k] = m

for v, l in vl:
    print(tables[v - 1][l])

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+2**9)]
#前計算
def dfs(i):
    global n,vw,dp
    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+2**9 and i*2<=n:
        dfs(i*2)
        if i*2+1<=2**10+2**9 and i*2+1<=n:
            dfs(i*2+1)
dfs(1)
for i in range(2**10+2**9):
    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:
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
    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:
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+2**9)]
#前計算
def dfs(i):
    global n,vw,dp
    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+2**9 and i*2+1<=n:
            dfs(i*2+1)
dfs(1)
for i in range(2**10+2**9):
    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+2**9:
        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 bisect
from functools import lru_cache
from collections import defaultdict
inf = float('inf')
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10**6)
def input(): return sys.stdin.readline().rstrip()
def read():
  return int(readline())
def reads():
  return map(int, readline().split())
n=read()
V,W=[0]*(n+1),[0]*(n+1)
for i in range(1,n+1):
  V[i],W[i]=reads()
q=read()
v,L=[0]*q,[0]*q
for i in range(q):
  v[i],L[i]=reads()
def solve(index,maxweight):#indexは頂点の位置
  pricels=[V[index]]
  weightls=[W[index]]
  hoge=index
  while(True):
    hoge//=2
    if hoge==0:
      break
    pricels.append(V[hoge])
    weightls.append(W[hoge])
  #print(pricels)
  #print(weightls)
  lw=max(len(weightls),maxweight)
  l=len(pricels)
  dp=[[0 for i in range(l+1)]for j in range(lw+1)]
  for i in range(1,lw+1):#weight
    for j in range(1,l+1):#price
      dp[i][j]=dp[i][j-1]
      #print(i,weightls[j])
      if i-weightls[j-1]>=0:
      	dp[i][j]=max(dp[i-weightls[j-1]][j-1]+pricels[j-1],dp[i][j])
  #print(dp)
  return dp[lw][l] 
for i in range(q):
  print(solve(v[i],L[i]))

Submission status: Time Limit Exceeded

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


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

    return rv, rw

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


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


Rv = [[0] for _ in range(BS+1)]
Rw = [[0] for _ in range(BS+1)]
for i in range(1, BS):
    for vm, wm in zip(*mergeup(Rv[i//2], Rw[i//2], VW[i])):
        if Rv[i][-1] < vm:
          Rv[i].append(vm)
          Rw[i].append(wm)
    
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
    cnt = len(Rv[v])-1
    ctr = 0
    for j in range(len(Kv)-1, -1, -1):
        kv, kw = Kv[j], Kw[j]
        while kw < Rw[v][cnt]:
            cnt -= 1
        ctr = max(ctr, kv+Rv[v][cnt])
    ans[i] = ctr

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

Submission status: Time Limit Exceeded

Solution code:
import sys
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 or Aw[idx] > Aw[jdx] + w:
            if Aw[jdx] + w > limit:
                break
            rw.append(Aw[jdx]+w)
            rv.append(Av[jdx]+v)
            jdx += 1
        else:
            rw.append(Aw[idx])
            rv.append(Av[idx])
            idx += 1

    return tuple(rv), tuple(rw)

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


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


Rv = [[0] for _ in range(BS+1)]
Rw = [[0] for _ in range(BS+1)]
for i in range(1, BS):
    for vm, wm in zip(*mergeup(Rv[i//2], Rw[i//2], VW[i])):
        if Rv[i][-1] < vm:
          Rv[i].append(vm)
          Rw[i].append(wm)
    
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
    cnt = len(Rv[v])-1
    ctr = 0
    for j in range(len(Kv)-1, -1, -1):
        kv, kw = Kv[j], Kw[j]
        while kw < Rw[v][cnt]:
            cnt -= 1
        ctr = max(ctr, kv+Rv[v][cnt])
    ans[i] = ctr

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

Submission status: Time Limit Exceeded

Solution code:
import sys
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 or Aw[idx] > Aw[jdx] + w:
            if Aw[jdx] + w > limit:
                break
            rw.append(Aw[jdx]+w)
            rv.append(Av[jdx]+v)
            jdx += 1
        else:
            rw.append(Aw[idx])
            rv.append(Av[idx])
            idx += 1

    return rv, rw

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


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


Rv = [[0] for _ in range(BS+1)]
Rw = [[0] for _ in range(BS+1)]
for i in range(1, BS):
    for vm, wm in zip(*mergeup(Rv[i//2], Rw[i//2], VW[i])):
        if Rv[i][-1] < vm:
          Rv[i].append(vm)
          Rw[i].append(wm)
    
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
    cnt = len(Rv[v])-1
    ctr = 0
    for j in range(len(Kv)-1, -1, -1):
        kv, kw = Kv[j], Kw[j]
        while kw < Rw[v][cnt]:
            cnt -= 1
        ctr = max(ctr, kv+Rv[v][cnt])
    ans[i] = ctr

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