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 sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
 
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=1):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        #self.st=SegTree(self.size*2-1,self.ETdepth,function=min,ide=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in edge]) for edge in self.edges]):
            print( [[nd for nd,d in edge] for edge in self.edges] )
        else:
            print(self)
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    # return boundary index of r such that func({table[i]} =< x , i in [pos,r]
    def right_bound(self,pos,x):
        k=(self.size-pos).bit_length()
        for j in range(k)[::-1]:
            nx=pos+(1<<j)
            if nx<n and self.query(pos,nx+1)<=x:
                pos+=(1<<j)
        return pos
    
    # return boundary index of l such that func({table[i]} =< x , i in [l,pos]
    def left_bound(self,pos,x):
        k=pos.bit_length()
        for j in range(k)[::-1]:
            nx=pos-(1<<j)
            if 0<=nx and self.query(nx,pos+1)<=x:
                pos-=(1<<j)
        return pos
 
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)
 
show_flg=False
show_flg=True
ans=0



n=I()
d=n//2
d=n-1
D=1<<d
Vs=[0]*(n+1)
Ws=[0]*(n+1)

pre=[set()for i in rep(D)]

for i in rep(1,n+1):
    a,b=LI()
    Vs[i]=a
    Ws[i]=b

'''
pre[1]=[v[1]*10**9+w[1]]
for i in rep(2,D):
    p=i>>1
    for j in pre[p]:
        pre[i].add(j)
        pre[i].add(j+v[i]*10**9+w[i])

for i in rep(1,D):
    pre[i]=sorted(pre[i],key=lambda x:x%10**9)
'''

def pre(W):
    A= [[(0,0)] for i in range(D)]
    for i in range(1,D):
        p=i>>1
        A[i] = [(w+Ws[i],v+Vs[i]) for w,v in A[p]]+A[p]
    A[i].sort(key = lambda x: (x[0],-x[1]))
    tmp = -1
    tmpList = []
    for w,v in A[i]:
        if w <= W and v > tmp:
            tmpList.append((w,v))
            tmp = v
    A[i] = tmpList[:]
    return A

A=pre(10)


def solver(t,W):
    B= [(0,0)]
    if t>=D:
        for i in range(D+1,n+1):
            B += [(w+Ws[i],v+Vs[i]) for w,v in B]
        B.sort(key = lambda x: (x[0],-x[1]))
        tmp = -1
        tmpList = []
        for w,v in B:
            if w <= W and v > tmp:
                tmpList.append((w,v))
                tmp = v
        B = tmpList[:]

    wA,vA = zip(*A[min(t,D-1)])
    ans = 0
    for wb,vb in B:
        idx = bisect.bisect_right(wA,W-wb)
        ans = max(ans, vA[idx-1]+vb)
    print(ans)

q=I()
for i in rep(q):
    x,l=LI()
    solver(x,l)


print(ans)

Submission status: Runtime Error

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

import numpy as np
N = int(input())
VW = [list(mapint()) for _ in range(N)]
Q = int(input())
VL = [list(mapint()) for _ in range(Q)]

def dfs(i, cnt):
    v, w = VW[i-1]
    dp[cnt][w:] = np.maximum(dp[cnt][w:], dp[cnt][:-w]+v)
    if i*2>N:
        return
    for j in range(2):
        dfs(i*2+j, cnt+1)

dp = [np.array([0]*(10**5+1)) for _ in range(N.bit_length())]
dfs(1, 0)
for q in range(Q):
    v, l = VL[q]
    print(dp[v.bit_length()-1][l])

Submission status: Runtime Error

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 = data[:2*n:2]
W = data[1:2*n:2]
q = data[2*n]
v = data[2*n+1::2]
L = 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**10まで前計算
b_len = min(10, n.bit_length()-1)

bef = [ [] for _ in range(2**b_len)]
bef[1] = [(0,0),(W[0],V[0])]

