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:
n = int(input())
from collections import defaultdict
vw = defaultdict(lambda: None)

class Node():
    def __init__(self, index, wei, val):
        self.index = index
        self.wei = wei
        self.val = val
        global vw
        vw[index] = self
        self.dp = defaultdict(int)
        if self.index < 128:
            self.calc()

    def __repr__(self):
        return f'Node({self.index}, {self.wei}, {self.val})'

    @property
    def parent(self):
        if self.index != 1:
            global vw
            return vw[self.index//2]
        else:
            return None

    def calc(self):
        dp = self.dp
        if self.parent is not None:
            anc = self.parent
            while 1:
                adp = anc.dp
                for w, v in list(adp.items()):
                    if v > 0:
                        if self.wei+w in adp:
                            dp[self.wei+w] = max(self.val+v, adp[self.wei+w])
                        else:
                            dp[self.wei+w] = self.val+v
                if anc.parent is not None:
                    anc = anc.parent
                else:
                    break
            dp[self.wei] = self.val
        else:
            dp[self.wei] = self.val

    def search(self, lw):
        ans = 0
        cur = self
        while 1:
            for w, v in cur.dp.items():
                if w <= lw:
                    ans = max(ans, v)
            if cur.index > 1:
                cur = cur.parent
            else:
                break
        return ans

for i in range(1, n+1):
    v, w = map(int, input().split())
    Node(i, w, v)

from collections import deque

def search_list(x):
    sl = deque()
    while x > 127:
        sl.appendleft(x)
        x //= 2
    return sl

q = int(input())

for _ in range(q):
    v, l = map(int, input().split())
    sl = search_list(v)
    for tmpv in sl:
        vw[tmpv].calc()
    print(vw[v].search(l))

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)

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:
import sys


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

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

    q = int(input())
    v_to_il = [[] for _ in range(n)]
    flag = [False] * n
    for i in range(q):
        v, l = map(int, input().split())
        v -= 1
        v_to_il[v].append((i, l))
        flag[v] = True
        while v > 0:
            v = (v - 1) // 2
            if flag[v]:
                break
            flag[v] = True

    MAX = 10**5
    # dp[i+1][j] = (i番目まで見て重さの合計がj以下のの時の価値の最大値)
    dp = [[0] * (MAX + 1) for _ in range(19)]
    ans = [0] * q

    d_th = 9
    queue = [(0, 0, [])]
    while queue:
        v, depth, items_sub = queue.pop()
        val, w = items[v]

        if depth < d_th:
            for j in range(MAX + 1):
                if j < w:
                    dp[depth + 1][j] = dp[depth][j]
                else:
                    dp[depth + 1][j] = max(dp[depth][j],
                                           dp[depth][j - w] + val)
        else:
            items_sub.append(v)

        if len(v_to_il[v]) > 0:
            if depth < d_th:
                for i, l in v_to_il[v]:
                    ans[i] = dp[depth + 1][l]
            else:
                cand = 0
                m = len(items_sub)
                for bit in range(1 << m):
                    s_val = s_w = 0
                    for i, v in enumerate(items_sub):
                        if (bit >> i) & 1:
                            s_val += items[v][0]
                            s_w += items[v][1]
                    for i, l in v_to_il[v]:
                        if s_w <= l:
                            ans[i] = max(ans[i], dp[d_th][l - s_w] + s_val)

        if v * 2 + 1 < n and flag[v * 2 + 1]:
            queue.append((v * 2 + 1, depth + 1, items_sub))
        if v * 2 + 2 < n and flag[v * 2 + 2]:
            queue.append((v * 2 + 2, depth + 1, items_sub))

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


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())
    v_to_il = [[] for _ in range(n)]
    flag = [False] * n
    for i in range(q):
        v, l = map(int, input().split())
        v -= 1
        v_to_il[v].append((i, l))
        flag[v] = True
        while v > 0:
            v = (v - 1) // 2
            if flag[v]:
                break
            flag[v] = True

    MAX = 10**5
    # dp[i+1][j] = (i番目まで見て重さの合計がj以下のの時の価値の最大値)
    dp = [[0] * (MAX + 1) for _ in range(19)]
    ans = [0] * q

    d_th = 11
    queue = [(0, 0, [])]
    while queue:
        v, depth, items_sub = queue.pop()
        val, w = items[v]

        if depth < d_th:
            for j in range(MAX + 1):
                if j < w:
                    dp[depth + 1][j] = dp[depth][j]
                else:
                    dp[depth + 1][j] = max(dp[depth][j],
                                           dp[depth][j - w] + val)
        else:
            items_sub.append(v)

        if len(v_to_il[v]) > 0:
            if depth < d_th:
                for i, l in v_to_il[v]:
                    ans[i] = dp[depth + 1][l]
            else:
                cand = 0
                m = len(items_sub)
                for bit in range(1 << m):
                    s_val = s_w = 0
                    for i, v in enumerate(items_sub):
                        if (bit >> i) & 1:
                            s_val += items[v][0]
                            s_w += items[v][1]
                    for i, l in v_to_il[v]:
                        if s_w <= l:
                            ans[i] = max(ans[i], dp[d_th][l - s_w] + s_val)

        if v * 2 + 1 < n and flag[v * 2 + 1]:
            queue.append((v * 2 + 1, depth + 1, items_sub))
        if v * 2 + 2 < n and flag[v * 2 + 2]:
            queue.append((v * 2 + 2, depth + 1, items_sub))

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


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!python3

