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: Wrong Answer

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)]
        for v,w in n1:
            ln1c=len(n1c)
            n1ca=[(n1cv+v,n1cw+w) for n1cv,n1cw in n1c]
            i1=0
            i2=0
            tot=[]

            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(n1c[i2])
                    i2+=1
                    
            if i1<ln1c:
                tot+=n1c[i1:]
            else:tot+=n1ca[i2:]
            n1c=tot

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

            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
            if f1:
                tot.append(n2c[i1])
                i1+=1
            else:
                tot.append(n2c[i2])
                i2+=1

            if i1<ln2c:
                tot+=n2c[i1:]
            else:tot+=n2ca[i2:]
            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)
        #print(n1c[:j1],n2c[:j2])
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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)]
        for v,w in n1:
            ln1c=len(n1c)
            n1ca=[(n1cv+v,n1cw+w) for n1cv,n1cw in n1c]
            i1=0
            i2=0
            tot=[]

            while i1<ln1c and i2<ln1c:
                if n1c[i1][1]<=n1ca[i2][1]:
                    tot.append(n1c[i1])
                    i1+=1
                    
                else:
                    tot.append(n1c[i2])
                    i2+=1
            if i1<ln1c:
                tot+=n1c[i1:]
            else:tot+=n1ca[i2:]
            n1c=tot

                
        for v,w in n2:
            ln2c=len(n2c)
            n2ca=[(n2cv+v,n2cw+w) for n2cv,n2cw in n2c]
            i1=0
            i2=0
            tot=[]

            while i1<ln2c and i2<ln2c:
                if n2c[i1][1]<=n2ca[i2][1]:
                    tot.append(n2c[i1])
                    i1+=1

                else:
                    tot.append(n2c[i2])
                    i2+=1

            if i1<ln2c:
                tot+=n2c[i1:]
            else:tot+=n2ca[i2:]
            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)
        #print(n1c,n2c)
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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)]
        for v,w in n1:
            ln1c=len(n1c)
            n1ca=[(n1cv+v,n1cw+w) for n1cv,n1cw in n1c]
            i1=0
            i2=0
            tot=[]

            while i1<ln1c and i2<ln1c:
                if n1c[i1][1]<=n1ca[i2][1]:
                    tot.append(n1c[i1])
                    i1+=1
                    
                else:
                    tot.append(n1c[i2])
                    i2+=1
            if i1<ln1c:
                tot+=n1c[i1:]
            else:tot+=n1ca[i2:]
            n1c=tot

                
        for v,w in n2:
            ln2c=len(n2c)
            n2ca=[(n2cv+v,n2cw+w) for n2cv,n2cw in n2c]
            i1=0
            i2=0
            tot=[]

            while i1<ln2c and i2<ln2c:
                if n2c[i1][1]<=n2ca[i2][1]:
                    tot.append(n2c[i1])
                    i1+=1

                else:
                    tot.append(n2c[i2])
                    i2+=1

            if i1<ln2c:
                tot+=n2c[i1:]
            else:tot+=n2ca[i2:]
            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][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):
            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)
        #print(n1c,n2c)
if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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:])
dp_w = [0] * (1 << 9)
dp_v = [0] * (1 << 9)
for u, l in zip(mp, mp):
    if u < precalc_limit:
        buf.append(precalc[u][l])
        continue
    lim = 1
    while u >= precalc_limit:
        v = vvv[u]
        w = www[u]
        for i in range(lim):
            nw = dp_w[i] + w
            if nw > l:
                continue
            nv = dp_v[i] + v
            dp_w[lim + i] = nw
            dp_v[lim + i] = nv
        u >>= 1
        lim <<= 1
    ans = 0
    for i in range(lim):
        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: Wrong Answer

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]
            if val > ans: ans = val
    print(ans)

