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



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] = [(0,0), (W[0], V[0])]

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

def sub0(l, w, v):
    ll = list((ww+w, vv+v) for ww,vv in l)
    nl = [(0,0)]
    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.append(l[i1])
            i1 += 1
        elif i2<length:
            if ll[i2][1]>nl[-1][1]:
                nl.append(ll[i2])
            i2 += 1      
    return nl

# until = n
while q:
    u = q.pop()
    l = d[u]
    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)

from bisect import bisect_right as br
def sub(vv, L):
    if d[vv] is None:
        ll = [(0,0)]
        while d[vv] is None:
            ll = sub0(ll, W[vv], V[vv])
            vv = (vv-1)//2
#             ll.extend(list((wt+W[vv], vt+V[vv]) for wt,vt in ll))
        tmp = ll
    else:
        tmp = [(0,0)]
    l = d[vv]
    ans = -1
    
    for w1,v1 in tmp:
        if w1>L:
            continue
        out = br(l, (L-w1, float("inf")))
        ans = max(ans, l[out-1][1]+v1)
    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:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")



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] = [(0,0), (W[0], V[0])]

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

def sub0(l, w, v):
    ll = list((ww+w, vv+v) for ww,vv in l)
    nl = [(0,0)]
    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.append(l[i1])
            i1 += 1
        elif i2<length:
            if ll[i2][1]>nl[-1][1]:
                nl.append(ll[i2])
            i2 += 1      
    return nl

# until = n
while q:
    u = q.pop()
    l = d[u]
    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)

from bisect import bisect_right as br
def sub(vv, L):
    if d[vv] is None:
        ll = [(0,0)]
        while d[vv] is None:
            ll = sub0(ll, W[vv], V[vv])
            vv = (vv-1)//2
#             ll.extend(list((wt+W[vv], vt+V[vv]) for wt,vt in ll))
        tmp = ll
    else:
        tmp = [(0,0)]
    l = d[vv]
    ans = -1
    
    for w1,v1 in tmp:
        if w1>L:
            continue
        out = br(l, (L-w1, float("inf")))
        ans = max(ans, l[out-1][1]+v1)
    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:
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 = 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 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 = 9

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)

ans = []
for i, l in VL:
    if i < len(dp):
        ans.append(dp[i][l])
        continue

    dp1 = dp[i >> i.bit_length() - MAX_D - 1]
    dp2 = np.zeros(l + 1, dtype=int)
    p = i
    while p >= 1 << MAX_D + 1:
        v, w = VW[p]
        dp2[w:] = np.maximum(dp2[w:], dp2[:-w] + v)
        p >>= 1
    ans.append((dp1[:l + 1] + dp2[::-1]).max())

print(*ans, sep='\n')

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())
stdin = list(map(int,read().split()))
v = [0]+stdin[:2*n:2]
w = [0]+stdin[1:2*n:2]
q = stdin[2*n]
query = stdin[2*n+1:]
k = 0
num = 1
while num < n:
    k += 1
    num *= 2
