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:
from functools import lru_cache

@lru_cache(maxsize=None)
def rooting(index):
  targets = []
  while index > 0:
    targets.append(index)
    index = index // 2
  return targets

class Node:
    def __init__(self, data, value, weight): #コンストラクタ
        self.data = data #ノードがもつ数値
        self.value = value
        self.weight = weight
        self.left = None #左エッジ
        self.right = None #右エッジ


class BST:
    def __init__(self, number_list): #コンストラクタ
        self.root = None #ルートノード初期化
        for node in number_list: #数値を持つ配列から二分木を生成
            self.insert(*node) #挿入メソッドを使ってノードを挿入する
    #挿入
    def insert(self, data, value, weight):
        n = self.root
        if n == None:
            self.root = Node(data, value, weight)
            return
        else:
            targets = rooting(data)
            num = 1
            pn = n
            cn = n
            for i in reversed(targets[:-1]):
                if i == num * 2:
                    pn = cn
                    cn = cn.left
                else:
                    pn = cn
                    cn = cn.right
                num = i
            if targets[1] * 2 == targets[0]:
                pn.left = Node(data, value, weight)
            else:
                pn.right = Node(data, value, weight)

n = int(input())
vw = []
for j in range(n):
    vw.append([j+1] + [int(i) for i in input().split()])

q = int(input())
vl = []
for _ in range(q):
    vl.append([int(i) for i in input().split()])

import math
tree = BST(vw)

Submission status: Wrong Answer

Solution code:
n=int(input())
a=[]
b=[]
c=[]

for i in range(n):
    v,w=map(int,input().split())
    a.append((v,w))
q=int(input())
for i in range(q):
    d,e=map(int,input().split())
    b.append(d)
    c.append(e)