import sys
iim = lambda: map(int, sys.stdin.readline().rstrip().split())
from collections import defaultdict

def resolve():
    it = map(int, sys.stdin.read().split())
    N = next(it)
    V = [(next(it), next(it)) for i in range(N)]
    Q = next(it)

    N1 = N+1
    rhs = 10**5

    D = [None] * N1
    D[0] = defaultdict(int)
    for i in range(1, N+1):
        d0 = D[i//2]
        d1 = D[i] = d0.copy()

        v1, w1 = V[i-1]
        for w2, v2 in d0.items():
            ww = w1 + w2
            if ww > rhs:
                continue
            d1[ww] = max(d1[ww], v1+v2)
        d1[w1] = max(d1[w1], v1)


    for i, li in zip(it, it):
        ans = 0
        for wi, vi in D[i].items():
            if wi > li:
                continue
            ans = max(ans, vi)
        print(ans)


if __name__ == "__main__":
    resolve()

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:
          continue
        else:
          ans = max(ans, Ddp[y][L-z[1]] + z[0])

    print(ans)
    
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(1024, 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):
            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():
    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):
            v_sum, w_sum = 0, 0
            for j, k in later:
                pass
                # 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():  
  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
  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:
          continue
        else:
          ans = max(ans, Ddp[y][L-z[1]] + z[0])

    print(ans)
    
main()

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**12-1)

