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

N = int(input())
X = [tuple(map(int, input().split())) for _ in range(N)]

d = dict()

@lru_cache(maxsize=None)
def rec(i, j):
    if i == 1:
        return X[0][0] if j >= X[0][1] else 0
    if (i, j) in d:
        return d[(i, j)]

    ret = rec(i // 2, j)
    if j >= X[i - 1][1]:
        ret = max(ret, rec(i // 2, j - X[i - 1][1]) + X[i - 1][0])
    d[(i, j)] = ret
    return ret


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

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')

#solve
def solve():
    n = II()
    vw = LIR(n)
    dp = [{i} for i in range(1 << n.bit_length() + 1)]
    for i in range(1, (1 << (n.bit_length() - 1))):
        dp[2 * i] |= dp[i]
        dp[2 * i + 1] |= dp[i]
    for i in range(1, n+1):
        t = dp[i]
        dp[i] = []
        for j in list(t):
            v, w = vw[j - 1]
            dp[i].append((v, w))
    for _ in range(II()):
        v, L = LI()
        t = dp[v]
        n1 = len(t) // 2
        n2 = len(t) - n1
        vw1 = t[:n1]
        vw2 = t[n1:]
        d1 = defaultdict(int)
        d2 = defaultdict(int)
        lis1 = []
        lis2 = []
        fullserch1 = itertools.product(range(2), repeat=n1)
        fullserch2 = itertools.product(range(2), repeat=n2)
        ans = 0
        for fulls in fullserch1:
            v, w = [0] * 2
            for i, full in enumerate(fulls):
                if full:
                    v += vw1[i][0]
                    w += vw1[i][1]
            d1[w] = max(d1[w], v)
        pre = -1
        l = list(d1.items())
        l.sort(key=lambda x: x[0])
        for key, value in l:
            if value > pre:
                lis1.append(key)
                pre = value

        for fulls in fullserch2:
            v, w = [0] * 2
            for i, full in enumerate(fulls):
                if full:
                    v += vw2[i][0]
                    w += vw2[i][1]
            d2[w] = max(d2[w], v)
        pre = -1
        l = list(d2.items())
        l.sort(key=lambda x: x[0])
        for key, value in l:
            if value > pre:
                lis2.append(key)
                pre = value

        for l1 in lis1:
            x = bisect_right(lis2, L - l1) - 1
            if x == -1:
                continue
            ans = max(ans, d1[l1]+d2[lis2[x]])

        print(ans)
    return


#main
if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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
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
Q = int(input())
for i in range(Q):
    V,L = map(int,input().split())
    ans = 0
    for w,v in DP[V-1].items():
        if w <= L:
            ans = max(ans,v)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def num2bi(x, k):
  out=format(x, '0'+str(k)+'b')
  return out

N=int(input())
V=[0 for _ in range(N+1)]
W=[0 for _ in range(N+1)]
for i in range(N):
  v, w=input().split()
  V[i+1]=int(v)
  W[i+1]=int(w)
  
Q=int(input())
for i in range(Q):
  u, L=input().split()
  u=int(u)
  L=int(L)
  
  Vt=[]
  Wt=[]
  while u>0:
    Vt.append(V[u])
    Wt.append(W[u])
    u//=2
    
  out=0
  q=len(Vt)
  for i in range(2**q):
    tmp=num2bi(i, q)
    Vtmp=sum([Vt[i] for i in range(q) if tmp[i]=='1'])
    Wtmp=sum([Wt[i] for i in range(q) if tmp[i]=='1'])
    if Wtmp<=L and Vtmp>out:
      out=Vtmp
      
  print(out)

Submission status: Time Limit Exceeded

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**8-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: Time Limit Exceeded

Solution code:
n = int(input())

#iまでのアイテムで合計がL以下の最大値
dp = [[0 for j in range(10**5+1)] for _ in range(2 ** 10 + 1)]
vwl = [list(map(int,input().split())) for _ in range(n)]

for i in range(min(2**10, n)):
    v, w = vwl[i]
    for j in range(10**5+1):
        if j - w >= 0:
            dp[i+1][j] = max(dp[(i+1) // 2][j-w] + v, dp[(i+1) // 2][j])
        else:
            dp[i+1][j] = dp[(i+1) // 2][j]

from itertools import product
q = int(input())
for _ in range(q):
    v,l = map(int,input().split())
    items = []
    while v > 2**10:
        items.append(v)
        v //= 2
    ans = dp[v][l]
    for bits in product([0, 1], repeat=len(items)):
        weight = 0
        value = 0
        for idx, bit in enumerate(bits):
            weight += vwl[items[idx]][1] * bit
            value += vwl[items[idx]][0] * bit
        if weight > l:
            continue
        ans = max(dp[v][l-weight]+value, ans)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
VW = [list(map(int,input().split())) for _ in range(N)]
import math

Q = int(input())
for _ in range(Q):
  v,L = map(int,input().split())
  N = int(math.log2(v)) + 1
  dp = [[0] * (L+1) for _ in range(N+1)]
  dp[0][0] = 0
  for i in range(1,N+1):
    V,W = VW[v-1]
    v //= 2
    for j in range(L+1):
      if W<=j:
        dp[i][j] = max(dp[i-1][j], dp[i-1][j-W] + V)
      else:
        dp[i][j] = dp[i-1][j]
        
  print(dp[-1][-1])

Submission status: Time Limit Exceeded

Solution code:
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys
input = sys.stdin.readline
ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda :int(input())
ip = lambda :[int(w) for w in input().split()]

def knapsack(W,wt,val,n): 
	K = [[0 for x in range(W + 1)] for x in range(n + 1)] 
	for i in range(n + 1): 
		for w in range(W + 1): 
			if i == 0 or w == 0: 
				K[i][w] = 0
			elif wt[i-1] <= w: 
				K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]) 
			else: 
				K[i][w] = K[i-1][w] 
	return K[n][W] 

n = inp()
v = [0]*(n+1)
w = [0]*(n+1)
for i in range(1,n+1):
    v[i],w[i] = ip()
for _ in range(inp()):
    i,L = ip()
    nv,nw = [],[]
    while i:
        nv.append(v[i])
        nw.append(w[i])
        i >>= 1
    print(knapsack(L,nw,nv,len(nv)))

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
vws = []
for _ in range(n):
    v, w = map(int, input().split())
    vws.append((v, w))
q = int(input())
querys = []
for _ in range(q):
    v, l = map(int, input().split())
    querys.append((v, l))
for ver, l in querys:
    vw = []
    while ver>0:
        vw.append(vws[ver-1])
        ver//=2
    dp = {0: 0}
    for va, we in vw:
        newdp = dp.copy()
        for w in dp:
            if w+we>l:
                continue
            if w+we in newdp.keys():
                if newdp[w+we]<dp[w]+va:
                    newdp[w+we] = dp[w]+va
            else:
                newdp[w+we] = dp[w]+va
        dp = newdp
    print(max(dp.values()))

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A = [(0,0)]
for i in range(N):
  v,w = map(int,input().split()) #価値重さ
  A.append((v,w))
  
dp = [0 for _ in range(20)]
#i個目まで取った時の最大値
INF = float("inf")
Q = int(input())
for case in range(Q):
  start,weight = map(int,input().split())
  dp = [[-INF for i in range(weight+1)] for j in range(20)]
  for unko in range(weight+1):
    #print(unko,weight)
    dp[0][unko] = 0
  #i個目までで重さweight以下の最大値
  n = start.bit_length()
  i = start*1
  for b in range(n):
    for j in range(weight+1):
      if j >= A[i][1]:
        dp[b+1][j] = max(dp[b][j],dp[b][j-A[i][1]]+A[i][0])
      else:
        dp[b+1][j] = dp[b][j]
    i = i//2
  #print(dp)
  print(dp[n][weight])

Submission status: Time Limit Exceeded

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n = I()
V = []
W = []
for _ in range(n):
    v, w = LI()
    V.append(v)
    W.append(w)

q = I()
for _ in range(q):
    v, L = LI()
    m = int(math.log2(v)) + 1
    dp = [[0]*(L+1) for _ in range(m+1)]
    idx = v
    for i in range(m):
        for j in range(L+1):
            if j < W[idx-1]:
                dp[i+1][j] = dp[i][j]
            else:
                dp[i+1][j] = max(dp[i][j],dp[i][j-W[idx-1]] + V[idx-1])
        idx //= 2
    print(dp[-1][L])

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
VW = [tuple(map(int,input().split())) for i in range(N)]
Q = int(input())
VL = [tuple(map(int,input().split())) for i in range(Q)]

def solve():
    ans = []
    for i,(u,l) in enumerate(VL):
        dp = {0:0}
        while u > 0:
            v,w = VW[u-1]
            dp2 = {}
            for w0,v0 in dp.items():
                if w0 in dp2:
                    dp2[w0] = max(dp2[w0], v0)
                else:
                    dp2[w0] = v0
                if w0+w > l: continue
                if w0+w in dp2:
                    dp2[w0+w] = max(dp2[w0+w], v0+v)
                else:
                    dp2[w0+w] = v0+v
            dp = dp2
            u //= 2
        ans.append(max(dp.values()))
    print(*ans, sep='\n')
solve()

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict
 
n = int(input())
ns = [0]
for i in range(n):
    v, w = map(int, input().split())
    ns.append((v, w))
q = int(input())
for i in range(q):
    v, l = map(int, input().split())
    nums = []
    while v != 1:
        nums.append(ns[v])
        v //= 2
    nums.append(ns[1])
    dp = defaultdict(lambda: float('inf'))
    dp[0] = 0
    for v, w in nums:
        for nv, nw in list(dp.items()):
            if nw + w <= l:
                dp[nv + v] = min(dp[nv + v], nw + w)
    print(max(dp))

Submission status: Time Limit Exceeded

Solution code:
import copy
def main():
    N = int(input())
    l = []
    for _ in range(N):
        v, w = map(int, input().split())
        l.append((v, w))
    Q = int(input())
    dp = []
    t = set()
    t.add(l[0])
    dp.append(0)
    dp.append(t)
    for i in range(1, N):
        t = copy.deepcopy(dp[(int((i+1)/2))])
        for j in dp[int((i+1)/2)]:
            t.add((j[0]+l[i][0], j[1]+l[i][1]))
        t.add(l[i])
        dp.append(t)
    for _ in range(Q):
        v, L = map(int, input().split())
        m = 0
        for i in dp[v]:
            if i[1] <= L:
                m = max(m, i[0])
        print(m)

main()

Submission status: Time Limit Exceeded

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 = []
    v *= 2
    while v:
        v //= 2
        seq.append(v)
        if visited[v]:
            break
        visited[v] = True
    seq = 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: Time Limit Exceeded

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**10-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: Time Limit Exceeded

Solution code:
from collections import deque, Counter, defaultdict
from itertools import chain, combinations
import json
# import numpy as np
import bisect
import sys
import math
import bisect
from functools import lru_cache
import itertools

sys.setrecursionlimit(10 ** 8)

M = 10 ** 9 + 7
INF = 10 ** 17


def main():
    # # N, K = [int(a) for a in input().split()]
    # # A = [int(a) for a in input().split()]
    # K=200000
    # # T = int(input())
    # # A = [int(a) for a in input().split()]
    # # T1, T2, T3 = [int(a) for a in input().split()]
    # A = [0]*100000
    #
    # for _ in range(K):
    #     AA = [1] * len(A)
    #     flag = True
    #     for i, ai in enumerate(A):
    #         if ai != len(A):
    #             flag = False
    #         for ii in range(ai):
    #             ii += 1
    #             if i + ii < len(A):
    #                 AA[i + ii] += 1
    #             if i - ii >= 0:
    #                 AA[i - ii] += 1
    #     A = AA
    #     if flag:
    #         return print(888888)
    #     print(A)
    # print(A)
    N = int(input())
    VW = [[int(a) for a in input().split()] for _ in range(N)]
    Q = int(input())
    uL = [[int(a) for a in input().split()] for _ in range(Q)]

    DP = [
        [0] * (100002)
        for _ in range(N)
    ]
    mem = [0] * N

    for u, L in uL:
        parents_index = []
        uu = u
        while True:
            parents_index.append(uu - 1)
            uu = uu // 2
            if uu == 0:
                break
        parents_index.reverse()

        prev = None
        for i in parents_index:
            v, ww = VW[i]
            for w in range(mem[i], L + 1):
                if prev is None:
                    if w >= ww:
                        DP[i][w] = v
                    else:
                        DP[i][w] = 0
                else:
                    if w >= ww:
                        DP[i][w] = max(DP[prev][w - ww] + v, DP[prev][w])
                    else:
                        DP[i][w] = DP[prev][w]
            prev = i
            mem[i] = L + 1
        print(DP[u - 1][L])


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(raw_input())
h = [None for _ in range(n + 1)]
for u in range(n):
	v, w = map(int,raw_input().split(' '))
	h[u + 1] = (v,w)
nq = int(raw_input())
def f(v,l,h):
	dp = [0 for _ in range(l+1)]
	while(v):
		cv, cw = h[v]
		v = v/2
		for ww in range(l,-1,-1):
			if ww - cw >= 0: 
				dp[ww] = max(dp[ww], dp[ww - cw] + cv)
			else:
				break
	return dp[l]
for _ in range(nq):
	v,l = map(int, raw_input().split(' '))
	print f(v,l,h)

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
N = int(input())
VW = [tuple(map(int,input().split())) for i in range(N)]
Q = int(input())
VL = [tuple(map(int,input().split())) for i in range(Q)]

ans = [None] * Q
for i,(u,l) in enumerate(VL):
    dp = {0:0}
    while u > 0:
        v,w = VW[u-1]
        dp2 = {}
        for w0,v0 in dp.items():
            if w0 in dp2:
                dp2[w0] = max(dp2[w0], v0)
            else:
                dp2[w0] = v0
            if w0+w > l: continue
            if w0+w in dp2:
                dp2[w0+w] = max(dp2[w0+w], v0+v)
            else:
                dp2[w0+w] = v0+v
        dp = dp2
        u //= 2
    ans[i] = max(dp.values())
print(*ans, sep='\n')

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
X = [[] for _ in range(N)]
for i in range(N):
    X[i] = list(map(int, input().split()))
Q = int(input())
query = [[] for _ in range(Q)]


for i in range(Q):
    query[i] = list(map(int, input().split()))

for q in query:
    i = q[0]
    W = q[1]
    w = []
    v = []
    while i != 0:
        v.append(X[i-1][0])
        w.append(X[i-1][1])
        i = i//2
    size = len(v)
    dp = [[0]*(W+1) for j in range(size+1)]
    for i in range(size-1,-1,-1):
        for j in range(W+1):
            if j < w[i]:
                dp[i][j] = dp[i+1][j]
            else:
                dp[i][j] = max(dp[i+1][j],dp[i+1][j-w[i]]+v[i])
    print(dp[0][W])

Submission status: Time Limit Exceeded

Solution code:
n = int(raw_input())
h = [None for _ in range(n + 1)]
for u in range(n):
	v, w = map(int,raw_input().split(' '))
	h[u + 1] = (v,w)
nq = int(raw_input())
def f(v,l,h):
	dp = [0 for _ in range(l+1)]
	while(v):
		cv, cw = h[v]
		v = v/2
		for ww in range(l,-1,-1):
			if ww - cw >= 0: dp[ww] = max(dp[ww], dp[ww - cw] + cv)
	return dp[l]
for _ in range(nq):
	v,l = map(int, raw_input().split(' '))
	print f(v,l,h)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
N = int(input())
VW = [list(map(int, input().split())) for _ in range(N)]
Q = int(input())
for _ in range(Q):
  v, L = map(int, input().split())
  vals = deque()
  weis = deque()
  x = v
  while x > 0:
    vals.append(VW[x-1][0])
    weis.append(VW[x-1][1])
    x //= 2
  l = len(vals)
  dp = [[0]*(L+1) for _ in range(l+1)]
  i = 0
  while i < l:
    w = 0
    while w <= L:
      if w >= weis[i]:
        dp[i+1][w] = max(dp[i][w-weis[i]]+vals[i], dp[i][w])
      else:
        dp[i+1][w] = dp[i][w]
      w += 1
    i += 1
  print(dp[l][L])

Submission status: Time Limit Exceeded

Solution code:
import sys

# from https://tjkendev.github.io/procon-library/python/dp/knapsack-meet-in-the-middle.html
def solve(N, W, S):
    # S[i] = (v, w): 価値v, 重さw

    def make(S):
        T = {0: 0}
        for v, w in S:
            # 価値v, 重さw
            T0 = dict(T)
            for k, val in T.items():
                if k+w > W:
                    continue
                if k+w in T0:
                    T0[k+w] = max(T0[k+w], val + v)
                else:
                    T0[k+w] = val + v
            T = T0
        v = 0
        R = []
        for k in sorted(T):
            v = max(v, T[k])
            # (重さk, 重さk以下での価値の最大v)
            R.append((k, v))
        return R

    def solve(T0, T1):
        T0.sort()
        T1.sort(reverse=1)

        it = iter(T1); k1, v1 = next(it)
        yield 0
        for k0, v0 in T0:
            # 重さの和がW以下になるようにスライドする
            while k0 + k1 > W:
                k1, v1 = next(it)
            yield v0 + v1

    # ２つの集合に分けて、それぞれ全列挙
    T0 = make(S[:N//2])
    T1 = make(S[N//2:])

    # 2つの全列挙を元に解を求める
    return max(solve(T0, T1))

def main():
    input = sys.stdin.readline
    N = int(input())
    VW = [0] + [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Ans = []
    for _ in range(Q):
        V, L = map(int, input().split())
        vw = []
        while V > 0:
            vw.append(VW[V])
            V /= 2
        ans = solve(len(vw), L, vw)
        Ans.append(ans)
    print("\n".join(map(str, Ans)))

main()

Submission status: Time Limit Exceeded

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: Time Limit Exceeded

Solution code:
import sys

# i番目の重みws[i], 価値vs[i]


def solve(N, W, ws, vs):
    # S[i] = (v, w): 価値v, 重さw
    *S, = zip(vs, ws)

    def make(S):
        T = {0: 0}
        for v, w in S:
            # 価値v, 重さw
            T0 = dict(T)
            for k, val in T.items():
                if k + w > W:
                    continue
                if k + w in T0:
                    T0[k + w] = max(T0[k + w], val + v)
                else:
                    T0[k + w] = val + v
            T = T0
        v = 0
        R = []
        for k in sorted(T):
            v = max(v, T[k])
            # (重さk, 重さk以下での価値の最大v)
            R.append((k, v))
        return R

    def solve(T0, T1):
        T0.sort()
        T1.sort(reverse=1)

        it = iter(T1)
        k1, v1 = next(it)
        yield 0
        for k0, v0 in T0:
            # 重さの和がW以下になるようにスライドする
            while k0 + k1 > W:
                k1, v1 = next(it)
            yield v0 + v1

    # ２つの集合に分けて、それぞれ全列挙
    T0 = make(S[:N // 2])
    T1 = make(S[N // 2:])

    # 2つの全列挙を元に解を求める
    return max(solve(T0, T1))


def main():
    input = sys.stdin.buffer.readline
    n = int(input())
    vw = [map(int, input().split()) for _ in range(n)]
    given_vs, given_ws = [list(i) for i in zip(*vw)]
    q = int(input())
    for i in range(q):
        v, l = map(int, input().split())
        vs = []
        ws = []
        while True:
            vs.append(given_vs[v - 1])
            ws.append(given_ws[v - 1])
            if v == 1:
                break
            v = v // 2
        print(solve(n, l, ws, vs))


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from  math import ceil,log

N=int(input())
V=[]
W=[]
S=100

for i in range(N):
    v,w=map(int,input().split())
    V.append(v)
    W.append(w)
            
Q=int(input())
for _ in range(Q):
    v,L=map(int,input().split())
    d=ceil(log(v+1,2))
    D=[[0]*(L+1) for _ in range(d+1)]

    w=v
    E=[]
    while w!=0:
        E.append(w)
        w=w>>1
    
    for i in range(1,d+1):
        for w in range(L+1):
            if w>=W[E[-i]-1]:
                D[i][w]=max(D[i-1][w],D[i-1][w-W[E[-i]-1]]+V[E[-i]-1])
            else:
                D[i][w]=D[i-1][w]

    print(D[-1][-1])

Submission status: Time Limit Exceeded

Solution code:
import sys
from operator import itemgetter
from bisect import bisect_left
 
# from https://atcoder.jp/contests/abc032/submissions/3020872
def solve(N, W, DD):
    L = DD[:N / 2]
    M = DD[N / 2:]
    s = len(L)
    t = len(M)
    A = set()
    B = []
    for i in range(1 << s):
        v, w = 0, 0
        for j in range(s):
            if i & (1 << j):
                v += L[j][0]
                w += L[j][1]
        if w <= W:
            A.add((w, v))
    for i in range(1 << t):
        v, w = 0, 0
        for j in range(t):
            if i & (1 << j):
                v += M[j][0]
                w += M[j][1]
        if w <= W:
            B.append((w, v))
    B = sorted(B, key=itemgetter(1, 0))
    value = 0
    maxv = [0]
    for w,v in B:
        maxv.append(max(maxv[-1],v))
    for w, v in A:
        x = bisect_left(B, (W - w + 1, 0))
        if x==0:
            continue
        if maxv[x] + v > value:
            value = maxv[x] + v
    return value
        
def main():
    input = sys.stdin.readline
    N = int(input())
    VW = [0] + [list(map(int, input().split())) for _ in range(N)]
    Q = int(input())
    Ans = []
    for _ in range(Q):
        V, L = map(int, input().split())
        vw = []
        while V > 0:
            vw.append(VW[V])
            V /= 2
        ans = solve(N, L, vw)
        Ans.append(ans)
    print("\n".join(map(str, Ans)))

main()

Submission status: Time Limit Exceeded

Solution code:

n = int(raw_input())
h = {}
for u in range(n):
	v, w = map(int,raw_input().split(' '))
	h[u + 1] = (v,w)

nq = int(raw_input())

def f(v,l,h):
	dp = [0 for _ in range(l+1)]
	while(v):
		cv, cw = h[v]
		v = v/2
		for ww in range(l,-1,-1):
			if ww - cw >=0: dp[ww] = max(dp[ww], dp[ww - cw] + cv)
	return dp[l]
for _ in range(nq):
	v,l = map(int, raw_input().split(' '))
	print f(v,l,h)

Submission status: Time Limit Exceeded

Solution code:
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
    data = [(0,0)]
    for _ in range(n):
        v,w = map(int,ipt().split())
        data.append((v,w))
    q = int(ipt())
    for _ in [0]*q:
        dp = defaultdict(int)
        dp[0] = 0
        v,l = map(int,ipt().split())
        while v != 0:
            vi,wi = data[v]
            cng = queue.Queue()
            dpi = set(dp.items())
            for ik,iv in dpi:
                if ik+wi <= l:
                    if dp[ik+wi] < dp[ik]+vi:
                        cng.put((ik+wi,dp[ik]+vi))
            while not cng.empty():
                ww,vv = cng.get()
                dp[ww] = vv
            v >>= 1
        print(max(dp.values()))
    return

if __name__ == '__main__':
    main()