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 heapq
n=int(input())
tree=[0]
for i in range(n):
  v,w=map(int,input().split())
  tree.append((v,w))
q=int(input())
def cal(num,w_max):
	l=[]
	x=num
	while x:
		l.append(tree[x])
		x=x//2
	l=sorted(l,key=lambda x: x[0]/x[1],reverse=True)
	def upperbound(v,w,i):#iまで決定済み
		rest=w_max-w
		v_=0
		for j in range(i+1,len(l)):
			if rest >=l[j][1]:
				v+=l[j][0]
				rest-=l[j][1]
			else:
				v_=rest*l[j][0]/l[j][1]
				break
		return v,v+v_
	
	best,best_=upperbound(0,0,-1)
	heap=[(-best_,0,0,1)]#(v,w,i,best)iまで決定,それまでのv,w,upperbound
	while len(heap):
		v_,v,w,i=heapq.heappop(heap)
		v_,v,w,i=-v_,-v,-w,-i
		if best>=v_ or i==len(l)-1:continue
		if w_max-w>=l[i+1][1]:
			for j in range(2):
				vt,vt_=upperbound(v+j*l[i+1][0],w+j*l[i+1][1],i+1)
				if best<vt_:
					heapq.heappush(heap,(-vt_,-(v+j*l[i+1][0]),-(w+j*l[i+1][1]),-(i+1)))
					if best<vt:
						best=vt
		else:
			vt,vt_=upperbound(v,w,i+1)
			if best<vt_:
				heapq.heappush(heap,(-vt_,-v,-w,-(i+1)))
				if best<vt:
					best=vt
	return best

for i in range(q):
	v,l=map(int,input().split())
	print(cal(v,l))

Submission status: Time Limit Exceeded

Solution code:
"""
問題点
greedyを使っている
選択内容がわからない
"""
import heapq
n=int(input())
tree=[0]
for i in range(n):
  v,w=map(int,input().split())
  tree.append((v,w))
q=int(input())
def cal(num,w_max):
	l=[]
	x=num
	while x:
		l.append(tree[x])
		x=x//2
	l=sorted(l,key=lambda x: x[0]/x[1],reverse=True)
	def upperbound(v,w,i):#iまで決定済み
		rest=w_max-w
		v_=0
		for j in range(i+1,len(l)):
			if rest >=l[j][1]:
				v+=l[j][0]
				rest-=l[j][1]
			else:
				v_=rest*l[j][0]/l[j][1]
				break
		return v,v+v_
	
	best,best_=upperbound(0,0,-1)
	heap=[(-best_,0,0,1)]#(v,w,i,best)iまで決定,それまでのv,w,upperbound
	while len(heap):
		v_,v,w,i=heapq.heappop(heap)
		v_,v,w,i=-v_,-v,-w,-i
		if best>=v_ or i==len(l)-1:continue
		if w_max-w>=l[i+1][1]:
			for j in range(2):
				vt,vt_=upperbound(v+j*l[i+1][0],w+j*l[i+1][1],i+1)
				if best<vt_:
					heapq.heappush(heap,(-vt_,-(v+j*l[i+1][0]),-(w+j*l[i+1][1]),-(i+1)))
					if best<vt:
						best=vt
		else:
			vt,vt_=upperbound(v,w,i+1)
			if best<vt_:
				heapq.heappush(heap,(-vt_,-v,-w,-(i+1)))
				if best<vt:
					best=vt
	return best
qs=[]
for i in range(q):
	v,l=map(int,input().split())
	qs.append((v,l))
	
for v,l in qs:
	print(cal(v,l))

Submission status: Time Limit Exceeded

Solution code:
import sys


def get_solve():
    cache = [None] * precalc_limit
    cache[0] = [0] * (weight_limit + 1)
    _vvv = vvv
    _www = www
    _weight_limit = weight_limit

    def _f(u):
        """ u < precalc_limit """
        if cache[u] is not None:
            return cache[u]
        dp = _f(u >> 1).copy()
        v = _vvv[u]
        w = _www[u]
        for x in range(_weight_limit, w - 1, -1):
            nv = dp[x - w] + v
            if dp[x] < nv:
                dp[x] = nv
        cache[u] = dp
        return dp

    return _f


n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 10, n + 1)

solve = get_solve()

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        dp = solve(u)
        buf.append(dp[l])
        continue
    dp_w = [0]
    dp_v = [0]
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(len(dp_w)):
            nw = dp_w[i] + w
            if nw > l:
                continue
            nv = dp_v[i] + v
            dp_w.append(nw)
            dp_v.append(nv)
        u >>= 1
    ans = 0
    dp = solve(u)
    for w, v in zip(dp_w, dp_v):
        nv = v + dp[l - w]
        if ans < nv:
            ans = nv
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率

