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 numpy as np
import bisect
N=int(input())

I=[]
for i in range(N):
    v,w=map(int, input().split())
    I.append((v,w))


        


Q=int(input())
for i in range(Q):
    v,l=map(int, input().split())
    L=[v-1]
    while v>1:
      v=v//2
      L.append(v-1)
    L=L[::-1]
    length=len(L)
    if length==1:
        if I[0][1]<=l:
            print(I[0][0])
        else:
            print(0)
        continue
    part1=L[:length//2]
    part2=L[length//2:]
    #print(part1, part2)
    result_1=[]
    for b in range(2**(len(part1))):
        ws=0
        vs=0
        for i in range(len(part1)):
            if b>>i&1==1:
                v,w=I[part1[i]]
                ws+=w
                vs+=v
        result_1.append([ws,vs])

    result_2=[]
    for b in range(2**(len(part2))):
        ws=0
        vs=0
        for i in range(len(part2)):
            if b>>i&1==1:
                v,w=I[part2[i]]
                ws+=w
                vs+=v
        result_2.append([ws,vs])
    result_2=np.array(sorted(result_2))
    #print(result_1,result_2)
    ans=0
    for t in result_1:
        w,v=t
        if w>l:
            continue
        #重さ
        limit=bisect.bisect_right(result_2[:,0], l-w)
        #print(result_2[:,0], l-w,limit)
        if limit>0:
            X=result_2[:limit,1].max()
        else:
            X=0
        #print(X)
        ans=max(ans, v+X)

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

    n = int(input())

    L_MAX = 10**5
    D_TH = 10
    V_MAX = 1 << D_TH
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]
    items = []

    for i in range(n):
        val, w = map(int, input().split())
        items.append((val, w))
        if i < V_MAX:
            i1 = i + 1
            i0 = (i + 1) // 2
            for j in range(L_MAX + 1):
                if j < w:
                    dp[i1][j] = dp[i0][j]
                else:
                    dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v < V_MAX:
            ans = dp[v + 1][l]
        else:
            items_sub = [items[v]]
            while v >= V_MAX:
                v = (v - 1) // 2
                items_sub.append(items[v])

            ans = 0
            for bit in range(1 << len(items_sub)):
                s_val = s_w = 0
                for i, (val, w) in enumerate(items_sub):
                    if (bit >> i) & 1:
                        s_val += val
                        s_w += w
                        if s_w > l:
                            break
                if s_w <= l:
                    ans = max(ans, dp[v + 1][l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

    n = int(input())

    L_MAX = 10**5
    D_TH = 9
    V_MAX = 1 << D_TH
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]
    items = []

    for i in range(n):
        val, w = map(int, input().split())
        items.append((val, w))
        if i < V_MAX:
            for j in range(L_MAX + 1):
                i1 = i + 1
                i0 = (i + 1) // 2
                if j < w:
                    dp[i1][j] = dp[i0][j]
                else:
                    dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v < V_MAX:
            ans = dp[v + 1][l]
        else:
            items_sub = [items[v]]
            while v >= V_MAX:
                v = (v - 1) // 2
                items_sub.append(items[v])

            ans = 0
            for bit in range(1 << len(items_sub)):
                s_val = s_w = 0
                for i, (val, w) in enumerate(items_sub):
                    if (bit >> i) & 1:
                        s_val += val
                        s_w += w
                        if s_w > l:
                            break
                if s_w <= l:
                    ans = max(ans, dp[v + 1][l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

n = int(readline())
data = list(map(int,read().split()))

V = tuple(data[:2*n:2])
W = tuple(data[1:2*n:2])
q = data[2*n]
v = tuple(data[2*n+1::2])
L = tuple(data[2*n+2::2])

if(n==1):
    ans = []
    for i,j in zip(v,L):
        if(W[i-1] <= j):
            ans.append(V[0])
        else:
            ans.append(0)
    print('\n'.join(map(str,ans)))
    exit()

# 前処理　最大2**9まで前計算
b_len = min(9, n.bit_length()-1)
max_bef = 2**b_len
bef = [ [0]*(10**5 + 1) for _ in range(max_bef)]

for i in range(1,max_bef):
    iw,iv = W[i-1],V[i-1]
    par = i//2
    for j in range(1,10**5+1):
        if(j>=iw):
            bef[i][j] = max(bef[par][j] , bef[par][j-iw]+iv)
        else:
            bef[i][j] = bef[par][j]

ans = []
for vi,Li in zip(v,L):
    if(vi==1):
        if(W[0] <= Li):
            ans.append(V[0])
        else:
            ans.append(0)
        continue

    par = vi
    while(par>= max_bef):
        par //= 2

    aft = [(0,0)]
    x = vi
    max_ans = bef[par][Li]
    while(x >= max_bef):
        xw,xv = W[x-1],V[x-1]
        aft2 = []
        for jw,jv in aft:
            jw += xw
            jv += xv
            lim_w = Li - jw
            if(lim_w < 0):
                continue
            aft2.append((jw,jv))
            max_ans = max(max_ans, bef[par][lim_w]+jv)
        x //= 2
        aft = aft + aft2

    ans.append(max_ans)

print('\n'.join(map(str,ans)))

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

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

    L_MAX = 10**5
    D_TH = 9
    V_MAX = 1 << D_TH
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]

    for i, (val, w) in enumerate(items[:V_MAX]):
        for j in range(L_MAX + 1):
            i1 = i + 1
            i0 = (i + 1) // 2
            if j < w:
                dp[i1][j] = dp[i0][j]
            else:
                dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v < V_MAX:
            ans = dp[v + 1][l]
        else:
            items_sub = [items[v]]
            while v >= V_MAX:
                v = (v - 1) // 2
                items_sub.append(items[v])

            ans = 0
            for bit in range(1 << len(items_sub)):
                s_val = s_w = 0
                for i, (val, w) in enumerate(items_sub):
                    if (bit >> i) & 1:
                        s_val += val
                        s_w += w
                        if s_w > l:
                            break
                if s_w <= l:
                    ans = max(ans, dp[v + 1][l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

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

    L_MAX = 10**5
    D_TH = 8
    V_MAX = 1 << D_TH
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]

    for i, (val, w) in enumerate(items[:V_MAX]):
        for j in range(L_MAX + 1):
            i1 = i + 1
            i0 = (i + 1) // 2
            if j < w:
                dp[i1][j] = dp[i0][j]
            else:
                dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v < V_MAX:
            ans = dp[v + 1][l]
        else:
            items_sub = [items[v]]
            while v >= V_MAX:
                v = (v - 1) // 2
                items_sub.append(items[v])

            ans = 0
            for bit in range(1 << len(items_sub)):
                s_val = s_w = 0
                for i, (val, w) in enumerate(items_sub):
                    if (bit >> i) & 1:
                        s_val += val
                        s_w += w
                if s_w <= l:
                    ans = max(ans, dp[v + 1][l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

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

    L_MAX = 10**5
    D_TH = 11
    V_MAX = 1 << D_TH
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]

    for i, (val, w) in enumerate(items[:V_MAX]):
        for j in range(L_MAX + 1):
            i1 = i + 1
            i0 = (i + 1) // 2
            if j < w:
                dp[i1][j] = dp[i0][j]
            else:
                dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v + 1 <= V_MAX:
            ans = dp[v + 1][l]
        else:
            items_sub = [items[v]]
            while v > V_MAX:
                v = (v - 1) // 2
                items_sub.append(items[v])

            ans = 0
            for bit in range(1 << len(items_sub)):
                s_val = s_w = 0
                for i, (val, w) in enumerate(items_sub):
                    if (bit >> i) & 1:
                        s_val += val
                        s_w += w
                if s_w <= l:
                    ans = max(ans, dp[V_MAX][l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

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

    L_MAX = 10**5
    D_TH = 9
    V_MAX = 1 << D_TH
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]

    for i, (val, w) in enumerate(items[:V_MAX]):
        for j in range(L_MAX + 1):
            i1 = i + 1
            i0 = (i + 1) // 2
            if j < w:
                dp[i1][j] = dp[i0][j]
            else:
                dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v + 1 <= V_MAX:
            ans = dp[v + 1][l]
        else:
            items_sub = [items[v]]
            while v > V_MAX:
                v = (v - 1) // 2
                items_sub.append(items[v])

            ans = 0
            for bit in range(1 << len(items_sub)):
                s_val = s_w = 0
                for i, (val, w) in enumerate(items_sub):
                    if (bit >> i) & 1:
                        s_val += val
                        s_w += w
                if s_w <= l:
                    ans = max(ans, dp[V_MAX][l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main(): 
  import sys
  read = sys.stdin.buffer.read
  readline = sys.stdin.buffer.readline
  readlines = sys.stdin.buffer.readlines
  from bisect import bisect

  n = int(readline())
  g = []
  for i in range(n):
    v,W = map(int,readline().split())
    g.append((v,W))

  q = int(readline())
  for i in range(q):
    V,w = map(int,readline().split())
    c = []
    ans = 0
    while V > 0:
      c.append(g[V-1])
      V //= 2
    d = []
    e = []
    h = 2*n//3
    H = n-h
    for i in range(2**h):
      cw = 0
      cv = 0
      for j,cj in enumerate(c[:h]):
        if (i>>j)&1 == 1:
          cw += cj[1]
          cv += cj[0]
      d.append((cv,cw))

    for i in range(2**H):
      cw = 0
      cv = 0
      for j,cj in enumerate(c[h:]):
        if (i>>j)&1 == 1:
          cw += cj[1]
          cv += cj[0]
      e.append((cv,cw))

    from operator import itemgetter
    e = sorted(e,key=itemgetter(1))

    Ev = [0]
    Ew = [0]
    ch = 0
    for i in range(1,len(e)):
      ev,ew = e[i]
      if ev > ch:
        Ev.append(ev)
        Ew.append(ew)
        ch = ev

    for i in d:
      Cv,Cw = i
      if Cw > w:
        continue
      ind = bisect(Ew,w-Cw)
      cc = Cv+Ev[ind-1]
      ans = max(cc,ans)

    print(ans)
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

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

    L_MAX = 10**5
    D_TH = 10
    V_MAX = 1 << D_TH
    dp = [[0] * (L_MAX + 1) for _ in range(V_MAX + 1)]

    for i, (val, w) in enumerate(items[:V_MAX]):
        for j in range(L_MAX + 1):
            i1 = i + 1
            i0 = (i + 1) // 2
            if j < w:
                dp[i1][j] = dp[i0][j]
            else:
                dp[i1][j] = max(dp[i0][j], dp[i0][j - w] + val)

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1

        if v + 1 <= V_MAX:
            ans = dp[v + 1][l]
        else:
            items_sub = [items[v]]
            while v > V_MAX:
                v = (v - 1) // 2
                items_sub.append(items[v])

            ans = 0
            for bit in range(1 << len(items_sub)):
                s_val = s_w = 0
                for i, (val, w) in enumerate(items_sub):
                    if (bit >> i) & 1:
                        s_val += val
                        s_w += w
                if s_w <= l:
                    ans = max(ans, dp[V_MAX][l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():  
  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 = 0
  import math
  from collections import deque
  for q in range(Q):
    x = vL[q][1]
    if x>M:
      M = x

  D = int(math.log2(N)) + 1
  K = D * 3//5
  Ddp = [[0] * (M+1) for _ in range(2**K)]
  for i in range(1,2**K):
    V,W = VW[i-1]
    for j in range(M+1):
      if W<=j:
        Ddp[i][j] = max(Ddp[i//2][j-W] + V, Ddp[i//2][j])
      else:
        Ddp[i][j] = Ddp[i//2][j]


  for q in range(Q):
    v,L = vL[q]
    if v<=2**K - 1:
      print(Ddp[v][L])
      continue
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      for i in range(x - K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      for i in range(2**length):
        z = [0,0]
        for j in range(length):
          if i>>j&1:
            vw = l[j]
            z[0] += vw[0]
            z[1] += vw[1]

          if z[1]>L:
            break
        if z[1]>L:
          continue
        else:
          ans = max(ans, Ddp[y][L-z[1]] + z[0])

    print(ans)
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():  
  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 = 0
  import math
  from collections import deque
  for q in range(Q):
    x = vL[q][1]
    if x>M:
      M = x

  D = int(math.log2(N)) + 1
  K = D//2
  Ddp = [[0] * (M+1) for _ in range(2**K)]
  for i in range(1,2**K):
    V,W = VW[i-1]
    for j in range(M+1):
      if W<=j:
        Ddp[i][j] = max(Ddp[i//2][j-W] + V, Ddp[i//2][j])
      else:
        Ddp[i][j] = Ddp[i//2][j]


  for q in range(Q):
    v,L = vL[q]
    if v<=2**K - 1:
      print(Ddp[v][L])
      continue
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      for i in range(x - K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      for i in range(2**length):
        z = [0,0]
        for j in range(length):
          if i>>j&1:
            vw = l[j]
            z[0] += vw[0]
            z[1] += vw[1]

          if z[1]>L:
            break
        if z[1]>L:
          continue
        else:
          ans = max(ans, Ddp[y][L-z[1]] + z[0])

    print(ans)
    
main()

Submission status: Time Limit Exceeded

Solution code:
def main():  
  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 = 0
  import math
  from collections import deque
  for q in range(Q):
    x = vL[q][1]
    if x>M:
      M = x

  D = int(math.log2(N)) + 1
  K = D//2
  Ddp = [[0] * (M+1) for _ in range(2**K)]
  for i in range(1,2**K):
    V,W = VW[i-1]
    for j in range(M+1):
      if W<=j:
        Ddp[i][j] = max(Ddp[i//2][j-W] + V, Ddp[i//2][j])
      else:
        Ddp[i][j] = Ddp[i//2][j]


  for q in range(Q):
    v,L = vL[q]
    if v<=2**K - 1:
      print(Ddp[v][L])
      continue
    else:
      y = v
      l = deque([])
      x = int(math.log2(v)) + 1
      for i in range(x - K):
        vw = VW[y-1]
        if vw[1]<=L:
          l.append(vw)
        y //= 2
      ans = 0
      length = len(l)
      for i in range(2**length):
        z = [0,0]
        p = [0,float('inf')]
        for j in range(length):
          if i>>j&1:
            vw = l[j]
            z[0] += vw[0]
            z[1] += vw[1]

          if (z[1]>L)or((z[0]<p[0])&(z[1]>p[1])):
            break
        if (z[1]>L)or((z[0]<p[0])&(z[1]>p[1])):
          continue
        else:
          if (z[0]>p[0])&(z[1]<p[1]):
            p[0] = z[0]
            p[1] = z[1]
          ans = max(ans, Ddp[y][L-z[1]] + z[0])

    print(ans)
    
main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

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

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1
        items_sub = [items[v]]
        while v > 0:
            v = (v - 1) // 2
            items_sub.append(items[v])

        m = len(items_sub)
        dp = [0] * (l + 1)
        for bit in range(1 << (m // 2)):
            s_val = s_w = 0
            for i, (val, w) in enumerate(items_sub[:m // 2]):
                if (bit >> i) & 1:
                    s_val += val
                    s_w += w
                    if s_w > l:
                        break
            if s_w <= l and dp[s_w] < s_val:
                dp[s_w] = s_val
        for i in range(l):
            if dp[i + 1] < dp[i]:
                dp[i + 1] = dp[i]

        ans = 0
        for bit in range(1 << (m - m // 2)):
            s_val = s_w = 0
            for i, (val, w) in enumerate(items_sub[m // 2:]):
                if (bit >> i) & 1:
                    s_val += val
                    s_w += w
                    if s_w > l:
                        break
            if s_w <= l:
                ans = max(ans, dp[l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys


def main():
    input = sys.stdin.readline

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

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1
        items_sub = [items[v]]
        while v > 0:
            v = (v - 1) // 2
            items_sub.append(items[v])

        m = len(items_sub)
        dp = [0] * (l + 1)
        for bit in range(1 << (m // 2)):
            s_val = s_w = 0
            for i, (val, w) in enumerate(items_sub[:m // 2]):
                if (bit >> i) & 1:
                    s_val += val
                    s_w += w
                    if s_w > l:
                        break
            if s_w <= l:
                dp[s_w] = max(dp[s_w], s_val)
        for i in range(l):
            dp[i + 1] = max(dp[i + 1], dp[i])

        ans = 0
        for bit in range(1 << (m - m // 2)):
            s_val = s_w = 0
            for i, (val, w) in enumerate(items_sub[m // 2:]):
                if (bit >> i) & 1:
                    s_val += val
                    s_w += w
                    if s_w > l:
                        break
            if s_w <= l:
                ans = max(ans, dp[l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict


def main():
    input = sys.stdin.readline

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

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1
        items_sub = [items[v]]
        while v > 0:
            v = (v - 1) // 2
            items_sub.append(items[v])

        m = len(items_sub)
        dp = [0] * (l + 1)
        for bit in range(1 << (m // 2)):
            s_val = s_w = 0
            for i, (val, w) in enumerate(items_sub[:m // 2]):
                if (bit >> i) & 1:
                    s_val += val
                    s_w += w
            if s_w <= l:
                dp[s_w] = max(dp[s_w], s_val)
        for i in range(l):
            dp[i + 1] = max(dp[i + 1], dp[i])

        ans = 0
        for bit in range(1 << (m - m // 2)):
            s_val = s_w = 0
            for i, (val, w) in enumerate(items_sub[m // 2:]):
                if (bit >> i) & 1:
                    s_val += val
                    s_w += w
            if s_w <= l:
                ans = max(ans, dp[l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict


def main():
    input = sys.stdin.readline

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

    q = int(input())
    for _ in range(q):
        v, l = map(int, input().split())
        v -= 1
        items_sub = [v]
        while v > 0:
            v = (v - 1) // 2
            items_sub.append(v)

        m = len(items_sub)
        dp = [0] * (l + 1)
        for bit in range(1 << (m // 2)):
            s_val = s_w = 0
            for i in range(m // 2):
                if (bit >> i) & 1:
                    s_val += items[items_sub[i]][0]
                    s_w += items[items_sub[i]][1]
            if s_w <= l:
                dp[s_w] = max(dp[s_w], s_val)
        for i in range(l):
            dp[i + 1] = max(dp[i + 1], dp[i])

        ans = 0
        for bit in range(1 << (m - m // 2)):
            s_val = s_w = 0
            for i in range(m - m // 2):
                if (bit >> i) & 1:
                    s_val += items[items_sub[m // 2 + i]][0]
                    s_w += items[items_sub[m // 2 + i]][1]
            if s_w <= l:
                ans = max(ans, dp[l - s_w] + s_val)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():  
  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 = 0
  import math
  for q in range(Q):
    x = vL[q][1]
    if x>M:
      M = x

  D = int(math.log2(N)) + 1
  K = D//3 * 2
  Ddp = [[0] * (M+1) for _ in range(2**K)]
  for i in range(1,2**K):
    V,W = VW[i-1]
    for j in range(M+1):
      if W<=j:
        Ddp[i][j] = max(Ddp[i//2][j-W] + V, Ddp[i//2][j])
      else:
        Ddp[i][j] = Ddp[i//2][j]


  for q in range(Q):
    v,L = vL[q]
    if v<=2**K - 1:
      print(Ddp[v][L])
      continue
    else:
      ans = 0
      x = int(math.log2(v)) + 1
      for i in range(2**(x - K)):
        y = v
        z = [0,0]
        for j in range(x - K):
          if i>>j&1:
            vw = VW[y-1]
            z[0] += vw[0]
            z[1] += vw[1]

          y //= 2
          if z[1]>L:
            break
        if z[1]>L:
          continue
        else:
          ans = max(ans, Ddp[y][L-z[1]] + z[0])

    print(ans)
    
main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
import cmath
import heapq
import itertools
import math
import operator
import os
import random
import re
import string
import sys
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from functools import lru_cache, reduce
from math import gcd
from operator import add, itemgetter, mul, xor
import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


# 先に親側のを全部計算しとく式
N = int(sys.stdin.buffer.readline())
VW = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
Q = int(sys.stdin.buffer.readline())
VL = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]

VW = [(0, 0)] + VW

MAX_L = 10 ** 5 + 10
MAX_D = 10

dp = [None] * (1 << MAX_D + 1)
dp[0] = np.zeros(MAX_L, dtype=int)
for i in range(1, min(N + 1, 1 << MAX_D + 1)):
    # 深さ9まで
    # vより親側を全部計算しとく
    v, w = VW[i]
    dp[i] = dp[i >> 1].copy()
    dp[i][w:] = np.maximum(dp[i][w:], dp[i][:-w] + v)

choices = np.array(list(itertools.product([0, 1], repeat=max(1, N.bit_length() - MAX_D - 1))))
k = 0
ans = []
for i, l in VL:
    k += 1
    if i < len(dp):
        ans.append(dp[i][l])
        continue

    dp1 = dp[i >> i.bit_length() - MAX_D - 1]
    weights = []
    values = []
    ps = []
    p = i
    while p >= (1 << MAX_D + 1):
        v, w = VW[p]
        weights.append(w)
        values.append(v)
        ps.append(p)
        p >>= 1
    weights = np.array(weights, dtype=int)
    values = np.array(values, dtype=int)
    V = choices[:1 << len(values), -len(values):] @ values
    W = choices[:1 << len(values), -len(values):] @ weights
    V = V[W <= l]
    W = W[W <= l]
    if len(V) > 0:
        opt = (dp1[l - W] + V).max()
    else:
        opt = 0
    ans.append(opt)
print(*ans, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
def main():  
  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 = 0
  import math
  for q in range(Q):
    x = vL[q][1]
    if x>M:
      M = x

  D = int(math.log2(N)) + 1
  K = D//2
  if D>=8:
    K+=2
  Ddp = [[0] * (M+1) for _ in range(2**K)]
  for i in range(1,2**K):
    V,W = VW[i-1]
    for j in range(M+1):
      if W<=j:
        Ddp[i][j] = max(Ddp[i//2][j-W] + V, Ddp[i//2][j])
      else:
        Ddp[i][j] = Ddp[i//2][j]


  for q in range(Q):
    v,L = vL[q]
    if v<=2**K - 1:
      print(Ddp[v][L])
      continue
    else:
      ans = 0
      x = int(math.log2(v)) + 1
      for i in range(2**(x - K)):
        y = v
        z = [0,0]
        for j in range(x - K):
          if i>>j&1:
            vw = VW[y-1]
            z[0] += vw[0]
            z[1] += vw[1]

          y //= 2
          if z[1]>L:
            break
        if z[1]>L:
          continue
        else:
          ans = max(ans, Ddp[y][L-z[1]] + z[0])

    print(ans)
    
main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
import cmath
import heapq
import itertools
import math
import operator
import os
import random
import re
import string
import sys
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from functools import lru_cache, reduce
from math import gcd
from operator import add, itemgetter, mul, xor
import numpy as np

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


# 先に親側のを全部計算しとく式
N = int(sys.stdin.buffer.readline())
VW = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
Q = int(sys.stdin.buffer.readline())
VL = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]

VW = [(0, 0)] + VW

MAX_L = 10 ** 5 + 10
MAX_D = 8

dp = [None] * (1 << MAX_D + 1)
dp[0] = np.zeros(MAX_L, dtype=int)
for i in range(1, min(N + 1, 1 << MAX_D + 1)):
    # 深さ9まで
    # vより親側を全部計算しとく
    v, w = VW[i]
    dp[i] = dp[i >> 1].copy()
    dp[i][w:] = np.maximum(dp[i][w:], dp[i][:-w] + v)

choices = np.array(list(itertools.product([0, 1], repeat=max(1, N.bit_length() - MAX_D - 1))))
k = 0
ans = []
for i, l in VL:
    k += 1
    if i < len(dp):
        ans.append(dp[i][l])
        continue

    dp1 = dp[i >> i.bit_length() - MAX_D - 1]
    weights = []
    values = []
    ps = []
    p = i
    while p >= (1 << MAX_D + 1):
        v, w = VW[p]
        weights.append(w)
        values.append(v)
        ps.append(p)
        p >>= 1
    weights = np.array(weights, dtype=int)
    values = np.array(values, dtype=int)
    V = choices[:1 << len(values), -len(values):] @ values
    W = choices[:1 << len(values), -len(values):] @ weights
    V = V[W <= l]
    W = W[W <= l]
    if len(V) > 0:
        opt = (dp1[l - W] + V).max()
    else:
        opt = 0
    ans.append(opt)
print(*ans, sep='\n')