prev = k//2
remain = k-k//2
dp = [[0]*(10**5+1)]
for i in range(1,2**prev+1):
    vi = v[i]
    wi = w[i]
    dp.append(dp[i//2][:])
    for j in range(wi,10**5+1):
        dp[i][j] = max(dp[i][j],dp[i//2][j-wi]+vi)
for i in range(q):
    vq,lq = query[i*2],query[i*2+1]
    if vq <= 2**prev:
        print(dp[vq][lq])
    else:
        ans = 0
        for j in range(2**remain):
            cur = vq
            curw = 0
            curv = 0
            while cur > 2**prev:
                if j & 1:
                    curv += v[cur]
                    curw += w[cur]
                cur //= 2
                j >>= 1
            if curw <= lq:
                ans = max(ans,curv+dp[cur][lq-curw])
        print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**9)

def main():
    n = int(ipt())
    data = [(0,0)]
    for _ in range(n):
        v,w = map(int,ipt().split())
        data.append((v,w))
    q = int(ipt())
    dp = [[0]*(10**5+1) for _ in range(n+1)]
    dp[0][10**5] = -1

    for i in range(1,min(512,n+1)):
        dpp = dp[i//2]
        vi,wi = data[i]
        dpn = dp[i]
        dpn[:wi:] = dpp[:wi:]
        for j,dpj in enumerate(dpp[wi::]):
            dpjm = dpp[j]
            if dpj < dpjm+vi:
                dpn[j+wi] = dpjm+vi
            else:
                dpn[j+wi] = dpj

    def solve(i):
        dpn = dp[i]
        dpp = dp[i//2]
        if dpn[10**5] != 0:
            return
        if dpp[10**5] == 0:
            solve(i//2)
        vi,wi = data[i]
        dpn[:wi:] = dpp[:wi:]
        for j,dpj in enumerate(dpp[wi::]):
            dpjm = dpp[j]
            if dpj < dpjm+vi:
                dpn[j+wi] = dpjm+vi
            else:
                dpn[j+wi] = dpj
        return

    for _ in [0]*q:
        v,l = map(int,ipt().split())
        solve(v)
        print(dp[v][l])

    return

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from sys import stdin
    input = stdin.readline

    n = int(input())
    vw = [list(map(int, input().split())) for _ in [0]*n]
    q = int(input())
    vl = [list(map(int, input().split())) for _ in [0]*q]

    former = min(512, n)
    former_dp = [[-1]*100001 for _ in [0]*former]
    former_set = [set() for _ in [0]*former]

    former_dp[0][0] = 0
    former_dp[0][vw[0][1]] = vw[0][0]
    former_set[0] = {0, vw[0][1]}

    for i in range(1, former):
        v, w = vw[i]
        anc_dp = former_dp[(i-1)//2]
        now_dp = former_dp[i]
        anc_set = former_set[(i-1)//2]
        now_set = former_set[i]
        for j in anc_set:
            now_dp[j] = anc_dp[j]
            now_set.add(j)
        for j in anc_set:
            if w+j <= 100000:
                now_dp[w+j] = max(now_dp[w+j], anc_dp[j]+v)
                now_set.add(w+j)

    for i in range(former):
        m = 0
        now_dp = former_dp[i]
        for j in range(1, 100001):
            m = max(m, now_dp[j])
            now_dp[j] = m

    for v, l in vl:
        if v <= former:
            print(former_dp[v-1][l])
            continue
        later = []
        vv = v
        while vv > former:
            later.append(vw[vv-1])
            vv >>= 1
        anc_dp = former_dp[vv-1]
        m = len(later)
        ans = 0
        for i in range(2**m):
            vv = v
            v_sum, w_sum = 0, 0
            for j, k in later:
                if i & 1:
                    v_sum += j
                    w_sum += k
                i >>= 1
            if w_sum > l:
                continue
            ans = max(ans, v_sum+anc_dp[l-w_sum])
        print(ans)


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 = n//2+1
    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
from collections import defaultdict
readline = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    N = gete(int)
    V = [0] * (N + 1)
    W = [0] * (N + 1)
    for i in range(1, N + 1):
        V[i], W[i] = geta(int)

    N1 = 2**9 - 1
    M = 10**5
    dp = [[0] * (M + 1) for _ in range(N1 + 1)]

    dp[1] = [0 if i < W[1] else V[1] for i in range(M + 1)]

    N2 = min(N1, N)
    for i in range(2, N2 + 1):
        ip = i >> 1
        v, w = V[i], W[i]
        for j in range(M + 1):
            dp[i][j] = dp[ip][j]
            if j >= w:
                dp2 = dp[ip][j - w] + v
                if dp[i][j] < dp2: dp[i][j] = dp2

    for _ in range(gete(int)):
        v, L = geta(int)

        if v <= N2:
            print(dp[v][L])
        else:
            ans = 0
            l = []
            cnt = 0
            v0 = v
            while v > N2:
                cnt += 1
                v >>= 1
            for bit in range(1 << cnt):
                v_tot = 0
                w_tot = 0
                tmp = bit
                v1 = v0
                while tmp > 0:
                    if tmp & 1 == 1:
                        v_tot += V[v1]
                        w_tot += W[v1]
                    v1 >>= 1
                    tmp >>= 1

                if w_tot > L:
                    continue
                else:
                    ans2 = v_tot + dp[v][L - w_tot]
                    if ans < ans2: ans = ans2

            print(ans)


if __name__ == "__main__":
    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

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

dp = [[0] * MAX_L]
for i in range(1, min(N, 1023) + 1):
    # 深さ9まで
    # vより親側を全部計算しとく
    ndp = list(dp[i >> 1])
    v, w = VW[i]
    for j in reversed(range(len(ndp) - w)):
        ndp[j + w] = max(ndp[j + w], ndp[j] + v)
    dp.append(ndp)


for i, l in VL:
    if i < len(dp):
        print(dp[i][l])
        continue

    dp1 = dp[i >> i.bit_length() - 10]
    dp2 = [0] * (l + 1)
    p = i
    while p >= 1024:
        v, w = VW[p]
        for j in reversed(range(len(dp2) - w)):
            dp2[j + w] = max(dp2[j + w], dp2[j] + v)
        p >>= 1

    ans = 0
    for j in range(l + 1):
        ans = max(ans, dp1[l - j] + dp2[j])
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    N = gete(int)
    V = [0] * (N + 1)
    W = [0] * (N + 1)
    for i in range(1, N + 1):
        V[i], W[i] = geta(int)

    N1 = 2**9 - 1
    M = 10**5
    dp = [[0] * (M + 1) for _ in range(N1 + 1)]

    dp[1] = [0 if i < W[1] else V[1] for i in range(M + 1)]

    N2 = min(N1, N)
    for i in range(2, N2 + 1):
        ip = i >> 1
        v, w = V[i], W[i]
        for j in range(M + 1):
            dp[i][j] = dp[ip][j]
            if j >= w:
                dp2 = dp[ip][j - w] + v
                if dp[i][j] < dp2: dp[i][j] = dp2

    for _ in range(gete(int)):
        v, L = geta(int)

        if v <= N2:
            print(dp[v][L])
        else:
            ans = 0
            l = []
            while v > N2:
                l.append(v)
                v >>= 1
            for bit in range(1 << len(l)):
                v_tot = 0
                w_tot = 0
                i = 0
                tmp = bit
                while tmp > 0:
                    if tmp & 1 == 1:
                        v_tot += V[l[i]]
                        w_tot += W[l[i]]
                    i += 1
                    tmp >>= 1

                if w_tot > L:
                    continue
                else:
                    ans2 = v_tot + dp[v][L - w_tot]
                    if ans < ans2: ans = ans2

            print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    N = gete(int)
    V = [0] * (N + 1)
    W = [0] * (N + 1)
    for i in range(1, N + 1):
        V[i], W[i] = geta(int)

    N1 = 2**9 - 1
    M = 10**5
    dp = [[0] * (M + 1) for _ in range(N1 + 1)]

    dp[1] = [0 if i < W[1] else V[1] for i in range(M + 1)]

    N2 = min(N1, N)
    for i in range(2, N2 + 1):
        ip = i // 2
        v, w = V[i], W[i]
        for j in range(M + 1):
            if j < w:
                dp[i][j] = dp[ip][j]
            else:
                dp[i][j] = max(dp[ip][j], dp[ip][j - w] + v)

    for _ in range(gete(int)):
        v, L = geta(int)

        if v <= N2:
            print(dp[v][L])
        else:
            ans = 0
            l = []
            while v > N2:
                l.append(v)
                v >>= 1
            for bit in range(1 << len(l)):
                v_tot = 0
                w_tot = 0
                i = 0
                tmp = bit
                while tmp > 0:
                    if tmp & 1 == 1:
                        v_tot += V[l[i]]
                        w_tot += W[l[i]]
                    i += 1
                    tmp >>= 1

                if w_tot > L:
                    continue

                if ans < v_tot + dp[v][L - w_tot]:
                    ans = v_tot + dp[v][L - w_tot]

            print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    N = gete(int)
    V = [0] * (N + 1)
    W = [0] * (N + 1)
    for i in range(1, N + 1):
        V[i], W[i] = geta(int)

    N1 = 2**9 - 1
    M = 10**5
    dp = [[0] * (M + 1) for _ in range(N1 + 1)]

    dp[1] = [0 if i < W[1] else V[1] for i in range(M + 1)]

    N2 = min(N1, N)
    for i in range(2, N2 + 1):
        ip = i // 2
        v, w = V[i], W[i]
        for j in range(M + 1):
            if j < w:
                dp[i][j] = dp[ip][j]
            else:
                dp[i][j] = max(dp[ip][j], dp[ip][j - w] + v)

    for _ in range(gete(int)):
        v, L = geta(int)

        if v <= N2:
            print(dp[v][L])
        else:
            ans = 0
            l = []
            while v > N2:
                l.append(v)
                v //= 2
            for bit in range(1 << len(l)):
                v_tot = 0
                w_tot = 0
                i = 0
                while bit > 0:
                    if bit & 1 == 1:
                        v_tot += V[l[i]]
                        w_tot += W[l[i]]
                    i += 1
                    bit = bit >> 1

                if w_tot > L:
                    continue

                if ans < v_tot + dp[v][L - w_tot]:
                    ans = v_tot + dp[v][L - w_tot]

            print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    M = 1 << 9
    N = int(input())
    V = []
    W = []
    for i in range(N):
        v,w = map(int,input().split())
        V.append(v)
        W.append(w)

    dp = [[0]*(10**5+1) for _ in range(min(M,N+1))]

    for n in range(1,min(M,N+1)):
        for l in range(10**5+1):
            c = 0
            if l>=W[n-1]:
                c = dp[n//2][l-W[n-1]]+V[n-1]
            dp[n][l] = max(dp[n//2][l],c)
    for n in range(min(M,N+1)):
        for l in range(1,10**5+1):
            dp[n][l] = max(dp[n][l],dp[n][l-1])


    Q = int(input())
    vL = [list(map(int,input().split())) for _ in range(Q)]

    for i in range(Q):
        n,l = vL[i]
        ans = 0
        if n < M:
            ans = dp[n][l]
        else:
            v = []
            while n >= M:
                v.append(n)
                n //= 2
            m = len(v)
            ans = dp[v[-1]//2][l]
            for n in range(1 << m):
                v_tot = 0
                w_tot = 0
                for k in range(m):
                    if n&1:
                        v_tot += V[v[k]-1]
                        w_tot += W[v[k]-1]
                    n >>= 1
                    if w_tot>l:
                        break
                if w_tot <= l:
                    ans = max(ans,v_tot+dp[v[-1]//2][l-w_tot])
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    M = 1 << 9
    N = int(input())
    V = []
    W = []
    for i in range(N):
        v,w = map(int,input().split())
        V.append(v)
        W.append(w)

    dp = [[0]*(10**5+1) for _ in range(min(M,N+1))]

    for n in range(1,min(M,N+1)):
        for l in range(10**5+1):
            c = 0
            if l>=W[n-1]:
                c = dp[n//2][l-W[n-1]]+V[n-1]
            dp[n][l] = max(dp[n//2][l],c)
    for n in range(min(M,N+1)):
        for l in range(1,10**5+1):
            dp[n][l] = max(dp[n][l],dp[n][l-1])

    def cal(n,l):
        if n < M:
            return dp[n][l]
        else:
            v = []
            while n >= M:
                v.append(n)
                n //= 2
            m = len(v)
            res = dp[v[-1]//2][l]
            for n in range(1 << m):
                v_tot = 0
                w_tot = 0
                for k in range(m):
                    if n&1:
                        v_tot += V[v[k]-1]
                        w_tot += W[v[k]-1]
                    n >>= 1
                    if w_tot>l:
                        break
                if w_tot <= l:
                    res = max(res,v_tot+dp[v[-1]//2][l-w_tot])
            return res

    Q = int(input())
    vL = [list(map(int,input().split())) for _ in range(Q)]

    for i in range(Q):
        v,L = vL[i]
        print(cal(v,L))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys; input = sys.stdin.buffer.readline
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")
import bisect

def getlist():
	return list(map(int, input().split()))

#処理内容
def main():
	N = int(input())
	NN = 2 ** N.bit_length() - 1
	WW = [0] * NN
	VV = [0] * NN

	for i in range(N):
		V, W = getlist()
		VV[i] = V
		WW[i] = W

	Q = int(input())
	for _ in range(Q):
		v, L = getlist(); v -= 1
		if v == 0:
			if WW[0] <= L:
				print(VV[0])
			else:
				print(0)
		
		else:
			node1 = []
			node2 = []
			WW1 = []
			WW2 = []
			M = (v + 1).bit_length()
			m = int(M // 2)
			for i in range(M - m):
				node1.append(v)
				v = int((v - 1) // 2)
			while True:
				node2.append(v)
				v = int((v - 1) // 2)
				if v < 0:
					break

			a = len(node1)
			b = len(node2)
			Lis1 = []
			Lis2 = []
			for i in range(1 << a):
				w = 0; v = 0
				for j in range(a):
					if ((i >> j) & 1) == 1:
						w += WW[node1[j]]
						v += VV[node1[j]]
				Lis1.append([w, v])

			for i in range(1 << b):
				w = 0; v = 0
				for j in range(b):
					if ((i >> j) & 1) == 1:
						w += WW[node2[j]]
						v += VV[node2[j]]
				Lis2.append([w, v])

			A = len(Lis1)
			B = len(Lis2)
			Lis1.sort()
			Lis2.sort()
			for i in range(A - 1):
				Lis1[i + 1][1] = max(Lis1[i + 1][1], Lis1[i][1])

			for i in range(B - 1):
				Lis2[i + 1][1] = max(Lis2[i + 1][1], Lis2[i][1])
			# print(Lis1)
			# print(Lis2)

			ans = 0
			x = 0; y = B - 1
			while x <= A - 1 and 0 <= y:
				w1, v1 = Lis1[x]
				w2, v2 = Lis2[y]
				if w1 + w2 <= L:
					ans = max(ans, v1 + v2)
					x += 1
				else:
					y -= 1

			print(ans)


if __name__ == '__main__':
	main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import defaultdict
readline = sys.stdin.buffer.readline
#sys.setrecursionlimit(10**8)


def geta(fn=lambda s: s.decode()):
    return map(fn, readline().split())


def gete(fn=lambda s: s.decode()):
    return fn(readline().rstrip())


def main():
    N = gete(int)
    V = [0] * (N + 1)
    W = [0] * (N + 1)
    for i in range(1, N + 1):
        V[i], W[i] = geta(int)

    N1 = 2**9 - 1
    M = 10**5
    dp = [[0] * (M + 1) for _ in range(N1 + 1)]

    dp[1] = [0 if i < W[1] else V[1] for i in range(M + 1)]

    N2 = min(N1, N)
    for i in range(2, N2 + 1):
        ip = i // 2
        v, w = V[i], W[i]
        for j in range(M + 1):
            if j < w:
                dp[i][j] = dp[ip][j]
            else:
                dp[i][j] = max(dp[ip][j], dp[ip][j - w] + v)

    for _ in range(gete(int)):
        v, L = geta(int)

        if v <= N2:
            print(dp[v][L])
        else:
            ans = 0
            vw = []
            while v > N2:
                vw.append((V[v], W[v]))
                v //= 2
            for bit in range(1 << len(vw)):
                i = 0
                v_tot = 0
                w_tot = 0
                while bit > 0:
                    if bit & 1 == 1:
                        v_tot += vw[i][0]
                        w_tot += vw[i][1]

                if w_tot > L:
                    continue

                if ans < v_tot + dp[v][L - w_tot]:
                    ans = v_tot + dp[v][L - w_tot]

            print(ans)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
INF = float("inf")


def main():
    # 事前にDPする。必ず上からDPする
    # すでに計算済みのところはスキップする
    # N*Lの配列を用意するとダメなので、
    # 辞書で対応したい。要素数は高々log(N)だと思う。
    # 頂点ごとに辞書を持つことになる。
    N = int(input())
    V = [-1]
    W = [-1]
    for i in range(N):
        a, b = map(int, input().split())
        V.append(a)
        W.append(b)

    Q = int(input())
    v = []
    L = []
    LMAX = 0
    for i in range(Q):
        a, b = map(int, input().split())
        v.append(a)
        L.append(b)
        LMAX = max(b, LMAX)

    DP = [None]*(N+1)

    for q in range(Q):
        order = []
        while v[q] > 0:
            order.append(v[q])
            v[q] >>= 1

        pre = None
        for u in reversed(order):
            if DP[u] is None:
                # 重さがkeyになるときの価値の総和value
                if pre is None:
                    DP[u] = {0: 0, W[u]: V[u]}
                else:
                    DP[u] = pre.copy()
                    for k in sorted(pre.keys(), reverse=True):
                        if k + W[u] > LMAX:
                            continue
                        DP[u][k+W[u]] = pre[k]+V[u]
                        if k+W[u] in pre:
                            DP[u][k+W[u]] = max(DP[u][k+W[u]], pre[k+W[u]])
            pre = DP[u]
        # key
        m = 0
        for k, val in DP[order[0]].items():
            if k <= L[q]:
                m = max(m, val)
        print(m)

    return


if __name__ == '__main__':
    main()