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
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
import numpy as np
from numba import njit


n = int(input())
V = [None]*n
W = [None]*n
for i in range(n):
    V[i],W[i] = map(int, input().split())

from queue import deque
q = deque([0])
d = [None]*n
d[0] = np.array([(0,0), (W[0], V[0])], dtype=np.int32)


until = min(n, 2**9-1)

@njit("i4[:,:],i4,i4", cache=True)
def sub0(l, w, v):
    ll = np.zeros_like(l)
    ll += l
    ll[:,0] += w
    ll[:,1] += v
    s = 1
    nl = np.zeros((l.shape[0]*2, 2), dtype=np.int32)
    i1 = 0
    i2 = 0
    length = len(l)
    while i1<length or i2<length:
        if i1<length and (i2>=length or l[i1][0]<ll[i2][0]):
            if l[i1][1]>nl[-1][1]:
                nl[s,:] = l[i1]
                s += 1
            i1 += 1
        elif i2<length:
            if ll[i2][1]>nl[-1][1]:
                nl[s,:] = ll[i2]
                s += 1
            i2 += 1      
    return nl[:s]

while q:
    u = q.pop()
    l = np.array(d[u], dtype=np.int32)
    for v in (2*u+1, 2*u+2):
        if v>=until:
            continue
        nl = sub0(l, W[v], V[v])
        d[v] = nl
#         print(l, ll, nl)
        q.appendleft(v)

@njit("i4[:,:],i4[:,:],i4", cache=True)
def merge(l1, l2, L):
    right = len(l2)-1
    ans = -1
    for left in range(len(l1)):
        w1, v1 = l1[left]
        while right>0 and w1+l2[right][0]>L:
            right -= 1
        if w1+l2[right][0]<=L:
            ans = max(ans, v1+l2[right][1])
        else:
            break
    return ans

def sub(vv, L):
    if d[vv] is None:
        ll = np.array([(0,0)], dtype=np.int32)
        while d[vv] is None:
            ll = sub0(ll, W[vv], V[vv])
            vv = (vv-1)//2
        tmp = ll
    else:
        tmp = np.array([(0,0)], dtype=np.int32)
    l = d[vv]
    ans = merge(l, tmp, L)
    return ans
        
q = int(input())
ans = [None]*q
for i in range(q):
    vv, ll = map(int, input().split())
    vv -= 1
    ans[i] = sub(vv, ll)
write("\n".join(map(str, ans)))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

#n,k,*a = map(int,read().split())
n, = map(int,readline().split())
vw = [(0,0)]+[tuple(map(int,readline().split())) for _ in range(n)]

#print(vw)
A = 9
N = min(1<<A,n+1)

memo = [None for _ in range(N)]
L = 10**5+1
memo[0] = [0]*L

for i in range(1,N):
    m = memo[i>>1][:]
    v,w = vw[i]    
    for j in range(L-1,w-1,-1):
        if m[j] < m[j-w]+v:
            m[j] = m[j-w]+v
    memo[i] = m
    #for j in range(1,L):
    #    memo[i][j] = max(memo[i][j],memo[i][j-1])


q, = map(int,readline().split())
for _ in range(q):
    u,l = map(int,readline().split())
    
    ans = 0
    q = [(0,0,u)]
    while q:
        v,w,u = q.pop()
        if u < N:
            if w <= l:
                ans = max(ans,memo[u][l-w]+v)
        else:
            q.append((v,w,u>>1))
            q.append((v+vw[u][0],w+vw[u][1],u>>1))    

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline

#n,k,*a = map(int,read().split())
n, = map(int,readline().split())
vw = [(0,0)]+[tuple(map(int,readline().split())) for _ in range(n)]

#print(vw)
A = 9
N = min(1<<A,n+1)

memo = [None for _ in range(N)]
L = 10**5+1
memo[0] = [0]*L

for i in range(1,N):
    m = memo[i>>1][:]
    v,w = vw[i]    
    for j in range(L-1,w-1,-1):
        if m[j] < m[j-w]+v:
            m[j] = m[j-w]+v
    memo[i] = m
    #for j in range(1,L):
    #    memo[i][j] = max(memo[i][j],memo[i][j-1])


