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: Runtime Error

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)]
    dpd = [-1]*(n+1)
    dpd[0] = 1

    for i in range(1,min(512,n+1)):
        dpd[i] = 1
        dpp = dp[i//2]
        dpn = [0]*(10**5+1)
        vi,wi = data[i]
        for j in range(10**5+1):
            if j < wi:
                dpn[j] = dpp[j]
            else:
                if dpp[j] < dpp[j-wi]+vi:
                    dpn[j] = dpp[j-wi]+vi
                else:
                    dpn[j] = dpp[j]
        dp[i] = dpn

    def solve(i):
        if dpd[i//2] == -1:
            dp[i//2] = solve(i//2)
            dpd[i//2] = 1
        dpp = dp[i//2]
        dpn = [0]*(10**5+1)
        vi,wi = data[i]
        for j in range(10**5+1):
            if j < wi:
                dpn[j] = dpp[j]
            else:
                if dpp[j] < dpp[j-wi]+vi:
                    dpn[j] = dpp[j-wi]+vi
                else:
                    dpn[j] = dpp[j]
        return dpn

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

    return

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from  math import floor,log

def I(u,L):
    T=0
    for i in range(len(L)):
        T+=(u%2)*L[i]
        u=u>>1
    return T
        
N=int(input())
M=10**5

V=["*"]
W=["*"]
K=floor((log(N,2)+1)/2)
S=2**K-1
D=[[0]*(M+1) for _ in range(S+1)]

for i in range(N):
    v,w=map(int,input().split())
    V.append(v)
    W.append(w)

for k in range(1,S+1):
    for w in range(M+1):
        if w>=W[k]:
            D[k][w]=max(D[k>>1][w],D[k>>1][w-W[k]]+V[k])
        else:
            D[k][w]=D[k>>1][w]
            
Q=int(input())
for _ in range(Q):
    v,L=map(int,input().split())
    if v<=S:
        print(D[v][L])
        continue

    u=v
    P=[]

    A=[]
    B=[]
    while u>S:
        P.append(u)
        A.append(V[u])
        B.append(W[u])
        u=u>>1
        
    T=0
    for i in range(2**len(P)):
        Y=I(i,B)
        T=max(T,D[u][L-Y]+I(i,A))

    print(T)

Submission status: Runtime Error

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: Runtime Error

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

A = 256

def main(N, V, W, v, L):
    def precompute(N, V, W):
        U = 10**5 + 10
        dp = np.zeros((A, U), np.int32)
        for v in range(1, min(A, N + 1)):
            p = v // 2
            dp[v] = dp[p]
            dp[v, W[v]:] = np.maximum(dp[v, W[v]:], dp[p, :-W[v]] + V[v])
            for i in range(1, U):
                dp[v][i] = max(dp[v][i], dp[v][i - 1])
        return dp

    dp = precompute(N, V, W)
    values = np.empty(A, np.int32)
    weights = np.empty(A, np.int32)

    def solve(i, lim, values, weights, dp):
        if i < A:
            return dp[i][lim]
        values[0] = 0
        weights[0] = 0
        p = 0
        while i >= A:
            for j in range(1 << p):
                values[j + (1 << p)] = values[j] + V[i]
                weights[j + (1 << p)] = weights[j] + W[i]
            p += 1
            i >>= 1
        best = 0
        for n in range(1 << p):
            if weights[n] > lim:
                continue
            x = dp[i][lim - weights[n]] + values[n]
            best = max(best, x)
        return best

    Q = len(v)
    for i in range(Q):
        x = solve(v[i], L[i], values, weights, dp)
        print(x)

        
if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i4,i4[:],i4[:],i4[:],i4[:])')(main)
    cc.compile()
    exit()

from my_module import main

N = int(readline())
stdin = np.array(read().split(), np.int32)
V = np.zeros(N + 1, np.int32)
W = np.zeros(N + 1, np.int32)
V[1:] = stdin[:N + N:2]
W[1:] = stdin[1:N + N:2]
query = stdin[N + N + 1:]
v, L = query[::2].copy(), query[1::2].copy()

main(N, V, W, v, L)

Submission status: Runtime Error

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: Runtime Error

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines


def main(N, V, W, v, L):
    def precompute(N, V, W):
        U = 10**5 + 10
        dp = np.zeros((1024, U), np.int32)
        for v in range(1, min(1024, N + 1)):
            p = v // 2
            dp[v] = dp[p]
            dp[v, W[v]:] = np.maximum(dp[v, W[v]:], dp[p, :-W[v]] + V[v])
            for i in range(1, U):
                dp[v][i] = max(dp[v][i], dp[v][i - 1])
        return dp

    dp = precompute(N, V, W)
    values = np.empty(1024, np.int32)
    weights = np.empty(1024, np.int32)

    def solve(i, lim, values, weights, dp):
        if i < 1024:
            return dp[i][lim]
        values[0] = 0
        weights[0] = 0
        p = 0
        while i >= 1024:
            for j in range(1 << p):
                values[j + (1 << p)] = values[j] + V[i]
                weights[j + (1 << p)] = weights[j] + W[i]
            p += 1
            i >>= 1
        best = 0
        for n in range(1 << p):
            if weights[n] > lim:
                continue
            x = dp[i][lim - weights[n]] + values[n]
            best = max(best, x)
        return best

    Q = len(v)
    for i in range(Q):
        x = solve(v[i], L[i], values, weights, dp)
        print(x)

        
if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', '(i4,i4[::1],i4[::1],i4[::1],i4[::1])')(main)
    cc.compile()
    exit()

from my_module import main

N = int(readline())
stdin = np.array(read().split(), np.int32)
V = np.zeros(N + 1, np.int32)
W = np.zeros(N + 1, np.int32)
V[1:] = stdin[:N + N:2]
W[1:] = stdin[1:N + N:2]
query = stdin[N + N + 1:]
v, L = query[::2], query[1::2]

main(N, V, W, v, L)

Submission status: Runtime Error

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] for _ in range(n2)]
    tab[0] = [0] * ma
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        aa, bb = vw[i]
        a = tab[j]
        b = tab[i]
        tab[i] = a[:bb] + [0] * (ma - bb)
        for k in range(bb, ma):
            b[k] = max((b[k - 1], a[k - bb] + aa, a[k]))

    # q = int(input())
    # for _ in range(q):
    #     u, l = map(int, input().split())
    #     u -= 1
    #     if u < n2:
    #         print(tab[u][l])
    #     else:
    #         a = [(0, 0)]
    #         while u >= n2:
    #             for i in a[:]:
    #                 if i[0] + vw[u][1] <= l:
    #                     a.append((i[0] + vw[u][1], i[1] + vw[u][0]))
    #             u = (u - 1) // 2
    #         ans = 0
    #         b = tab[u]
    #         for i, j in a:
    #             ans = max(ans, b[l - i] + j)
    #         print(ans)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

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

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 = np.zeros((n+1,10**5+1),dtype=int)

#dpを先に計算してしまう
    for i in range(1,min(1024,n+1)):
        vi,wi = data[i]
        dp[i][:wi:]=dp[i//2][:wi:]
        dp[i][wi::]=np.maximum(dp[i//2][:10**5+1-wi:]+vi,dp[i//2][wi::])

    def calc(i):
        if dp[i//2][10**5] == 0:
            calc(i//2)
        vi,wi = data[i]
        dp[i][:wi:]=dp[i//2][:wi:]
        dp[i][wi::]=np.maximum(dp[i//2][:10**5+1-wi:]+vi,dp[i//2][wi::])
        return dp[i]

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

    return

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
# coding: utf-8
#import numpy as np
import re
import math
from collections import defaultdict
from collections import deque
import collections
from fractions import Fraction
import bisect
from queue import PriorityQueue
import itertools
from copy import deepcopy
import random
import time
import os
import sys
import datetime
from functools import lru_cache
from functools import reduce
readline=sys.stdin.readline
sys.setrecursionlimit(2000000)
alphabet="abcdefghijklmnopqrstuvwxyz"
numbers="0123456789"
mod=int(10**9+7)
inf=int(10**19)
class Edge():
    def __init__(self,x,y,val=1):
        self.x=x
        self.y=y
        self.val=val
class unionfind():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(n)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):
            self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def yn(b):
    if b:print("yes")
    else:print("no")
def Yn(b):
    if b:print("Yes")
    else:print("No")
def YN(b):
    if b:print("YES")
    else:print("NO")
def ispow(a,b):
    now=b
    while now<a:
        now*=b
    return now==a
def getbin(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def getfacs(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod_>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def nextcomb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:return num
def getprimes(n):
    if n==0:return []
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    ret=[]
    for a in range(n+1):
        if(A[a]):ret.append(a)
    return ret
def isprime(num):
    if(num<=1):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True
def ifelse(bbool,ret1,ret2):
    if bbool:return ret1
    else:return  ret2
def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
def factorize(n):
    b = 2
    ret=defaultdict(int)
    while b * b <= n:
        while n % b == 0:
            n //= b
            ret[b]+=1
        b+=1
    if n > 1:ret[n]+=1
    return ret
def pm(x):
    return x//abs(x)
def inputintlist(): 
    return list(map(int,input().split()))
def inputfloatlist(): 
    return list(map(float,input().split()))
def tozero(A):
    ret=[None]*len(A)
    for a in range(len(A)):
        ret[a]=A[a]-1
    return ret
def istanchouzouka(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>=a:
            f=False
        prev=a
    return f
def istanchouhigensyou(A):
    f=True
    prev=min(A)-1
    for a in A:
        if prev>a:
            f=False
        prev=a
    return f
def getallsum(A):
    s=sum(A)
    dp=defaultdict(int)
    dp[0]=1
    for a in range(0,len(A)):
        for b in range(s,-1,-1):
            if b-A[a]>=0:
                dp[b]+=dp[b-A[a]]
    return dp
def yuukoutomukou(edges):
    ret=deepcopy(edges)
    for edge in edges:
        if not edge.x==edge.y:
            ret.append(Edge(edge.y,edge.x,edge.val))
    return ret
def dijkstra(edges,V,start):
    mincost=[inf]*V
    G=[[] for a in range(V)]
    for edge in edges:
        G[edge.x].append([edge.val,edge.y])
    Q=PriorityQueue()
    Q.put([0,start])#[cost,x]
    while not Q.empty():
        nowcost,nowx=Q.get()
        if mincost[nowx]==inf:
            mincost[nowx]=nowcost
            for cost,y in G[nowx]:
                newcost=nowcost+cost
                Q.put([newcost,y])
    return mincost
def warshallfloyd(edges,V):
    mincost=[[inf for b in range(V)] for a in range(V)]
    for a in range(V):mincost[a][a]=0
    for edge in edges:
        mincost[edge.x][edge.y]=min(mincost[edge.x][edge.y],edge.val)#x→yが複数ある場合のためにmin()する
    for k in range(V):
        for s in range(V):
            for t in range(V):
                if mincost[s][k]==inf or mincost[k][t]==inf:continue
                mincost[s][t]=min(mincost[s][t],mincost[s][k]+mincost[k][t])
    return mincost
def bellemanford(edges,V,start):
    mincost=[inf]*V
    mincost[start]=0
    for _ in range(V):
        for edge in edges:
            if mincost[edge.x]==inf:continue
            mincost[edge.y]=min(mincost[edge.y],mincost[edge.x]+edge.val)
    return mincost
def ruisekiwa(A):
    ret=[0]*(len(A)+1)
    for a in range(len(A)):
        ret[a+1]=ret[a]+A[a]
    return ret
def getmd(x1,y1,x2,y2):
    return abs(x1-x2)+abs(y1-y2)
def geted(x1,y1,x2,y2):
    return math.sqrt((x1-x2)**2+(y1-y2)**2)
class fordfulkerson():
    def __init__(self,edges,V,s,t):
        self.V=V
        self.used=[False]*V
        self.G=[[] for a in range(V)]
        self.s=s
        self.t=t
        for edge in edges:
            self.G[edge.x].append({"x":edge.x,"y":edge.y,"cap":edge.val,"rev":len(self.G[edge.y])})
            self.G[edge.y].append({"x":edge.y,"y":edge.x,"cap":0,"rev":len(self.G[edge.x])-1})
    def dfs(self,v,t,f=inf):
        if v==t:return f
        self.used[v]=True
        for a in range(len(self.G[v])):
            x=self.G[v][a]["x"]
            y=self.G[v][a]["y"]
            cap=self.G[v][a]["cap"]
            rev=self.G[y][self.G[x][a]["rev"]]
            if self.used[y] or cap==0:continue
            f2=self.dfs(y,t,min(f,cap))
            if f2>0:
                self.G[v][a]["cap"]-=f2
                rev["cap"]+=f2
                return f2
        return 0
    def maxflow(self):
        flow=0
        while True:
            self.used=[False]*V
            zouka=self.dfs(self.s,self.t)
            if zouka==0:break
            flow+=zouka
        return flow
def heron(a,b,c):
    s=(a+b+c)/2
    S=s(s-a)(s-b)(a-c)
    S=math.sqrt(S)
    return S
def getAreaOfTriangle(x1,y1,x2,y2,x3,y3):
    a=geted(x1,y1,x2,y2)
    b=geted(x2,y2,x3,y3)
    c=geted(x3,y3,x1,y1)
    return heron(a,b,c)






######################################################################################################



N,K=inputintlist()
A=inputintlist()
for k in range(min(50,K)):
    imos=[0]*(N+1)
    for a in range(len(A)):
        mmin=max(a-A[a],0)
        mmax=min(a+A[a],N-1)
        imos[mmin]+=1
        imos[mmax+1]-=1
    B=[0]*N
    B[0]=imos[0]
    for a in range(1,N):
        B[a]=imos[a]+B[a-1]
    A=B[:]
print(join(A))

Submission status: Runtime Error

Solution code:
from numba import njit

@jit
def main(M,N,Q,V,W,v,L):
    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])

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

M = 2**9
N = int(input())
V = []
W = []
for i in range(N):
    v,w = map(int,input().split())
    V.append(v)
    W.append(w)
Q = int(input())
v = []
L = []
for i in range(Q):
    vL = list(map(int,input().split()))
    v.append(vL[0])
    L.append(vL[1])
main(M,N,Q,V,W,v,L)

Submission status: Runtime Error

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

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)]
    dpd = [-1]*(n+1)
    dpd[0] = 1

#dpを先に計算してしまう
    for i in range(1,n+1):
        dpn = dp[i]
        dpp = dp[i//2]
        vi,wi = data[i]
        for j,dpj in enumerate(dpp):
            if j < wi:
                dpn[j] = dpj
            else:
                dpw = dpp[j-wi]
                if dpj < dpw+vi:
                    dpn[j] = dpw+vi
                else:
                    dpn[j] = dpj
        return

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

    return

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
from numba import njit

@njit('(i4,i4[:],i4[:])', cache=True)
def main():
    M = 2**10
    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(2**m):
                v_tot = 0
                w_tot = 0
                for k in range(m):
                    if 2**k&n==2**k:
                        v_tot += V[v[k]-1]
                        w_tot += W[v[k]-1]
                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: Runtime Error

Solution code:
up = lambda x: x//2
n = int(input())
itm = []
for _ in range(n):
   v,w = [int(i) for i in input().split()]
   itm.append((v,w))
dplen = min(n,2**8)
dp = [ [0]*(10**5+2) for i in range(dplen+1)]
for i in range(1,dplen+1):
   for j in range(10**5+2):
      dp[i][j] = max(dp[up(i)][j], dp[i][max(0,j-1)])
      if (j >= itm[i-1][1]):
         dp[i][j] = max(dp[i][j], dp[up(i)][j-itm[i-1][1]] + itm[i-1][0])
q = int(input())
#print(dp[3][:10])
for i in range(q):
   vrt, l = [int(i) for i in input().split()]
   if vrt <= 2**8:
      print(dp[vrt][l])
      continue
   koho = []
   y = int(vrt)
   for i in range(10):
      if y <= 2**8:
        break
      koho.append(y)
      y = up(y)
   bn = len(koho)
   mb = 2**bn
   ans = 0
   for j in range(mb):
      curv,curw = 0,0
      for k in range(bn):
         if (j >> k) & 1 :
            curv += itm[koho[k]-1][0]
            curw += itm[koho[k]-1][1]
      if curw <= l:
         curv += dp[vrt][l-curw]
         ans = max(curv)
   print(ans)

Submission status: Runtime Error

Solution code:
import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
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
	WWlist = [[] for i in range(NN)]
	X = [None] * NN
	for i in range(N):
		V, W = getlist()
		X[i] = [W, V]

	#前半までbit全探索
	WWlist[0].append([0, 0])
	WWlist[0].append(X[0])
	dep = min(2 ** (N.bit_length() - 1) - 1, 2047)
	# dep = 7
	for i in range(dep):
		u1 = 2 * i + 1
		u2 = 2 * i + 2
		for w, v in WWlist[i]:
			WWlist[u1].append([w, v])
			WWlist[u1].append([w + X[u1][0] , v + X[u1][1]])
			WWlist[u2].append([w, v])
			WWlist[u2].append([w + X[u2][0] , v + X[u2][1]])
		WWlist[u1].sort()
		WWlist[u2].sort()

	#価値を単調増加させる
	for i in range(dep * 2 + 1):
		for j in range(len(WWlist[i]) - 1):
			WWlist[i][j + 1][1] = max(WWlist[i][j + 1][1], WWlist[i][j][1])

	# print(WWlist)

	Q = int(input())
	for i in range(Q):
		v, L = getlist()
		v -= 1
		if v <= dep * 2 + 1:
			ind = bisect.bisect_left(WWlist[v], [L + 1, -INF]) - 1
			ans = WWlist[v][ind][1]
			print(ans)
		else:
			node = []
			while True:
				node.append(v)
				v = int((v - 1) // 2)
				if v <= dep * 2 + 1:
					x = v
					break

			M = len(node)
			WWW = []
			for p in range(1 << M):
				bitlist = []
				w = 0; v = 0
				for q in range(M):
					if ((p >> q) & 1) == 1:
						w += X[node[q]][0]
						v += X[node[q]][1]
			WWW.append([w, v])
			ans = 0
			for wd, vd in WWW:
				ind = bisect.bisect_left(WWlist[x], [L - wd + 1, -INF]) - 1
				ans = max(ans, vd + WWlist[x][ind][1])
			print(ans)



if __name__ == '__main__':
	main()

Submission status: Runtime Error

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

#n,k,*a = map(int,read().split())

n, = map(int,readline().split())
vw = [[0,0]]+[list(map(int,readline().split())) for _ in range(n)]

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

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

from itertools import accumulate

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


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

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

Submission status: Runtime Error

Solution code:
import sys
import numpy as np

n = int(input())
tree = []
for i in range(n):
  tree.append(list(map(int, input().split())))

query = int(input())
prob = []
for q in range(query):
  prob.append(list(map(int, input().split())))

#print(prob)
for p in prob:
  v = p[0]
  l = p[1]
  #print("---------")
  #print(v,l)

  li = [v]
  while True:
    v = int(v/2)
    if v == 0:
      break
    li.append(v)

  nap = []
  for lii in li:
    nap.append(tree[lii-1])

  #print(nap)
  dp = np.zeros((len(nap),l),dtype=int)
  for i,ns in enumerate(nap):
    #print(dp)
    if i == 0:
      dp[0][:ns[1]-1] = 0
      dp[0][ns[1]-1:] = ns[0]
    else:
      dp[i][:ns[1]-1] = dp[i-1][:ns[1]-1]
      a = np.insert(dp[i-1][:l-ns[1]],0,0)
      dp[i][ns[1]-1:] = np.maximum(a+ns[0],dp[i-1][ns[1]-1:])

  #print(dp)
  print(dp[len(nap)-1][l-1])