for i in range(2,2**b_len):
    iw,iv = W[i-1],V[i-1]
    bef[i] = bef[i//2][::]
    for jw,jv in bef[i//2]:
        bef[i].append((iw+jw,iv+jv))

for i in range(1,2**b_len):
    bef[i].sort()

#
# print(bef)
# print(len(bef))
# print(b_len,2**b_len)

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

    aft = [(0,0)]
    x = vi
    while(x >= 2**b_len):
        xw,xv = W[x-1],V[x-1]
        aft2 = aft[::]
        for jw,jv in aft:
            aft2.append((xw+jw,xv+jv))
        x //= 2
        aft = aft2[::]

    aft.sort(reverse=True)

    max_ans = 0
    max_bef_v = 0
    i_bef = 0
    for aw,av in aft:
        lim_w = Li - aw
        if(lim_w < 0):
            continue

        while(i_bef < len(bef)):
            if(bef[x][i_bef][0] > lim_w):
                break
            max_bef_v = max(max_bef_v,bef[x][i_bef][1])
            i_bef += 1
        max_ans = max(max_ans, av + max_bef_v)

    ans.append(max_ans)

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

Submission status: Runtime Error

Solution code:
import math
N = int(input())
X = [[] for _ in range(N)]
for i in range(N):
    X[i] = list(map(int, input().split()))
Q = int(input())
for i in range(Q):
    x, W = map(int, input().split())
    size = int(math.log2(x)+1)
    # i = size -1
    i = 0
    dp = [[0]*(W+1) for _ in range(size+1)]
    while x != 0:
        v, w = X[x-1]
        # for j in range(W+1):
        for j in range(W, -1, -1):
            # if j < w:
            if j - w >= 0:
                # dp[i][j] = dp[i+1][j]
                dp[j] = dp[j-w]+v
            # else:
            #     dp[i][j] = max(dp[i+1][j],dp[i+1][j-w]+v)
        # i -= 1
        x = x//2
    # print(dp[0][W])
    print(dp[W])

Submission status: Runtime Error

Solution code:
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())
for _ in range(q):
  v,l=map(int,input().split())
  s=v
  p=[]
  z=0
  while s>=1:
    p.append(s)
    z+=1
    s=s//2
  weights＝[V[s] for s in p]
  values=[V[s] for s in p]


  dp={0:0}
  for i in range(z):
    w=weights[i]
    val=values[i]
    dplist=list(dp.keys())
    for c in dplist:
      p=c+w
      v=dp[c]+val
      if  p in dp and dp[p]>v:
        continue
      elif p<=l:
        dp[p]=v

  x=max(dp.values())
  print(x)

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())))
ans = []

#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]
      dp[i][ns[1]-1:] = np.maximum(dp[i-1][:l+1-ns[1]]+ns[0],dp[i-1][ns[1]-1:])

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

Submission status: Runtime Error

Solution code:
import sys,bisect,string,math,time,functools,random,fractions
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
rep=range
def Golf():n,*t=map(int,open(0).read().split())
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def MI():return map(int,input().split())
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def RA():return map(int,open(0).read().split())
def GI(V,E,ls=None,Directed=False,index=1):
    org_inp=[];g=[[] for i in range(V)]
    FromStdin=True if ls==None else False
    for i in range(E):
        if FromStdin:
            inp=LI()
            org_inp.append(inp)
        else:
            inp=ls[i]
        if len(inp)==2:
            a,b=inp;c=1
        else:
            a,b,c=inp
        if index==1:a-=1;b-=1
        aa=(a,c);bb=(b,c);g[a].append(bb)
        if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1):
    #h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0},boundary=1) # sample usage
    mp=[boundary]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[boundary]+[mp_def[j] for j in s]+[boundary]
    mp+=[boundary]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def accum(ls):
    rt=[0]
    for i in ls:rt+=[rt[-1]+i]
    return rt
def bit_combination(n,base=2):
    rt=[]
    for tb in range(base**n):s=[tb//(base**bt)%base for bt in range(n)];rt+=[s]
    return rt
def gcd(x,y):
    if y==0:return x
    if x%y==0:return y
    while x%y!=0:x,y=y,x%y
    return y
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)
 
YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
FourNb=[(-1,0),(1,0),(0,1),(0,-1)];EightNb=[(-1,0),(1,0),(0,1),(0,-1),(1,1),(-1,-1),(1,-1),(-1,1)];compas=dict(zip('WENS',FourNb));cursol=dict(zip('LRUD',FourNb))
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
read=sys.stdin.buffer.read
readline=sys.stdin.buffer.readline
input=lambda: sys.stdin.readline().rstrip()