Submission status: Wrong Answer

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 = tuple(data[:2*n:2])
W = tuple(data[1:2*n:2])
q = data[2*n]
v = tuple(data[2*n+1::2])
L = tuple(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**9まで前計算
b_len = min(9, n.bit_length()-1)
max_bef = 2**b_len
bef = [ [0]*(10**5 + 1) for _ in range(max_bef)]


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

    par = vi
    while(par>= max_bef):
        par //= 2

    max_ans = bef[par][Li]
    aft = [(0,0)]
    x = vi
    while(x >= max_bef):
        xw,xv = W[x-1],V[x-1]
        x //= 2
        if(x < max_bef):
            lim_j = len(aft)
            for j in range(lim_j):
                jw,jv = aft[j]
                jw += xw
                jv += xv
                lim_w = Li - (jw)
                if(lim_w >= 0):
                    max_ans = max(max_ans, bef[par][lim_w]+jv)
            break


        lim_j = len(aft)
        for j in range(lim_j):
            jw,jv = aft[j]
            jw += xw
            jv += xv
            lim_w = Li - (jw)
            if(lim_w >= 0):
                max_ans = max(max_ans, bef[par][lim_w]+jv)
                aft.append((jw,jv))

    ans.append(max_ans)

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

Submission status: Wrong Answer

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 = tuple(data[:2*n:2])
W = tuple(data[1:2*n:2])
q = data[2*n]
v = tuple(data[2*n+1::2])
L = tuple(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**9まで前計算
b_len = min(9, n.bit_length()-1)
max_bef = 2**b_len
bef = [ [0]*(10**5 + 1) for _ in range(max_bef)]

for i in range(1,max_bef):
    iw,iv = W[i-1],V[i-1]
    par = i//2
    for j in range(1,10**5+1):
        if(j>=iw):
            bef[i][j] = max(bef[par][j] , bef[par][j-iw]+iv)
        else:
            bef[i][j] = bef[par][j]

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

    par = vi
    while(par>= max_bef):
        par //= 2

    max_ans = bef[par][Li]
    aft = [(0,0)]
    x = vi
    while(x >= max_bef):
        xw,xv = W[x-1],V[x-1]
        x //= 2
        if(x < max_bef):
            lim_j = len(aft)
            for j in range(lim_j):
                jw,jv = aft[j]
                jw += xw
                jv += xv
                lim_w = Li - (jw)
                if(lim_w >= 0):
                    max_ans = max(max_ans, bef[par][lim_w]+jv)
        break


        lim_j = len(aft)
        for j in range(lim_j):
            jw,jv = aft[j]
            jw += xw
            jv += xv
            lim_w = Li - (jw)
            if(lim_w >= 0):
                max_ans = max(max_ans, bef[par][lim_w]+jv)
                aft.append((jw,jv))

    ans.append(max_ans)

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

Submission status: Wrong Answer

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)]+[tuple(map(int,readline().split())) for _ in range(n)]

A = 9
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())

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