def sub0(l, w, v):
    ll = tuple((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
        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():
    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:
#!/usr/bin/env python3

import sys, math, bisect
sys.setrecursionlimit(300000)


def solve(N: int, V: "List[int]", W: "List[int]", Q: int, VV: "List[int]", LL: "List[int]"):
    MAX_L = max(LL)
    d = int(math.log(N, 2)) + 1
    #print(d)
    hd = d // 2
    max_m = 2 ** (d // 2) - 1
    dp = [{} for _ in range(max_m + 1)]
    dp[0] = {0: 0}
    for i in range(max_m):
        v, w = V[i], W[i]
        idx = i + 1
        par = idx // 2
        for ww, vv in dp[par].items():
            dp[idx][ww] = dp[par][ww]
        for ww, vv in dp[par].items():
            if ww + w in dp[idx]:
                dp[idx][ww + w] = max(dp[idx][ww + w], dp[par][ww] + v)
            else:
                dp[idx][ww + w] = dp[par][ww] + v
    items = []
    for i in range(max_m + 1):
        max_v = 0
        tmp = [0] * (MAX_L + 1)
        for j in range(MAX_L + 1):
            if j in dp[i]:
                max_v = max(max_v, dp[i][j])
            tmp[j] = max_v
        items.append(tmp)

    #print(dp)
    #print(items)

    for q in range(Q):
        ret = 0
        idx, l = VV[q], LL[q]
        pre = {0: 0}
        while idx > max_m:
            w, v = W[idx - 1], V[idx - 1]
            cur = {ww: vv for ww, vv in pre.items()}
            for ww, vv in pre.items():
                if ww + w in cur:
                    cur[ww + w] = max(cur[ww + w], cur[ww] + v)
                else:
                    cur[ww + w] = cur[ww] + v
            pre = cur
            idx //= 2
        #print(pre, items[idx], l)
        for ww, vv in pre.items():
            if l < ww:
                continue
            max_l = l - ww
            vvv = items[idx][max_l]
            ret = max(ret, vv + vvv)

            ##x = bisect.bisect_right(items[idx], (max_l, float('inf')))
            ##if x < 1:
            ##    vvv = 0
            ##else:
            ##    vvv = items[idx][x - 1][1]
            ##ret = max(ret, vv + vvv)
            ###print(ww, vv, max_l, x, vvv, ret)
        print(ret)
        #print(' ************* ')
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    V = [int()] * (N)  # type: "List[int]"
    W = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        V[i] = int(next(tokens))
        W[i] = int(next(tokens))
    Q = int(next(tokens))  # type: int
    v = [int()] * (Q)  # type: "List[int]"
    L = [int()] * (Q)  # type: "List[int]"
    for i in range(Q):
        v[i] = int(next(tokens))
        L[i] = int(next(tokens))
    solve(N, V, W, Q, v, L)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
VW = [list(map(int,input().split())) for _ in range(N)]
Q = int(input())
vL = [list(map(int,input().split())) for _ in range(Q)]
M = 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
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:
        continue
      else:
        ans = max(ans, Ddp[y][L-z[1]] + z[0])
    
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
M = 10**5
VW = [(0, 0)] + [tuple(map(int, input().split())) for i in range(N)]

dp = [[0] * (M+1) for i in range(512)]
for i in range(1, 512):
  if i > N:
    break
  v, w = VW[i]
  par = i//2
  for wi in range(M+1):
    if wi < w:
      dp[i][wi] = dp[par][wi]
    else:
      dp[i][wi] = max(dp[par][wi], dp[par][wi-w]+v)

def enum(node):
  res = []
  while node > 511:
    res.append(node)
    node //= 2
  return res, node

def calc(node, L):
  nodes, node = enum(node)
  n = len(nodes)
  res = 0
  total_v = total_w = 0
  for i in range(2**n):
    for j in range(n):
      if i>>j & 1:
        vj, wj = VW[nodes[j]]
        total_v += vj; total_w += wj
    if total_w <= L:
      res = max(res, dp[node][L-total_w]+total_v)
  return res

Q = int(input())
ans = []
for q in range(Q):
  node, L = map(int, input().split())
  if node <= 511:
    ans.append(dp[node][L])
  else:
    ans.append(calc(node, L))

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

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

N = int(input())
M = 10**5
VW = [(0, 0)] + [tuple(map(int, input().split())) for i in range(N)]

dp = np.zeros([512, M+1], dtype=int)
for i in range(1, 512):
  if i > N:
    break
  v, w = VW[i]
  par = i//2
  dp[i, :w] = dp[par, :w].copy()
  dp[i, w:] = np.maximum(dp[par, w:], dp[par, :-w]+v)

def enum(node):
  res = []
  while node > 511:
    res.append(node)
    node //= 2
  return res, node

def calc(node, L):
  nodes, node = enum(node)
  n = len(nodes)
  res = 0
  total_v = total_w = 0
  for i in range(2**n):
    for j in range(n):
      if i>>j & 1:
        vj, wj = VW[nodes[j]]
        total_v += vj; total_w += wj
    if total_w <= L:
      res = max(res, dp[node, L-total_w]+total_v)
  return res

Q = int(input())
ans = []
for q in range(Q):
  node, L = map(int, input().split())
  if node <= 511:
    ans.append(dp[node, L])
  else:
    ans.append(calc(node, L))

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

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**11-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**13-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**12-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)))