class Tree:
    def __init__(self,inp_size=None,ls=None,init=True,index=1):
        self.LCA_init_stat=False
        self.ETtable=[]
        if init:
            if ls==None:
                self.stdin(inp_size,index=index)
            else:
                self.size=len(ls)+1
                self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def stdin(self,inp_size=None,index=1):
        if inp_size==None:
            self.size=int(input())
        else:
            self.size=inp_size
        self.edges,_=GI(self.size,self.size-1,index=index)
        return
    
    def listin(self,ls,index=0):
        self.size=len(ls)+1
        self.edges,_=GI(self.size,self.size-1,ls,index=index)
        return
 
    def dfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.size
        v[x]=root_v
        while q:
            c=q.pop()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def bfs(self,x,func=lambda pr,prv,nx,dist:prv+dist,root_v=0):
        q=deque([x])
        v=[None]*self.size
        v[x]=root_v
        while q:
            c=q.popleft()
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=func(c,v[c],nb,d)
        return v
 
    def parent(self,x):
        return self.dfs(0,func=lambda pr,prv,nx,dist:pr,root_v=-1)
 
    def topological_sort(self,x):  # return topological sort of the tree
        tps=[]
        q=deque([x])
        v=[None]*self.size
        v[x]=0
        while q:
            c=q.popleft()
            tps.append(c)
            for nb,d in self.edges[c]:
                if v[nb]==None:
                    q.append(nb)
                    v[nb]=0
        return tps
 
    def EulerTour(self,x):
        q=deque()
        q.append(x)
        self.depth=[None]*self.size
        self.depth[x]=0
        self.ETtable=[]
        self.ETdepth=[]
        self.ETin=[-1]*self.size
        self.ETout=[-1]*self.size
        cnt=0
        while q:
            c=q.pop()
            if c<0:
                ce=~c
            else:
                ce=c
                for nb,d in self.edges[ce]:
                    if self.depth[nb]==None:
                        q.append(~ce)
                        q.append(nb)
                        self.depth[nb]=self.depth[ce]+1
            self.ETtable.append(ce)
            self.ETdepth.append(self.depth[ce])
            if self.ETin[ce]==-1:
                self.ETin[ce]=cnt
            else:
                self.ETout[ce]=cnt
            cnt+=1
        return
    
    def LCA_init(self,root):
        self.EulerTour(root)
        self.st=SparseTable(self.ETdepth,init_func=min,init_idl=inf)
        #self.st=SegTree(self.size*2-1,self.ETdepth,function=min,ide=inf)
        self.LCA_init_stat=True
        return
    
    def LCA(self,root,x,y):
        if self.LCA_init_stat==False:
            self.LCA_init(root)
        xin,xout=self.ETin[x],self.ETout[x]
        yin,yout=self.ETin[y],self.ETout[y]
        a=min(xin,yin)
        b=max(xout,yout,xin,yin)
        id_of_min_dep_in_et=self.st.query_id(a,b+1)
        return self.ETtable[id_of_min_dep_in_et]
 
    def __str__(self):
        return  str(self.edges)
 
    def show(self):
        if all([all([d==1 for nd,d in edge]) for edge in self.edges]):
            print( [[nd for nd,d in edge] for edge in self.edges] )
        else:
            print(self)
 