Submission status: Wrong Answer

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)]+[tuple(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

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
    #for j in range(1,L):
    #    memo[i][j] = max(memo[i][j],memo[i][j-1])


def dfs(v,w,u):
    if u < N:
        return memo[u][l-w]+v if l>w else 0
    else:
        dfs(v,w,u>>1)
        dfs(v+vw[u][1],w+vw[u][1],u>>1)
        

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

Submission status: Wrong Answer

Solution code:
import bisect
import copy
import heapq
import sys
import itertools
import math
import queue
from functools import lru_cache
input = sys.stdin.readline
sys.setrecursionlimit(1000000)
mod = 10 ** 9 + 7 

def read_values(): return map(int, input().split())
def read_index(): return map(lambda x: int(x) - 1, input().split())
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


P = 8
def make(A, M):
    T = min(2 ** P, len(A))
    K = [[0 for _ in range(M + 1)] for _ in range(T)] 

    for v in range(T):
        for k in range(M + 1):
            a = A[v][0]
            w = A[v][1]
            if k < w:
                K[v][k] = max(K[(v - 1) // 2][k], K[v][k - 1])
            else:
                K[v][k] = max(K[(v - 1) // 2][k], K[v][k - 1], K[(v - 1) // 2][k - w] + a)
    
    return K


def f(A, v, L, K):
    T = []
    while v >= 2 ** P:
        T.append(A[v - 1])
        v = v >> 1

    M = len(T)
    res = 0
    for k in range(2 ** M):
        V = 0
        W = 0
        for i in range(M):
            if (k >> i) & 1:
                V += T[i][0]
                W += T[i][1]
            if W > L:
                break

        if W <= L:
            res = max(res, V + K[v - 1][L - W])

    return res


def main():
    N = int(input())
    A = []
    for _ in range(N):
        A.append(tuple(read_values()))
    
    Q = []
    M = 0
    for _ in range(int(input())):
        v, L = read_values()
        v -= 1
        Q.append((v, L))
        M = max(M, L)

    K = make(A, M) 
    ans = [""] * len(Q)
    for q, (v, L) in enumerate(Q):
        if v.bit_length() <= P:
            ans[q] = str(K[v][L])
        else:
            ans[q] = str(f(A, v + 1, L, K))

    print("\n".join(ans))
    

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

def main():
    import sys
    def I(): return int(sys.stdin.readline())
    def LI(): return list(map(int,sys.stdin.readline().split()))

    n = I()
    V = []
    W = []
    m = min(n, 1 << 10)
    maxL = 10**5
    dp = [[0]*(maxL + 1) for _ in range(m + 1)]
    
    for i in range(1, n+1):
        v, w = LI()
        if i <= m:
            for j in range(maxL+1):
                if j < w:
                    dp[i][j] = dp[i>>1][j]
                else:
                    dp[i][j] = max(dp[i>>1][j], dp[i>>1][j - w] + v)
            V.append(v)
            W.append(w)
        else:
            V.append(v)
            W.append(w)
    
    q = I()
    for i in range(q):
        v, L = LI()
        if v <= m:
            print(dp[v][L])
            continue
        cnt = 0
        tmp = v
        v_ = []
        w_ = []
        while tmp > m:
            v_.append(V[tmp-1])
            w_.append(W[tmp-1])
            tmp >>= 1
            cnt += 1
        ret = dp[tmp-1][L]
        v_tmp = [0] * (1 << cnt)
        w_tmp = [0] * (1 << cnt)
        for b in range(1, 1 << cnt):
            lsb = b & -b
            l = lsb.bit_length()
            w_tmp[b] = w_tmp[b - lsb] + w_[l-1]
            if w_tmp[b] <= L:
                v_tmp[b] = v_tmp[b - lsb] + v_[l-1]
                ret = max(ret, v_tmp[b] + dp[tmp-1][L - w_tmp[b]])
        print(ret)
    return

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

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

MAX = (1<<10)

def main():
    N = int(input())
    VW = [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Query = [list(map(int, input().split())) for _ in range(Q)]

    dp = [[] for _ in range(MAX+1)]
    dp[0] = [(0, 0)]
    for k in range(min(MAX, N)):
        nv, nw = VW[k]
        k += 1
        ndp = []
        for v, w in dp[k//2]:
            ndp.append((v+nv, w+nw))
        ind = 0
        for v, w in dp[k//2]:
            while ind < len(ndp) and ndp[ind][1] < w:
                dp[k].append(ndp[ind])
                ind += 1
            if ind < len(ndp) and ndp[ind][1] == w:
                if ndp[ind][0] > v:
                    dp[k].append(ndp[ind])
                else:
                    dp[k].append((v, w))
                ind += 1
            else:
                dp[k].append((v, w))
        while ind < len(ndp):
            dp[k].append(ndp[ind])
            ind += 1

    for s, L in Query:
        dp2 = [(0, 0)]
        # make new dp
        while s >= MAX:
            nv, nw = VW[s-1]
            ndp = []
            for v, w in dp2:
                if w + nw <= L:
                    ndp.append((v+nv, w+nw))
            ind = 0
            new = []
            for v, w in dp2:
                while ind < len(ndp) and ndp[ind][1] < w:
                    new.append(ndp[ind])
                    ind += 1
                if ind < len(ndp) and ndp[ind][1] == w:
                    if ndp[ind][0] > v:
                        new.append(ndp[ind])
                    else:
                        new.append((v, w))
                    ind += 1
                else:
                    new.append((v, w))
            while ind < len(ndp):
                new.append(ndp[ind])
                ind += 1
            dp2 = new
            s = s//2
        
        # merge
        ind2 = len(dp2)-1
        ans = 0
        for v, w in dp[s]:
            while ind2 > 0 and dp2[ind2][1] + w > L:
                ind2 -= 1
            if ind2 == 0 and dp2[ind2][1] + w > L: break
            score = dp2[ind2][0] + v
            if score > ans:
                ans = score
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys

#solve
def solve():

    input = sys.stdin.buffer.readline
    LI = lambda: map(int, input().split())
    II = lambda: int(input())
    n = II()
    vw = [[]] * n
    nbit = 1 << n.bit_length()
    M = 10 ** 5 + 1
    M0 = [0] * M
    XX = 1 << n.bit_length() // 2
    d = [[]] * XX
    d[0] = M0

    for i in range(1, XX):
        v, w = LI()
        vw[i - 1] = (v, w)
        di = d[i // 2][:]
        for j in range(M - 1, w - 1, -1):
            if di[j] < di[j - w] + v:
                di[j] = di[j - w] + v
        d[i] = di

    for i in range(XX, n + 1):
        v, w = LI()
        vw[i - 1] = (v, w)

    n = [pow(2, i) for i in range(18)]
    lentl = [i - i // 2 for i in range(19)]
    maskset = [[]] * n[9]

    for i in range(1, 10):
        for mask in range(n[i - 1], n[i]):
            a = mask & -mask
            b = a.bit_length() - 1
            maska = mask - a
            maskset[mask - 1] = (mask, a, b, maska)

    for _ in range(II()):
        V, L = LI()

        if V < XX:
            print(d[V][L])
            continue

        n2 = lentl[V.bit_length()]
        vw2 = [None] * n2

        for i in range(n2):
            vw2[i] = (vw[V - 1][0], vw[V - 1][1])
            V //= 2

        lw = [0] * n[n2]
        lv = [0] * n[n2]
        dv = d[V]
        ans = dv[L]

        for mask, a, b, maska in maskset[:n2]:
            v, w = vw2[b]
            ww = lw[maska] + w
            Lww = L - ww
            lw[mask] = ww
            if Lww < 0: continue
            vv = lv[maska] + v
            lv[mask] = vv
            tmp = dv[Lww] + vv
            if tmp > ans:
                ans = tmp
        print(ans)
    return

if __name__ == "__main__":
    solve()