q, = map(int,readline().split())
for _ in range(q):
    u,l = map(int,readline().split())

    dic = [(0,0)]
    while u >= N:
        dic += [(vw[u][1]+w1,vw[u][0]+v1) for w1,v1 in dic]
        u >>= 1
    
    ans = 0
    for w,v in dic:
        if w <= l:
            ans = max(ans,memo[u][l-w]+v)
    print(ans)

Submission status: Time Limit Exceeded

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

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

    n = I()
    V = []
    W = []

    maxL = 10**5
    m = min(n, 1 << 10)
    dp = [[0]*(maxL + 1)]
    
    for i in range(n):
        v, w = LI()
        if i <= m:
            d_ = dp[(i+1)>>1][:]
            for j in range(w, maxL+1)[::-1]:
                d_[j] = max(d_[j], d_[j - w] + v)
            dp.append(d_)
        V.append(v)
        W.append(w)
    
    q = I()
    for i in range(q):
        v, L = LI()
        if v <= m:
            print(dp[v][L])
            continue
        cnt = 0
        v_ = []
        w_ = []
        while v > m:
            v_.append(V[v-1])
            w_.append(W[v-1])
            v >>= 1
            cnt += 1
        ret = dp[v][L]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[v][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

    n = I()
    V = []
    W = []

    maxL = 10**5
    m = min(n, 1 << 10)
    dp = [[0]*(maxL + 1)]
    
    for i in range(n):
        v, w = LI()
        if i <= m:
            d_ = dp[(i+1)>>1][:]
            for j in range(w, maxL+1)[::-1]:
                d_[j] = max(d_[j], d_[j - w] + v)
            dp.append(d_)
        V.append(v)
        W.append(w)
    
    q = I()
    for i in range(q):
        v, L = LI()
        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]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

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

    n = I()
    V = []
    W = []

    maxL = 10**5
    m = min(n, 1 << 10)
    dp = [[0]*(maxL + 1)]
    
    for i in range(n):
        v, w = LI()
        d_ = dp[(i+1)>>1][:]
        if i <= m:
            for j in range(w, maxL+1)[::-1]:
                d_[j] = max(d_[j], d_[j - w] + v)
        V.append(v)
        W.append(w)
        dp.append(d_)
    
    q = I()
    for i in range(q):
        v, L = LI()
        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]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    import sys
    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]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    import sys
    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 i in range(1, m+1):
        v, w = V[i-1], W[i-1]
        d = [None]*(maxL + 1)
        for j in range(maxL+1):
            if j < w:
                d[j] = dp[i>>1][j]
            else:
                d[j] = max(dp[i>>1][j], dp[i>>1][j - w] + v)
        dp.append(d)

    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]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    N = int(input())
    item = [tuple(map(int,input().split())) for _ in range(N)]
    
    K = 1<<13 - 1
    MAXV = 100003
    dp = np.zeros((K + 1,MAXV),np.int32)
    for i,(v,w) in enumerate(item[:K],1):
        dp[i,w:] = np.maximum(dp[i >> 1,w:],dp[i >> 1,:-w] + v)
        dp[i,:w] = dp[i >> 1,:w]
    
    Q = int(input())
    answer = []
    for _ in range(Q):
        V,L = map(int,input().split())
        lower_item = []
        while K < V:
            lower_item.append(item[V - 1])
            V >>= 1
        choice = [(0,0)]
        for v,w in lower_item:
            choice += [(v + a,w + b) for a,b in choice]
        
        ans = max(v + dp[V][L - w] for v,w in choice if L - w >= 0)
        answer.append(ans)
    print('\n'.join(map(str,answer)))
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

def main():
    import sys
    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]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] > L:
                continue
            v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
            ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline
from numba import jit

MAX = (1<<10)