def input(): return sys.stdin.readline()[:-1]
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]

def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    vs=[]
    ws=[]
    costs=tuple(tuple(map(int, input().split())) for i in range(N))
    visited=[0]*N
    Q=int(input())
    qs= tuple(tuple(map(int, input().split())) for i in range(Q))
    maxL=int(max([qs[i][1] for i in range(Q)]))

    
    #愚直な半分全列挙,TLE    
    for v,L in qs:
        if v==1:
            v,w=costs[0]
            if w<=L:print(v)
            else:print(0)
            continue

        n=[]
        while v:
            n.append(costs[v-1])
            v=v//2
        ln=len(n)
        n1=n[:ln//2]
        n2=n[ln//2:]
        
        n1c=[]
        n2c=[]
        for i in range(len(n1)+1):
            for n1b in combinations(n1,i):
                vsum=sum([x[0] for x in n1b])
                wsum=sum([x[1] for x in n1b])
                n1c.append((wsum,vsum))
        for i in range(len(n2)+1):
            for n2b in combinations(n2,i):
                vsum=sum([x[0] for x in n2b])
                wsum=sum([x[1] for x in n2b])
                n2c.append((wsum,vsum))
        vmax=10**5+1
        n1c.sort(key=lambda k: k[0]*vmax+k[1])
        n2c.sort(key=lambda k: k[0]*vmax+k[1])
        
        j1=1
        for i in range(1,len(n1c)):
            if n1c[i][1]>n1c[j1-1][1]:
                n1c[j1]=n1c[i]
                j1+=1
        
        
        j=j1-1
        ans=0
        n1c1=tuple(x[0] for x in n1c)
        for i in range(len(n2c)):
            w,v=n2c[i]
            rw=L-w
            if rw<0:
                continue
            j=bisect_right(n1c1,rw)
            if j>0:
                v+=n1c[j-1][1]
            ans=max(ans,v)
        print(ans)
        #print(n1c,n1)
        
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率

def input(): return sys.stdin.readline()[:-1]
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    vs=[]
    ws=[]
    costs=tuple(tuple(map(int, input().split())) for i in range(N))
    visited=[0]*N
    Q=int(input())
    qs= tuple(tuple(map(int, input().split())) for i in range(Q))
    maxL=int(max([qs[i][1] for i in range(Q)]))

    
    #マージソートを利用してlog(2**N)を消す
    for v,L in qs:
        if v==1:
            v,w=costs[0]
            if w<=L:print(v)
            else:print(0)
            continue

        n=[]
        while v:
            n.append(costs[v-1])
            v=v//2
        ln=len(n)
        n1=n[:ln//2]
        n2=n[ln//2:]
        
        n1c=[(0,0)]
        n2c=[(0,0)]

        #print(n2)
        for v,w in n1:
            
            ln1c=len(n1c)
            n1ca=[(n1cv+v,n1cw+w) for n1cv,n1cw in n1c]
            i1=0
            i2=0
            tot=[]
            #print(n1c,n1ca)
            while i1<ln1c and i2<ln1c:
                f1=0
                if n1c[i1][1]<n1ca[i2][1]:
                    f1=1  
                elif n1c[i1][1]==n1ca[i2][1] and n1c[i1][0]<=n1ca[i2][0]:
                    f1=1
                if f1:
                    tot.append(n1c[i1])
                    i1+=1
                else:
                    tot.append(n1ca[i2])
                    i2+=1
                
                    
            if i1<ln1c:
                tot+=n1c[i1:]
            else:
                tot+=n1ca[i2:]
            
            n1c=tot
            #print(n1c)
            
            

                
        for v,w in n2:
            f1=0
            ln2c=len(n2c)
            n2ca=[(n2cv+v,n2cw+w) for n2cv,n2cw in n2c]
            i1=0
            i2=0
            tot=[]
            while i1<ln2c and i2<ln2c:
                f1=0
                if n2c[i1][1]<n2ca[i2][1]:
                    f1=1  
                elif n2c[i1][1]==n2ca[i2][1] and n2c[i1][0]<=n2ca[i2][0]:
                    f1=1
                #print(n2c[i1][1],n2c[i2][1],f)
                if f1:
                    tot.append(n2c[i1])
                    i1+=1
                else:
                    tot.append(n2ca[i2])
                    i2+=1
                
            if i1<ln2c:
                tot+=n2c[i1:]
            else:tot+=n2ca[i2:]
            #print(n2c,n2ca,tot)
            n2c=tot
            
        #vmax=10**5+1
        #n1c.sort(key=lambda k: k[0]*vmax+k[1])
        #n2c.sort(key=lambda k: k[0]*vmax+k[1])
        
        

        j1=1
        for i in range(1,len(n1c)):
            if n1c[i][0]>n1c[j1-1][0]:
                n1c[j1]=n1c[i]
                j1+=1
        
        j2=1
        for i in range(1,len(n2c)):
            if n2c[i][0]>n2c[j2-1][0]:
                n2c[j2]=n2c[i]
                j2+=1

        j=j1-1
        ans=0
        for i in range(j2):
            v,w=n2c[i]
            while j>=0 and n1c[j][1]+w>L:
                j-=1
            if j==-1:
                break
            ans=max(ans,v+n1c[j][0])
        print(ans)
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**7) #再帰関数の上限,10**5以上の場合python
import math
from copy import copy, deepcopy
from copy import deepcopy as dcp
from operator import itemgetter
from bisect import bisect_left, bisect, bisect_right#2分探索
#bisect_left(l,x), bisect(l,x)#aはソート済みである必要あり。aの中からx未満の要素数を返す。rightだと以下
from collections import deque
#deque(l), pop(), append(x), popleft(), appendleft(x)
##listでqueの代用をするとO(N)の計算量がかかってしまうので注意
from collections import Counter#文字列を個数カウント辞書に、
#S=Counter(l),S.most_common(x),S.keys(),S.values(),S.items()
from itertools import accumulate,combinations,permutations#累積和
#list(accumulate(l))
from heapq import heapify,heappop,heappush
#heapify(q),heappush(q,a),heappop(q) #q=heapify(q)としないこと、返り値はNone
#import fractions#古いatcoderコンテストの場合GCDなどはここからimportする
from functools import lru_cache#pypyでもうごく
#@lru_cache(maxsize = None)#maxsizeは保存するデータ数の最大値、2**nが最も高効率

def input(): return sys.stdin.readline()[:-1]
def printl(li): _=print(*li, sep="\n") if li else None
def argsort(s, return_sorted=False): 
    inds=sorted(range(len(s)), key=lambda k: s[k])
    if return_sorted: return inds, [s[i] for i in inds]
    return inds
def alp2num(c,cap=False): return ord(c)-97 if not cap else ord(c)-65
def num2alp(i,cap=False): return chr(i+97) if not cap else chr(i+65)
def matmat(A,B):
    K,N,M=len(B),len(A),len(B[0])
    return [[sum([(A[i][k]*B[k][j]) for k in range(K)]) for j in range(M)] for i in range(N)]
def matvec(M,v):
    N,size=len(v),len(M)
    return [sum([M[i][j]*v[j] for j in range(N)]) for i in range(size)]
def T(M):
    n,m=len(M),len(M[0])
    return [[M[j][i] for j in range(n)] for i in range(m)]
def main():
    mod = 1000000007
    #w.sort(key=itemgetter(1),reversed=True)  #二個目の要素で降順並び替え

    N = int(input())
    #N, K = map(int, input().split())
    #A = tuple(map(int, input().split())) #1行ベクトル
    #L = tuple(int(input()) for i in range(N)) #改行ベクトル
    #S = tuple(tuple(map(int, input().split())) for i in range(N)) #改行行列
    vs=[]
    ws=[]
    costs=tuple(tuple(map(int, input().split())) for i in range(N))
    visited=[0]*N
    Q=int(input())
    qs= tuple(tuple(map(int, input().split())) for i in range(Q))
    maxL=int(max([qs[i][1] for i in range(Q)]))

    
        
    for v,L in qs:
        if v==1:
            v,w=costs[0]
            if w<=L:print(v)
            else:print(0)
            continue

        n=[]
        while v:
            n.append(costs[v-1])
            v=v//2
        ln=len(n)
        n1=n[:ln//2]
        n2=n[ln//2:]
        
        n1c=[]
        n2c=[]
        for i in range(len(n1)+1):
            for n1b in combinations(n1,i):
                vsum=sum([x[0] for x in n1b])
                wsum=sum([x[1] for x in n1b])
                n1c.append((wsum,vsum))
        for i in range(len(n2)+1):
            for n2b in combinations(n2,i):
                vsum=sum([x[0] for x in n2b])
                wsum=sum([x[1] for x in n2b])
                n2c.append((wsum,vsum))
        vmax=10**5+1
        n1c.sort(key=lambda k: k[0]*vmax+k[1])
        n2c.sort(key=lambda k: k[0]*vmax+k[1])
        
        j1=1
        for i in range(1,len(n1c)):
            if n1c[i][1]>n1c[j1-1][1]:
                n1c[j1]=n1c[i]
                j1+=1
        
        j2=1
        for i in range(1,len(n2c)):
            if n2c[i][1]>n2c[j2-1][1]:
                n2c[j2]=n2c[i]
                j2+=1

        j=j1-1
        ans=0
        for i in range(j2):
            w,v=n2c[i]
            while j>=0 and n1c[j][0]+w>L:
                j-=1
            if j==-1:
                break
            ans=max(ans,v+n1c[j][1])
        print(ans)
        
if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input=sys.stdin.buffer.readline

N=int(input())
vw=[(-1,-1)]
for i in range(N):
    vw.append(tuple(map(int,input().split())))

dp=[[0 for i in range(100001)] for i in range(2**9)]
for i in range(vw[1][1],100001):
    dp[1][i]=vw[1][0]
MAX=min(2**9,N+1)
for i in range(2,MAX):
    v,w=vw[i]
    for j in range(100001):
        dp[i][j]=max(dp[i//2][j],(dp[i//2][j-w]+v)*(j>=w))

temp=[[0,0] for i in range(2**9)]

def solve(v,L):
    t=[]
    while v>=2**9:
        t.append(vw[v])
        v//=2
    n=len(t)
    for i in range(1,2**n):
        m=i.bit_length()
        temp[i][0]=temp[i-2**(m-1)][0]+t[m-1][0]
        temp[i][1]=temp[i-2**(m-1)][1]+t[m-1][1]
    ans=0
    for i in range(2**n):
        if L>=temp[i][1]:
            ans=max(ans,temp[i][0]+dp[v][L-temp[i][1]])
    return ans

for i in range(int(input())):
    v,L=map(int,input().split())
    print(solve(v,L))

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 11, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp_w = [0]
    dp_v = [0]
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(len(dp_w)):
            nw = dp_w[i] + w
            if nw > l:
                continue
            nv = dp_v[i] + v
            dp_w.append(nw)
            dp_v.append(nv)
        u >>= 1
    ans = 0
    for w, v in zip(dp_w, dp_v):
        nv = v + precalc[u][l - w]
        if ans < nv:
            ans = nv
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 9, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp_w = [0]
    dp_v = [0]
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(len(dp_w)):
            nw = dp_w[i] + w
            if nw > l:
                continue
            nv = dp_v[i] + v
            dp_w.append(nw)
            dp_v.append(nv)
        u >>= 1
    ans = 0
    for w, v in zip(dp_w, dp_v):
        nv = v + precalc[u][l - w]
        if ans < nv:
            ans = nv
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 9, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
inp_offset = n * 2 + 1
for i in range(0, inp[n * 2] * 2, 2):
    u = inp[inp_offset + i]
    l = inp[inp_offset + i + 1]
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp_w = [0]
    dp_v = [0]
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(len(dp_w)):
            nw = dp_w[i] + w
            nv = dp_v[i] + v
            if nw > l:
                continue
            dp_w.append(nw)
            dp_v.append(nv)
        u >>= 1
    ans = 0
    for i in range(len(dp_w)):
        nv = dp_v[i] + precalc[u][l - dp_w[i]]
        if ans < nv:
            ans = nv
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 9, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp = {0: 0}
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for cw, cv in list(dp.items()):
            nw = cw + w
            nv = cv + v
            if nw > l:
                continue
            if nw not in dp or dp[nw] < nv:
                dp[nw] = nv
        u >>= 1
    ans = max(v + precalc[u][l - w] for w, v in dp.items())
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 9, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp_w = [0]
    dp_v = [0]
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(len(dp_w)):
            nw = dp_w[i] + w
            if nw > l:
                continue
            nv = dp_v[i] + v
            dp_w.append(nw)
            dp_v.append(nv)
        u >>= 1
    ans = 0
    for i in range(len(dp_w)):
        w = dp_w[i]
        v = dp_v[i]
        nv = v + precalc[u][l - w]
        if ans < nv:
            ans = nv
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 1, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp_w = [0]
    dp_v = [0]
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(len(dp_w)):
            nw = dp_w[i] + w
            if nw > l:
                continue
            nv = dp_v[i] + v
            dp_w.append(nw)
            dp_v.append(nv)
        u >>= 1
    ans = 0
    for i in range(len(dp_w)):
        w = dp_w[i]
        v = dp_v[i]
        nv = v + precalc[u][l - w]
        if ans < nv:
            ans = nv
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 1, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp = {0: 0}
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for cw, cv in list(dp.items()):
            nw = cw + w
            nv = cv + v
            if nw > l:
                continue
            if nw not in dp or dp[nw] < nv:
                dp[nw] = nv
        u >>= 1
    ans = 0
    for w, v in dp.items():
        nv = v + precalc[u][l - w]
        if ans < nv:
            ans = nv
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
import sys

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]

weight_limit = 10 ** 5
precalc_limit = min(1 << 1, n + 1)
precalc = [[0] * (weight_limit + 1)]

for u in range(1, precalc_limit):
    v = vvv[u]
    w = www[u]
    dp = precalc[u >> 1][:]
    for x in range(weight_limit, w - 1, -1):
        nv = dp[x - w] + v
        if dp[x] < nv:
            dp[x] = nv
    precalc.append(dp)

buf = []
mp = iter(inp[n * 2 + 1:])
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    dp = {0: 0}
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for cw, cv in list(dp.items()):
            nw = cw + w
            nv = cv + v
            if nw > l:
                continue
            if nw not in dp or dp[nw] < nv:
                dp[nw] = nv
        u >>= 1
    ans = max(v + precalc[u][l - w] for w, v in dp.items())
    buf.append(ans)

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

Submission status: Time Limit Exceeded

Solution code:
while True:
	tmp = 0

Submission status: Time Limit Exceeded

Solution code:
n=int(input())
L=10**5
item=[(0,0)]
for i in range(n):
    v,w=map(int,input().split())
    item.append((v,w))

dp=[[0 for _ in range(L+1)] for _ in range(n+1)] 

for k in range(item[1][1],L+1):
    dp[1][k]=item[1][0]

MIN=min(2**9,n)
for i in range(2,MIN+1):
    for l in range(L+1):
        bi=i//2
        if item[i][1]<=l:
            dp[i][l]=max(dp[bi][l-item[i][1]]+item[i][0],dp[bi][l])
        else:
            dp[i][l]=dp[bi][l]

Q=int(input())
for q in range(Q):
    u,w=map(int,input().split())
    if u<=MIN:
        print(dp[u][w])
    
    else:
        node=[u]
        while u>MIN:
            u//=2
            node.append(u)

        v=node.pop() 
        while len(node)!=0 :
            nv=node.pop()
            for l in range(L+1):
                if item[nv][1]<=l:
                    dp[nv][l]=max(dp[v][l-item[nv][1]]+item[nv][0],dp[v][l])
                else:
                    dp[nv][l]=dp[v][l]
        print[nv][w]

Submission status: Time Limit Exceeded

Solution code:
def dfs(dpt,mxL,nodes,current,N):
    oya = current//2

    if current > N:
        return
    for omosa,value in dpt[oya].items():
        if omosa > mxL[current]:
            continue
        if omosa in dpt[current]:
            dpt[current][omosa] = max(dpt[current][omosa],value)
        else:
            dpt[current][omosa] = value
        new_omosa = omosa+nodes[current][0]
        if new_omosa > mxL[current]:
            continue
        if new_omosa in dpt[current]:
            dpt[current][new_omosa] = max(dpt[current][new_omosa],value+nodes[current][1])
        else:
            dpt[current][new_omosa] = value+nodes[current][1]

    dfs(dpt,mxL,nodes,current*2,N)
    dfs(dpt,mxL,nodes,current*2+1,N)






def resolve():
    N = int(input())
    nodes =[0] 
    for i in range(N):
        V,W = map(int,input().split())
        nodes.append((W,V))

    q = int(input())
    querys = []
    for i in range(q):
        v,L = map(int,input().split())
        querys.append((v,L))
    mxL = [0]*(N+1)

    for v,L in querys:
         while True:
             mxL[v] = max(mxL[v],L)
             if v == 0:
                 break
             v //=2
    dpt = [dict() for i in range(N+1)]
    dpt[0][0]=0
    dfs(dpt,mxL,nodes,1,N)

    for node, cost in querys:
        mx = 0
        for omosa, value in dpt[node].items():
            if omosa <= cost:
                mx = max(mx,value)
        print(mx)
resolve()

Submission status: Time Limit Exceeded

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

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

A = 10
N = min(1<<A,n+1)

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

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] = m

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

    m = u.bit_length() - A
    if m<0: m=0
    dv = [0]*(1<<m)
    dw = [0]*(1<<m)
    for i in range(m):
        v,w = vw[u]
        for j in range(1<<i):
            dv[j+(1<<i)] = dv[j]+v
            dw[j+(1<<i)] = dw[j]+w
        u >>= 1
    
    ans = 0
    for v,w in zip(dv,dw):
        if w <= l:
            val = memo[u][l-w] + v
            if val > ans: ans = val
    print(ans)