class SparseTable: # O(N log N) for init, O(1) for query(l,r)
    def __init__(self,ls,init_func=min,init_idl=float('inf')):
        self.func=init_func
        self.idl=init_idl
        self.size=len(ls)
        self.N0=self.size.bit_length()
        self.table=[ls[:]]
        self.index=[list(range(self.size))]
        self.lg=[0]*(self.size+1)
        
        for i in range(2,self.size+1):
            self.lg[i]=self.lg[i>>1]+1
 
        for i in range(self.N0):
            tmp=[self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) for j in range(self.size)]
            tmp_id=[self.index[i][j] if self.table[i][j]==self.func(self.table[i][j],self.table[i][min(j+(1<<i),self.size-1)]) else self.index[i][min(j+(1<<i),self.size-1)] for j in range(self.size)]
            self.table+=[tmp]
            self.index+=[tmp_id]
    
    # return func of [l,r)
    def query(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        return self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))])
    
    # return index of which val[i] = func of v among [l,r)
    def query_id(self,l,r):
        if r>self.size:r=self.size
        #N=(r-l).bit_length()-1
        N=self.lg[r-l]
        a,b=self.index[N][l],self.index[N][max(0,r-(1<<N))]
        if self.table[0][a]==self.func(self.table[N][l],self.table[N][max(0,r-(1<<N))]):
            b=a
        return b
    
    # return boundary index of r such that func({table[i]} =< x , i in [pos,r]
    def right_bound(self,pos,x):
        k=(self.size-pos).bit_length()
        for j in range(k)[::-1]:
            nx=pos+(1<<j)
            if nx<n and self.query(pos,nx+1)<=x:
                pos+=(1<<j)
        return pos
    
    # return boundary index of l such that func({table[i]} =< x , i in [l,pos]
    def left_bound(self,pos,x):
        k=pos.bit_length()
        for j in range(k)[::-1]:
            nx=pos-(1<<j)
            if 0<=nx and self.query(nx,pos+1)<=x:
                pos-=(1<<j)
        return pos
 
    def __str__(self):
        return str(self.table[0])
 
    def print(self):
        for i in self.table:
            print(*i)
 
show_flg=False
show_flg=True
ans=0



n=I()
d=n//2
d=n-1
D=1<<d
Vs=[0]*(n+1)
Ws=[0]*(n+1)

pre=[set()for i in rep(D)]

for i in rep(1,n+1):
    a,b=LI()
    Vs[i]=a
    Ws[i]=b

'''
pre[1]=[v[1]*10**9+w[1]]
for i in rep(2,D):
    p=i>>1
    for j in pre[p]:
        pre[i].add(j)
        pre[i].add(j+v[i]*10**9+w[i])

for i in rep(1,D):
    pre[i]=sorted(pre[i],key=lambda x:x%10**9)
'''

def pre(W):
    A= [[(0,0)] for i in range(D)]
    for i in range(1,D):
        p=i>>1
        A[i] = [(w+Ws[i],v+Vs[i]) for w,v in A[p]]+A[p]
    A[i].sort(key = lambda x: (x[0],-x[1]))
    tmp = -1
    tmpList = []
    for w,v in A[i]:
        if w <= W and v > tmp:
            tmpList.append((w,v))
            tmp = v
    A[i] = tmpList[:]
    return A

A=pre(10)


def solver(t,W):
    B= [(0,0)]
    if t>=D:
        for i in range(D+1,n+1):
            B += [(w+Ws[i],v+Vs[i]) for w,v in B]
        B.sort(key = lambda x: (x[0],-x[1]))
        tmp = -1
        tmpList = []
        for w,v in B:
            if w <= W and v > tmp:
                tmpList.append((w,v))
                tmp = v
        B = tmpList[:]

    wA,vA = zip(*A[D-1])
    ans = 0
    for wb,vb in B:
        idx = bisect.bisect_right(wA,W-wb)
        ans = max(ans, vA[idx-1]+vb)
    print(ans)

q=I()
for i in rep(q):
    x,l=LI()
    solver(x,l)


print(ans)

Submission status: Runtime Error

Solution code:
import math
N = int(input())
X = [[] for _ in range(N)]
for i in range(N):
    X[i] = list(map(int, input().split()))
Q = int(input())
for i in range(Q):
    x, W = list(map(int, input().split()))
    size = int(math.log2(x)+1)
    # i = size -1
    i = 0
    dp = [[0]*(W+1) for _ in range(size+1)]
    while x != 0:
        v, w = X[x-1]
        # for j in range(W+1):
        for j in range(W, -1, -1):
            # if j < w:
            if j - w >= 0:
                # dp[i][j] = dp[i+1][j]
                dp[j] = dp[j-w]+v
            # else:
            #     dp[i][j] = max(dp[i+1][j],dp[i+1][j-w]+v)
        # i -= 1
        x = x//2
    # print(dp[0][W])
    print(dp[W])

Submission status: Runtime Error

Solution code:
import sys
from heapq import heappop, heappush

readline = sys.stdin.readline
readall = sys.stdin.read
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')