an=[[-1 for i in range(max(c)+1)]for j in range(n)]
def ne(l,n):
    if an[n-1][l]!=-1:
        return an[n-1][l]
    elif n==1 and a[0][1]>l:
        an[n-1][l]=0
        return 0
    elif n==1 and a[0][1]<=l:
        an[n-1][l]=a[0][0]
        return a[0][0]
    elif a[n-1][1]<=l:
        
        return max(ne(l-a[n-1][1],n//2)+a[n-1][0],ne(l,n//2))
        an[n-1][l]=max(ne(l-a[n-1][1],n//2)+a[n-1][0],ne(l,n//2))
    else:
        return ne(l,n-1)
        an[n-1][l]=ne(l,n-1)
for i in range(q):
    print(ne(c[i],b[i]))

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np
from numba import njit

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

A = 1024

# ノード、重さ→価値
@njit('(i4,i4[:],i4[:])', cache=True)
def precompute(N, V, W):
    U = 10**5 + 10
    dp = np.zeros((A, U), np.int32)
    for v in range(1, min(A, N)):
        p = v // 2
        dp[v] = dp[p]
        dp[v, W[v]:] = np.maximum(dp[v, W[v]:], dp[p, :-W[v]] + V[v])
        for i in range(1, U):
            dp[v][i] = max(dp[v][i], dp[v][i - 1])
    return dp

@njit('(i4,i4[:],i4[:],i4[:],i4[:])', cache=True)
def main(N, V, W, v, L):
    dp = precompute(N, V, W)
    values = np.empty(1024, np.int32)
    weights = np.empty(1024, np.int32)

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

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

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

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

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
wv = []
for _ in range(n):
    v, w = map(int, input().split())
    wv.append([w, -v])

n2 = max(1, min(n, int(n ** 0.5)))
tab = [[[0, 0], wv[0]]]
for i in range(1, n2):
    j = (i - 1) // 2
    a = tab[j][:]
    for j in a[:]:
        a.append([j[0] + wv[i][0], j[1] + wv[i][1]])
    a.sort()
    tab.append(a)

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

        i = 0
        j = len(a) - 1
        for i in tab[u]:
            if i[0] > l:
                break
            while i[0] + a[j][0] > l:
                j -= 1
            ans = max(ans, -i[1]+a[j][1])
        print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())

S = [list(map(int, input().split())) for _ in range(n)]
q = int(input())

vl = [list(map(int, input().split())) for _ in range(q)]

dp = [[0]*(10**5+10) for _ in range(n+1)]


def knapsack(v, L):
    if v == 1:
        if S[v-1][1] > L:
            dp[v][L] = 0
            return 0
        else:
            dp[v][L] = S[v-1][0]
            return S[v-1][0]
    if dp[v][L] != 0:
        return dp[v][L]
    if L < S[v-1][1]:
        dp[v][L] = dp[v//2][L]
    else:
        #print(knapsack(v//2, L))
        #print(knapsack(v//2, L-S[v-1][1])+S[v-1][0])
        dp[v][L] = max(knapsack(v//2, L),
                       knapsack(v//2, L-S[v-1][1])+S[v-1][0])
    return dp[v][L]


for v, L in vl:
    print(knapsack(v, L))

Submission status: Wrong Answer

Solution code:
N=int(input())
"""
I=[]
for i in range(N):
    v,w=map(int, input().split())
    I.append((v,w))

Q=int(input())
for i in range(Q):
    v,l=map(int, input().split())
"""
for i in range(N):
    print(i)

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
vw = [[0,0]]+[list(map(int,input().split())) for i in range(n)]
q = int(input())
query = [list(map(int,input().split())) for i in range(q)]
border = 12
knapls = [[] for i in range(2**border)]
knapls[0].append((0,0))
for i in range(1,2**border):
  ls = []
  if i > n:
    break
  ls.extend(knapls[i//2])
  v,w = vw[i]
  l = len(ls)
  for j in range(l):
    vp,wp = ls[j]
    if wp+w > 10**5:
      continue
    ls.append((vp+v,wp+w))
  ls.sort(key = lambda x:x[1])
  knapls[i].append((0,0))

  for j in range(len(ls)):
    vn,wn = ls[j]
    vp,wp = knapls[i][-1]
    if wp <= wn and vp >= vn:
      continue
    knapls[i].append(ls[j])
for v,L in query:
  if v >= 2**border:
    anc = v
    ls = [(0,0)]
    while anc >= 2**border:
      vn,wn = vw[anc]
      l = len(ls)
      for i in range(l):
        vp,wp = ls[i]
        if wp+wn > L:
          continue
        ls.append((vp+vn,wp+wn))
      anc //= 2
    ans = 0
    l = len(ls)
    for i in range(l):
      vn,wn = ls[i]
      rest = L-wn
      left = 0
      right = len(knapls[anc])
      while left+1 < right:
        mid = (left+right)//2
        if knapls[anc][mid][1] > rest:
          right = mid
        else:
          left = mid
      ans = max(knapls[anc][left][0]+vn,ans)
  else:
    ans = 0
    left = 0
    right = len(knapls[v])
    while left+1 < right:
      mid = (left+right)//2
      if knapls[v][mid][1] > L:
        right = mid
      else:
        left = mid
    ans = knapls[v][left][0]
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys
from collections import defaultdict

n, *inp = map(int, sys.stdin.buffer.read().split())
vvv = [0] + inp[0:n * 2:2]
www = [0] + inp[1:n * 2:2]
mp = iter(inp[n * 2 + 1:])
query_ls = defaultdict(list)
query_idx = {}
required = [-1] * (n + 1)
for i, q in enumerate(zip(mp, mp)):
    query_idx[q] = i
    u, l = q
    query_ls[u].append(l)
    while u > 0:
        if required[u] >= l:
            break
        required[u] = l
        u >>= 1

cache_dp = [None] * (n + 1)
cache_dp[0] = {0: 0}
cache_max = [(-1, -1)] * (n + 1)
ans = [0] * inp[n * 2]

for u in range(1, n + 1):
    r = required[u]
    if r == -1:
        continue
    par = cache_dp[u >> 1]
    cur_w, cur_v = cache_max[u >> 1]
    if cur_w > r:
        cur_w, cur_v = max((itm for itm in par.items() if itm[0] <= r), default=(-1, -1))
    dp = par.copy()
    v = vvv[u]
    w = www[u]

    for cw, cv in par.items():
        nw = cw + w
        if nw > r:
            continue
        nv = cv + v
        if nw not in dp or dp[nw] < nv:
            dp[nw] = nv
            if nv > cur_v:
                cur_w = nw
                cur_v = nv
            elif nv == cur_v and cur_w > nw:
                cur_w = nw

    if u in query_ls:
        for l in query_ls[u]:
            if cur_w <= l:
                tmp = cur_v
            else:
                tmp = max((v for w, v in dp.items() if w <= l), default=0)
            ans[query_idx[u, l]] = tmp

    cache_dp[u] = dp

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

Submission status: Wrong Answer

Solution code:
N = int(input())
stones = [list(map(int,input().split())) for i in range(N)]
DP = [{0:0} for i in range(N)]
DP[0][stones[0][1]] = stones[0][0]
maxL = 10**5+1
queue = [{} for i in range(N)]
ans_index = []

Q = int(input())
for i in range(Q):
    V,L = map(int,input().split())
    queue[V-1][L] = 1
    ans_index.append([V-1,L])

for i in range(1,N):
    V,W = stones[i]
    par = (i-1)//2
    for w,v in DP[par].items():
        if w in DP[i]:
            DP[i][w] = max(v,DP[i][w])
        else:
            DP[i][w] = DP[par][w]
        if w+W in DP[i]:
            DP[i][w+W] = max(v+V,DP[i][w+W])
        else:
            DP[i][w+W] = v+V

print(0)

Submission status: Wrong Answer

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

for i in range(n):
  vw.append(list(map(int,input().split())))
q=int(input())
ans=[0]*q

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])
  dp = np.full(L, INF, dtype=int)
  dp[0] = 0
  for v, w in vws:
    np.minimum(
        dp[:L-v] + w,
        dp[v:],
        out=dp[v:]
    )

  answer, = np.where(dp <= l)
  print(answer[-1])

Submission status: Wrong Answer

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")



n = int(input())
V = [None]*n
W = [None]*n
for i in range(n):
    V[i],W[i] = map(int, input().split())

from queue import deque
q = deque([0])
d = [None]*n
d[0] = [(0,0), (W[0], V[0])]
until = min(n, 2**12-1)
# until = n
while q:
    u = q.pop()
    l = d[u]
    for v in (2*u+1, 2*u+2):
        if v>=until:
            continue
        ll = l + list((ww+W[v], vv+V[v]) for ww,vv in l)
        ll.sort()
        tmp = [ll[0]]
        for item in ll:
            if tmp[-1][1]<item[1]:
                tmp.append(item)
                
        d[v] = tmp
        q.appendleft(v)

from bisect import bisect_right as br
def sub(vv, L):
    if d[vv] is None:
        tmp = [(0,0), (W[vv], V[vv])]
        while d[vv] is None:
            vv = (vv-1)//2
            ll = tmp + list((wt+W[vv], vt+V[vv]) for wt,vt in tmp)
            ll.sort()
            tmp = [ll[0]]
            for item in ll:
                if tmp[-1][1]<item[1]:
                    tmp.append(item)
            ll = tmp
    else:
        tmp = [(0,0)]
    l = d[vv]
    ans = -1
    for w1,v1 in tmp:
        if w1>L:
            continue
        out = br(l, (L-w1, float("inf")))
        ans = max(ans, l[out-1][1]+v1)
    return ans
        
q = int(input())
ans = [None]*q
for i in range(q):
    vv, ll = map(int, input().split())
    vv -= 1
    ans[i] = sub(vv, ll)
write("\n".join(map(str, ans)))

Submission status: Wrong Answer

Solution code:
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
input = sys.stdin.readline
mod = 10**9+7
Max = sys.maxsize
def l(): #intのlist
	return list(map(int,input().split()))
def m(): #複数文字
	return map(int,input().split())
def onem(): #Nとかの取得
	return int(input())
def s(x): #圧縮
	a = []
	if len(x) == 0:
		return []
	aa = x[0]
	su = 1
	for i in range(len(x)-1):
		if aa != x[i+1]:
			a.append([aa,su])
			aa = x[i+1]
			su = 1
		else:
			su += 1
	a.append([aa,su])
	return a
def jo(x): #listをスペースごとに分ける
	return " ".join(map(str,x))
def max2(x): #他のときもどうように作成可能
	return max(map(max,x))
def In(x,a): #aがリスト(sorted)
    k = bs.bisect_left(a,x)
    if k != len(a) and a[k] ==  x:
        return True
    else:
        return False

def pow_k(x, n):
    ans = 1
    while n:
        if n % 2:
            ans *= x
        x *= x
        n >>= 1
    return ans

"""
def nibu(x,n,r):
	ll = 0
	rr = r
	while True:
		mid = (ll+rr)//2

	if rr == mid:
		return ll
	if (ここに評価入れる):
		rr = mid
	else:
		ll = mid+1
"""

n = onem()

po = []

for i in range(n):
	po.append(l())
q = onem()
for i in range(q):
	de = [[po[0][0]/po[0][1],po[0][0],po[0][1]]]
	v,L = m()
	while True:
		if v == 1:
			break
		de.append([po[v-1][0]/po[v-1][1],po[v-1][0],po[v-1][1]])
		v //= 2
	de.sort(reverse = True)
	we = 0
	ans = 0
	for j in range(len(de)):
		ja = de[j]
		if we + ja[2] <= L:
			we += ja[2]
			ans += ja[1]
	print(ans)

Submission status: Wrong Answer

Solution code:
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n=II()
    vv=[]
    ww=[]
    for _ in range(n):
        v,w=MI()
        vv.append(v)
        ww.append(w)
    q=II()
    ii=[-1]*n
    mm=[-1]*n
    for i in range(q):
        u,m=MI()
        ii[u-1]=i
        mm[u-1]=m
    ans=[-1]*q

    def dfs(u,dp):
        ndp=dp.copy()
        vu=vv[u]
        wu=ww[u]
        for w,v in dp.items():
            nw=w+wu
            nv=v+vu
            if nw in ndp:ndp[nw]=max(ndp[nw],nv)
            else:ndp[nw]=nv
        if ii[u]!=-1:
            i=ii[u]
            m=mm[u]
            ans[i]=max(v for w,v in ndp.items() if w<=m)
        if 2*u+1<n:dfs(2*u+1,ndp)
        if 2*u+2<n:dfs(2*u+2,ndp)

    dfs(0,{0:0})

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

main()

Submission status: Wrong Answer

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

sys.setrecursionlimit(1000000)
ACMOD = 1000000007
INF = 1 << 62


def solve(N: int, V: "List[int]", W: "List[int]", Q: int, v: "List[int]", L: "List[int]"):
    memo = {0: {0: 0, W[0]: V[0]}}

    def calc(i):
        if i in memo:
            return
        # handled in memo
        # if i == 0:
        #     return
        cw = W[i]
        cv = V[i]
        memo[i] = {}
        cur = memo[i]
        calc((i - 1) // 2)
        for w, v in memo[(i - 1) // 2].items():
            if w in cur:
                cur[w] = max(cur[w],v)
            else:
                cur[w] = v
            if w + cw <= 10 ** 5:
                if w + cw in cur:
                    cur[w + cw] = max(cur[w + cw], v + cv)
                else:
                    cur[w + cw] = v + cv

    for i in range(Q):
        target = v[i] - 1
        calc(target)
        # print(max(v for w, v in memo[target].items() if w <= L[i]))


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    V = [int()] * (N)  # type: "List[int]"
    W = [int()] * (N)  # type: "List[int]"
    for i in range(N):
        V[i] = int(next(tokens))
        W[i] = int(next(tokens))
    Q = int(next(tokens))  # type: int
    v = [int()] * (Q)  # type: "List[int]"
    L = [int()] * (Q)  # type: "List[int]"
    for i in range(Q):
        v[i] = int(next(tokens))
        L[i] = int(next(tokens))
    solve(N, V, W, Q, v, L)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict
from itertools import product
from bisect import bisect_right


def main():
    n = int(input())
    vw = [(None, None)]
    for _ in range(n):
        v, w = map(int, input().split())
        vw.append((v, w))
    q = int(input())
    ul = [map(int, input().split()) for _ in range(q)]

    def f(li, w_max):
        d = defaultdict(int)
        for pat in product(range(2), repeat=len(li)):
            v_sm = 0
            w_sm = 0
            for e, bl in zip(li, pat):
                if bl:
                    v, w = vw[e]
                    v_sm += v
                    w_sm += w

            if w_sm <= w_max:
                d[w_sm] = max(d[w_sm], v_sm)

        return d

    for u, l in ul:
        li = []
        now = u
        while now:
            li.append(now)
            now //= 2

        ln = len(li)
        d1 = f(li[:ln//2], l)
        d2 = f(li[ln//2:], l)

        wv2 = [[key, val] for key, val in d2.items()]
        wv2.sort()
        for i in range(1, len(wv2)):
            w_now, v_now = wv2[i]
            w_pre, v_pre = wv2[i-1]
            if v_pre > v_now:
                wv2[i][1] = v_pre

        ans = 0
        for k1, v1 in d1.items():
            i = bisect_right(wv2, [l - k1, v1])
            ans = max(ans, wv2[i-1][1] + v1)

        print(ans)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
a=[]
b=[]
c=[]

for i in range(n):
    v,w=map(int,input().split())
    a.append((v,w))
q=int(input())
for i in range(q):
    d,e=map(int,input().split())
    b.append(d)
    c.append(e)
an=[[-1 for i in range(max(c))]for j in range(n)]
def ne(l,n):
    if an[n-1][l-1]!=-1:
        return an[n-1][l-1]
    elif n==1 and a[0][1]>l:
        an[n-1][l-1]=0
        return 0
    elif n==1 and a[0][1]<=l:
        an[n-1][l-1]=a[0][0]
        return a[0][0]
    elif a[n-1][1]<=l:
        
        return max(ne(l-a[n-1][1],n//2)+a[n-1][0],ne(l,n//2))
        an[n-1][l-1]=max(ne(l-a[n-1][1],n//2)+a[n-1][0],ne(l,n//2))
    else:
        return ne(l,n-1)
        an[n-1][l-1]=ne(l,n-1)
for i in range(q):
    print(ne(c[i],b[i]))

Submission status: Wrong Answer

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

N = int(input())
VW = [[0,0]] + [list(map(int,input().split())) for i in range(N)]
Q = int(input())
vL = [list(map(int,input().split())) for i in range(Q)]

def dpinit(ps, val=0):
    res = [val for i in [0]*ps[-1]]
    for i in ps[:-1][::-1]:
        res = [res[:] for k in [0]*i]
    return res

maxL = 10**5
dp = dpinit((N+1,maxL + 2),0)
ans = []
visited = [False] * (N+1)
visited[0] = True
for v,L in vL:
    orgv = v
    seq = []
    while v:
        if visited[v]:
            seq.append(v)
            seq.append(v//2)
            break
        visited[v] = True
        seq.append(v)
        v //= 2
    seq = [0] + seq[::-1]
    for s,ns in zip(seq,seq[1:]):
        V,W = VW[ns]
        for i in range(W):
            dp[ns][i] = dp[s][i]
        for i in range(W,maxL+2):
            dp[ns][i] = max(dp[s][i], dp[s][i-W] + V)
    ans.append(dp[orgv][L])

for a in ans:
    print(a)

Submission status: Wrong Answer

Solution code:
n=int(input())
v=list()
w=list()
dp=list()
for i in range(n):
    a,b=map(int,input().split())
    v.append(a)
    w.append(b)
q=int(input())

def dp(V,L):
    if V==1:
        if w[0]<=L:
            return(v[0])
        else:
            return(0)
    elif L<0:
        return(-10000000)
    else:
        return(max(dp(V//2,L),dp(V//2,L-w[V-1])+v[V-1]))
    
res=list()
for i in range(q):
    u,l=map(int,input().split())
    res.append(dp(u,l))
    
for i in res:
    print(i)

Submission status: Wrong Answer

Solution code:
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, acos, atan, asin, log, log10, gcd
from itertools import permutations, combinations, product, accumulate, combinations_with_replacement
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
#from fractions import gcd
from decimal import *
def debug(*args):
    if debugmode:
        print(*args)
def input(): return sys.stdin.readline().strip()
def STR(): return input()
def INT(): return int(input())
def FLOAT(): return float(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
def lcm(a, b): return a * b // gcd(a, b)
sys.setrecursionlimit(10 ** 9)
inf = sys.maxsize
mod = 10 ** 9 + 7
dx = [0, 1, 0, -1, 1, -1, -1, 1]
dy = [1, 0, -1, 0, 1, -1, 1, -1]
debugmode = True

def parent(num):
    if num == 1:
        return [1]
    n_num = num // 2
    res = parent(n_num)
    res.append(num)
    return res

n = INT()
varr = [0 for _ in range(n + 1)]
warr = [0 for _ in range(n + 1)]
arr = [[] for _ in range(n + 1)]
for i in range(1, n + 1):
    v, w = MAP()
    varr[i] = v
    warr[i] = w
    par = i // 2

q = INT()

for _ in range(q):
    v, l = MAP()
    p = parent(v)
    #print(p)
    num = len(p)
    tmp = 0
    tmp2 = -1
    for j, i in enumerate(reversed(p)):
        if arr[i] != []:
            tmp = i
            tmp2 = j
    var = [varr[i] for i in p]
    war = [warr[i] for i in p]
    dp = [[0 for _ in range(100001)] for _ in range(num + 1)]
    strt = 1
    if tmp != 0:
        dp[tmp2] = [i for i in arr[tmp]]
        strt = tmp + 1
    for i in range(strt, num + 1):
        for j in range(war[i - 1]):
            dp[i][j] = dp[i - 1][j]
        for j in range(war[i - 1], 100001):
            dp[i][j] = max(dp[i][j], dp[i][j - war[i - 1]] + var[i - 1])
        arr[p[i - 1]] = [j for j in dp[i]]
    print(dp[num][l])
    #print(dp[num][:l + 1])

Submission status: Wrong Answer

Solution code:
import bisect
n=int(input())
V=[0]*n
W=[0]*n
for i in range(n):
  V[i],W[i]=map(int,input().split())
q=int(input())
for _ in range(q):
  v,w=map(int,input().split())
  VV=[]
  WW=[]
  nn=0
  while v>=1:
    VV.append(V[v-1])
    WW.append(W[v-1])
    v=v//2
    nn=nn+1
  V1=VV[0:nn//2]
  V2=VV[n//2:nn]
  W1=WW[0:nn//2]
  W2=WW[nn//2:nn]
  VW1=[]
  VW2=[]
  for i in range(2**len(V1)):
    s=format(i,"12b")
    A=[]
    for j in range(len(V1)):
      if s[-1-j]=="1":
        A.append(j)
    s=0
    t=0
    for j in range(len(A)):
      s=s+V1[A[j]]
      t=t+W1[A[j]]
    VW1.append([s,t])
  VW1.sort(reverse=True)
  VW11=[]
  s=10**12
  t=10**12
  for i in range(2**len(V1)):
    if VW1[i][0]<s and VW1[i][1]<t:
      VW11.append([VW1[i][0],VW1[i][1]])
      s=VW1[i][0]
      t=VW1[i][1]
  
  
  for i in range(2**len(V2)):
    s=format(i,"12b")
    A=[]
    for j in range(len(V2)):
      if s[-1-j]=="1":
        A.append(j)
    s=0
    t=0
    for j in range(len(A)):
      s=s+V2[A[j]]
      t=t+W2[A[j]]
    VW2.append([s,t])
  VW2.sort(reverse=True)
  V22=[]
  W22=[]
  s=10**12
  t=10**12
  for i in range(2**len(V2)):
    if VW2[i][0]<s and VW2[i][1]<t:
      V22.append(VW2[i][0])
      W22.append(VW2[i][1])
      s=VW2[i][0]
      t=VW2[i][1]
  V22=V22[::-1]
  W22=W22[::-1]
  ans=0
  for i in range(len(VW11)):
    j=bisect.bisect_right(W22,w-VW11[i][1],lo=0, hi=len(W22))
    if j==0:
      continue
    a=VW11[i][0]+V22[j-1]
    if a>ans:
      ans=a
  print(ans)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[1]:


import math


# In[2]:


N = int(input())
vw = []
for i in range(N):
    tmp = list(map(int, input().split()))
    tmp.append(tmp[0]/tmp[1])
    vw.append(tmp)
Q = int(input())


# In[28]:


def func(vw, v,l):
    mylist = [vw[v//(2**x)-1] for x in range(int(math.log2(v)+1))]
    mylist_s = sorted(mylist, key=lambda x: x[2], reverse=True)
    
    ans = 0
    rest = l
    for i in range(len(mylist_s)):
        if rest>= mylist_s[i][1]:
            ans += mylist_s[i][0]
            rest -= mylist_s[i][1]
    print(ans)


# In[29]:


for p in range(Q):
    v, l = map(int,input().split())
    func(vw, v, l)


# In[ ]:

Submission status: Wrong Answer

Solution code:
n=int(input())
v=list()
w=list()
dp=list()
for i in range(n):
    a,b=map(int,input().split())
    v.append(a)
    w.append(b)
q=int(input())

def dp(V,L):
    if V==1:
        if w[0]<=L:
            return(v[0])
        else:
            return(0)
    elif L<=0:
        return(-10000000000)
    else:
        return(max(dp(V//2,L),dp(V//2,L-w[V-1])+v[V-1]))
    
res=list()
for i in range(q):
    u,l=map(int,input().split())
    res.append(dp(u,l))
    
for i in res:
    print(i)

Submission status: Wrong Answer

Solution code:
n=int(input())
v=list()
w=list()
dp=list()
for i in range(n):
    a,b=map(int,input().split())
    v.append(a)
    w.append(b)
q=int(input())

def dp(V,L):
    if V==1:
        if w[0]<=L:
            return(v[0])
        else:
            return(0)
    elif L<=0:
        return(0)
    else:
        return(max(dp(V//2,L),dp(V//2,L-w[V-1])+v[V-1]))
    
res=list()
for i in range(q):
    u,l=map(int,input().split())
    res.append(dp(u,l))
    
for i in res:
    print(i)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python
# coding: utf-8

# In[1]:


import math


# In[2]:


N = int(input())
vw = []
for i in range(N):
    tmp = list(map(int, input().split()))
    tmp.append(tmp[0]/tmp[1])
    vw.append(tmp)
Q = int(input())


# In[15]:


def func(vw, v,l):
    mylist = [vw[2**(x)-1] for x in range(int(math.log2(v)+1))]
    mylist_s = sorted(mylist, key=lambda x: x[2], reverse=True)

    ans = 0
    rest = l
    for i in range(len(mylist_s)):
        ans += mylist_s[i][0]*(rest//mylist_s[i][1])
        rest -= (rest//mylist_s[i][1])*mylist_s[i][1]
    print(ans)


# In[16]:


for p in range(Q):
    v, l = map(int, input().split())
    func(vw, v, l)


# In[ ]:

Submission status: Wrong Answer

Solution code:
import math
N = int(input())
vw = [0] * N
for i in range(N):
  vw[i] = list(map(int, input().split()))
  
def knap(v, L):
  x = int(math.log(v, 2))
  dp = [[0] * (L + 1) for i in range(x + 2)]
  i = 0
  while v >= 1:
    now = vw[v - 1]
    for j in range(1, L + 1):
      if j - now[1] >= 0: 
        dp[i + 1][j] = max(dp[i][j - now[1]] + now[0], dp[i][j])
    i += 1
    v = int(v / 2)
    #print(v, x)
  return dp[-1][-1]

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

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    def dp_all(lis, l):
        res = [(0,0)]
        for v,w in lis:
            res += [(sv+v,sw+w) for (sv,sw) in res if sw+w <= l]
        return max(res)[0]

    def dp(lis, _lis, l):
        liss = [(0,0)]
        for v,w in lis:
            liss += [(sw+w,sv+v) for (sw,sv) in liss if sw+w <= l]
        ans = 0
        res = [(0,0)]
        for v,w in _lis:
            res += [(sw+w,sv+v) for (sw,sv) in res if sw+w <= l]
        res.sort(key = lambda x:(x[0],-x[1]))
        res_sw = []
        res_sv = []
        maxv = 0
        for i in range(len(res)):
            w,v = res[i]
            if v < maxv:
                continue
            res_sw.append(w)
            res_sv.append(v)
            maxv = v
        for sw,sv in liss:
            j = bisect.bisect_right(res_sw, l-sw)-1
            s = sv+res_sv[j]
            if ans < s:
                ans = s
        return ans

    n = I()
    g = [None]*(n+1)
    for i in range(1,n+1):
        v,w = LI()
        g[i] = (v,w)
    q = I()
    m = n.bit_length()>>1
    for _ in range(q):
        x,l = LI()
        h = x.bit_length()
        lis = []
        bit = 0
        t = 0
        while x:
            if t+m == h:
                bit = x
            lis.append(g[x])
            x >>= 1
            t += 1
        if h <= m:
            print(dp_all(lis,l))
        else:
            print(dp(lis[:-m],lis[-m:],l))
    return

#Solve
if __name__ == "__main__":
    solve()