@jit
def main():
    N = int(input())
    VW = [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    M = 0
    for _, L in Query:
        if L > M:
            M = L

    dp = [[0]*(M+1) for _ in range(MAX+1)]
    for k in range(min(MAX, N)):
        nv, nw = VW[k]
        k += 1
        for w in range(M+1):
            if w >= nw and dp[k][w] < dp[k//2][w-nw] + nv:
                dp[k][w] = dp[k//2][w-nw] + nv
            if dp[k][w] < dp[k//2][w]:
                dp[k][w] = dp[k//2][w]
        

    for s, L in Query:
        dp2 = []
        # make new dp
        while s >= MAX:
            dp2.append(VW[s-1])
            s = s//2
        
        T = len(dp2)
        ans = dp[s][L]
        dp3 = [(0, 0)]
        for nv, nw in dp2:
            ndp = []
            for v, w in dp3:
                if w + nw <= L:
                    ndp.append((v+nv, w+nw))
                    score = dp[s][L-(w+nw)] + v + nv
                    if score > ans:
                        ans = score
            dp3 += ndp
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

MAX = (1<<11)

def main():
    N = int(input())
    VW = [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    M = 0
    for _, L in Query:
        if L > M:
            M = L

    dp = [[0]*(M+1) for _ in range(MAX+1)]
    for k in range(min(MAX, N)):
        nv, nw = VW[k]
        k += 1
        for w in range(M+1):
            if w >= nw and dp[k][w] < dp[k//2][w-nw] + nv:
                dp[k][w] = dp[k//2][w-nw] + nv
            if dp[k][w] < dp[k//2][w]:
                dp[k][w] = dp[k//2][w]
        

    for s, L in Query:
        dp2 = []
        # make new dp
        while s >= MAX:
            dp2.append(VW[s-1])
            s = s//2
        
        T = len(dp2)
        ans = dp[s][L]
        dp3 = [(0, 0)]
        for nv, nw in dp2:
            ndp = []
            for v, w in dp3:
                if w + nw <= L:
                    ndp.append((v+nv, w+nw))
                    score = dp[s][L-(w+nw)] + v + nv
                    if score > ans:
                        ans = score
            dp3 += ndp
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    import sys
    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 i 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)
    
    ans = [None]*q
    for i in range(q):
        v, L = vl[i]
        if v <= m:
            ans[i] = 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]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        ans[i] = ret
    print('\n'.join(map(str,ans)))
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    N = int(input())
    item = [tuple(map(int,input().split())) for _ in range(N)]
    
    K = 1<<9 - 1
    MAXV = 100003
    dp = np.zeros((K + 1,MAXV),np.int32)
    for i,(v,w) in enumerate(item[:K],1):
        dp[i,w:] = np.maximum(dp[i >> 1,w:],dp[i >> 1,:-w] + v)
        dp[i,:w] = dp[i >> 1,:w]
    
    Q = int(input())
    for _ in range(Q):
        V,L = map(int,input().split())
        lower_item = []
        while K < V:
            lower_item.append(item[V - 1])
            V >>= 1
        choice = [(0,0)]
        for v,w in lower_item:
            choice += [(v + a,w + b) for a,b in choice]
        
        ans = max(v + dp[V][L - w] for v,w in choice if L - w >= 0)
        print(ans)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

MAX = (1<<10)

def main():
    N = int(input())
    VW = [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    M = 0
    for _, L in Query:
        if L > M:
            M = L

    dp = [[0]*(M+1) for _ in range(MAX+1)]
    for k in range(min(MAX, N)):
        nv, nw = VW[k]
        k += 1
        for w in range(M+1):
            if w >= nw and dp[k][w] < dp[k//2][w-nw] + nv:
                dp[k][w] = dp[k//2][w-nw] + nv
            if dp[k][w] < dp[k//2][w]:
                dp[k][w] = dp[k//2][w]
        

    for s, L in Query:
        dp2 = []
        # make new dp
        while s >= MAX:
            dp2.append(VW[s-1])
            s = s//2
        
        T = len(dp2)
        ans = dp[s][L]
        dp3 = [(0, 0)]
        for nv, nw in dp2:
            ndp = []
            for v, w in dp3:
                if w + nw <= L:
                    ndp.append((v+nv, w+nw))
                    score = dp[s][L-(w+nw)] + v + nv
                    if score > ans:
                        ans = score
            dp3 += ndp
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    import sys
    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)
    
    
    m = min(n, 1 << 10)
    dp = [[0]*(10**5 + 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(10**5 + 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)
    q = I()
    for i in range(q):
        v, L = LI()
        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]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

def main():
    N = int(input())
    item = [tuple(map(int,input().split())) for _ in range(N)]
    
    K = 1<<10 - 1
    MAXV = 100003
    dp = np.zeros((K + 1,MAXV),np.int32)
    for i,(v,w) in enumerate(item[:K],1):
        dp[i,w:] = np.maximum(dp[i >> 1,w:],dp[i >> 1,:-w] + v)
        dp[i,:w] = dp[i >> 1,:w]
    
    Q = int(input())
    for _ in range(Q):
        V,L = map(int,input().split())
        lower_item = []
        while V > 10:
            lower_item.append(item[V - 1])
            V >>= 1
        choice = [(0,0)]
        for v,w in lower_item:
            choice += [(v + a,w + b) for a,b in choice]
        
        ans = max(v + dp[V][L - w] for v,w in choice if L - w >= 0)
        print(ans)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

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

MAX = (1<<10)

def main():
    N = int(input())
    VW = [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    M = 0
    for _, L in Query:
        if L > M:
            M = L

    dp = [[0]*(M+1) for _ in range(MAX+1)]
    for k in range(min(MAX, N)):
        nv, nw = VW[k]
        k += 1
        for w in range(M+1):
            if w >= nw and dp[k][w] < dp[k//2][w-nw] + nv:
                dp[k][w] = dp[k//2][w-nw] + nv
            if dp[k][w] < dp[k//2][w]:
                dp[k][w] = dp[k//2][w]
        

    for s, L in Query:
        dp2 = []
        # make new dp
        while s >= MAX:
            dp2.append(VW[s-1])
            s = s//2
        
        # merge
        T = len(dp2)
        ans = 0
        for bit in range(1<<T):
            V = 0
            W = 0
            for i in range(T):
                if (1<<i)&bit:
                    V += dp2[i][0]
                    W += dp2[i][1]
            if W <= L:
                score = dp[s][L-W] + V
                if score > ans:
                    ans = score
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

#solve
def solve():

    input = sys.stdin.buffer.readline
    LI = lambda: map(int, input().split())
    II = lambda: int(input())
    n = II()
    vw = [[]] * n
    M = 10 ** 5 + 1
    M0 = [0] * M
    XX = 1 << 10
    d = [[]] * XX
    d[0] = M0

    for i in range(1, min(XX, n + 1)):
        v, w = LI()
        vw[i - 1] = (v, w)
        di = d[i // 2][:]
        for j in range(M - 1, w - 1, -1):
            if di[j] < di[j - w] + v:
                di[j] = di[j - w] + v
        d[i] = di

    for i in range(XX, n + 1):
        v, w = LI()
        vw[i - 1] = (v, w)

    Vv = [i.bit_length() for i in range(1 << 18)]
    n = [pow(2, i) for i in range(18)]
    lentl = [i - 10 for i in range(19)]
    maskset = [[]] * n[10]

    for i in range(1, 11):
        for mask in range(n[i - 1], n[i]):
            a = mask & -mask
            b = Vv[a] - 1
            maska = mask - a
            maskset[mask - 1] = (mask, b, maska)

    for _ in range(II()):
        V, L = LI()

        if V < XX:
            print(d[V][L])
            continue

        n2 = lentl[Vv[V]]
        vw2 = [None] * n2

        for i in range(n2):
            vw2[i] = (vw[V - 1][0], vw[V - 1][1])
            V //= 2

        lw = [0] * n[n2]
        lv = [0] * n[n2]
        dv = d[V]
        ans = dv[L]

        for i in range(n[n2] - 1):
            mask, b, maska = maskset[i]
            v, w = vw2[b]
            ww = lw[maska] + w
            Lww = L - ww
            lw[mask] = ww
            if Lww < 0: continue
            vv = lv[maska] + v
            lv[mask] = vv
            tmp = dv[Lww] + vv
            if tmp > ans:
                ans = tmp
        print(ans)
    return

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

#solve
def solve():

    input = sys.stdin.buffer.readline
    LI = lambda: map(int, input().split())
    II = lambda: int(input())
    n = II()
    vw = [[]] * n
    M = 10 ** 5 + 1
    M0 = [0] * M
    XX = 1 << 9
    d = [[]] * XX
    d[0] = M0

    for i in range(1, min(XX, n + 1)):
        v, w = LI()
        vw[i - 1] = (v, w)
        di = d[i // 2][:]
        for j in range(M - 1, w - 1, -1):
            if di[j] < di[j - w] + v:
                di[j] = di[j - w] + v
        d[i] = di

    for i in range(XX, n + 1):
        v, w = LI()
        vw[i - 1] = (v, w)

    Vv = [i.bit_length() for i in range(1 << 18)]
    n = [pow(2, i) for i in range(18)]
    lentl = [i - 9 for i in range(19)]
    maskset = [[]] * n[9]

    for i in range(1, 10):
        for mask in range(n[i - 1], n[i]):
            a = mask & -mask
            b = Vv[a] - 1
            maska = mask - a
            maskset[mask - 1] = (mask, b, maska)

    for _ in range(II()):
        V, L = LI()

        if V < XX:
            print(d[V][L])
            continue

        n2 = lentl[Vv[V]]
        vw2 = [None] * n2

        for i in range(n2):
            vw2[i] = (vw[V - 1][0], vw[V - 1][1])
            V //= 2

        lw = [0] * n[n2]
        lv = [0] * n[n2]
        dv = d[V]
        ans = dv[L]

        for i in range(n[n2] - 1):
            mask, b, maska = maskset[i]
            v, w = vw2[b]
            ww = lw[maska] + w
            Lww = L - ww
            lw[mask] = ww
            if Lww < 0: continue
            vv = lv[maska] + v
            lv[mask] = vv
            tmp = dv[Lww] + vv
            if tmp > ans:
                ans = tmp
        print(ans)
    return

if __name__ == "__main__":
    solve()

Submission status: Time Limit Exceeded

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

#solve
def solve():

    input = sys.stdin.buffer.readline
    LI = lambda: map(int, input().split())
    II = lambda: int(input())
    n = II()
    vw = [[]] * n
    M = 10 ** 5 + 1
    M0 = [0] * M
    XX = 1 << 9
    d = [[]] * XX
    d[0] = M0

    for i in range(1, min(XX, n + 1)):
        v, w = LI()
        vw[i - 1] = (v, w)
        di = d[i // 2][:]
        for j in range(M - 1, w - 1, -1):
            if di[j] < di[j - w] + v:
                di[j] = di[j - w] + v
        d[i] = di

    for i in range(XX, n + 1):
        v, w = LI()
        vw[i - 1] = (v, w)

    Vv = [i.bit_length() for i in range(n + 1)]
    n = [pow(2, i) for i in range(18)]
    lentl = [i - 9 for i in range(19)]
    maskset = [[]] * n[9]

    for i in range(1, 10):
        for mask in range(n[i - 1], n[i]):
            a = mask & -mask
            b = a.bit_length() - 1
            maska = mask - a
            maskset[mask - 1] = (mask, b, maska)

    for _ in range(II()):
        V, L = LI()

        if V < XX:
            print(d[V][L])
            continue

        n2 = lentl[Vv[V]]
        vw2 = [None] * n2

        for i in range(n2):
            vw2[i] = (vw[V - 1][0], vw[V - 1][1])
            V //= 2

        lw = [0] * n[n2]
        lv = [0] * n[n2]
        dv = d[V]
        ans = dv[L]

        for i in range(n[n2] - 1):
            mask, b, maska = maskset[i]
            v, w = vw2[b]
            ww = lw[maska] + w
            Lww = L - ww
            lw[mask] = ww
            if Lww < 0: continue
            vv = lv[maska] + v
            lv[mask] = vv
            tmp = dv[Lww] + vv
            if tmp > ans:
                ans = tmp
        print(ans)
    return

if __name__ == "__main__":
    solve()