def solve():
    n = ni()
    bag = [tuple(nm()) for _ in range(n)]
    q = ni()
    query = [tuple(nm()) for _ in range(q)]
    ansd = dict()
    g = [None]* 2 ** 10

    def calc(v):
        W = 10**5 + 1
        res = [0] * W
        l = list()
        while v:
            l.append(bag[v-1])
            v >>= 1
        m = len(l)
        for bit in range(1 << m):
            cv = cw = 0
            for i in range(m):
                if bit & (1 << i):
                    cv += l[i][0]
                    cw += l[i][1]
                    if cw > W:
                        break
            else:
                if res[cw] < cv:
                    res[cw] = cv
        for i in range(W-1):
            if res[i+1] < res[i]:
                res[i+1] < res[i]
        return res


    for _v, L in query:
        v = _v
        if v < 2 ** 9:
            l = list()
            while v:
                l.append(bag[v-1])
                v >>= 1
            m = len(l)
            ans = 0
            for bit in range(1 << m):
                cv = cw = 0
                for i in range(m):
                    if bit & (1 << i):
                        cv += l[i][0]
                        cw += l[i][1]
                        if cw > L:
                            break
                else:
                    if cv > ans:
                        ans = cv

            ansd[(_v, L)] = ans

        else:
            l = list()
            while v >= 2 ** 9:
                l.append(bag[v-1])
                v >>= 1
            if g[v] is None:
                g[v] = calc(v)
            m = len(l)
            ans = 0
            for bit in range(1 << m):
                cv = cw = 0
                for i in range(m):
                    if bit & (1 << i):
                        cv += l[i][0]
                        cw += l[i][1]
                        if cw > L:
                            break
                else:
                    if cv + g[v][L-cw] > ans:
                        ans = cv + g[v][L-cw]
            ansd[(_v, L)] = ans

    for c in query:
        print(ansd[c])
    return

solve()

Submission status: Runtime Error

Solution code:
#

import sys
input=sys.stdin.readline

def main():
    N=int(input())
    vw=[tuple(map(int,input().split())) for i in range(N)]
    vw=[(0,0)]+vw
    W=10**5
    dp=[[0]*(W+1) for i in range(N+1)]
    for i in range(1,W+1):
        if i < vw[1][1]:
            dp[1][i]=0
        else:
            dp[1][i]=vw[1][0]
    for i in range(2,N+1,2):
        for w in range(W+1):
            p=int(i//2)
            dp[i][w]=dp[p][w]
            if w>=vw[i][1]:
                dp[i][w]=max(dp[i][w], dp[p][w-vw[i][1]]+vw[i][0])
            if i+1<=N:
                dp[i+1][w]=dp[p][w]
                if w>=vw[i+1][1]:
                    dp[i+1][w]=max(dp[i+1][w], dp[p][w-vw[i+1][1]]+vw[i+1][0])
    Q=int(input())
    for i in range(Q):
        v,L=map(int,input().split())
        print(dp[v][L])    
    
if __name__=="__main__":
    main()

Submission status: Runtime Error

Solution code:
a,v=map(int,input().split())
b,w=map(int,input().split())
t=int(input())
x=a-b
y=abs(x)
if v*t>=(y+w*t):
    print("YES")
else:
    print("NO")

Submission status: Runtime Error

Solution code:
import numpy as np
INF = 10 ** 12
L = 10 ** 5 + 1
n=int(input())
vw=[]

def rec(x, uplimit_w):
  ans = 0
  if x == N:
    return 0

  # n番目の品物を使えない場合
  elif vws[x][1] > uplimit_w:
    return rec(x + 1, uplimit_w)

  # n番目の品物が使える時
  # -> n番目の品物は使った方がいいのか、使わない方がいいのか...?
  else:
    ans = max(
      rec(x + 1, uplimit_w),
      rec(x + 1, uplimit_w - vws[x][1]) + vws[x][0]
    )
    return ans

def solve():
  print(rec(0, l))

def main():
  solve()

for i in range(n):
  vw.append(list(map(int,input().split())))

q=int(input())

for i in range(q):
  v,l=map(int,input().split())
  vws=[vw[v-1]]
  while v>1:
    v=v//2
    vws.append(vw[v-1])
    N=len(vws)
  if __name__ == "__main__":
    main()