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:
#!/usr/bin/env python3
import sys
from collections import defaultdict
INF = float("inf")


def main():
    # 事前にDPする。必ず上からDPする
    # すでに計算済みのところはスキップする
    # N*Lの配列を用意するとダメなので、
    # 辞書で対応したい。要素数は高々log(N)だと思う。
    # 頂点ごとに辞書を持つことになる。
    N = int(input())
    V = [-1]
    W = [-1]
    for i in range(N):
        a, b = map(int, input().split())
        V.append(a)
        W.append(b)

    Q = int(input())
    v = []
    L = []
    for i in range(Q):
        a, b = map(int, input().split())
        v.append(a)
        L.append(b)

    LMAX = max(L)

    DP = [None]*(N+1)

    for q in range(Q):
        order = []
        while v[q] > 0:
            order.append(v[q])
            v[q] >>= 1

        pre = None
        for u in reversed(order):
            if DP[u] is None:
                # 重さがkeyになるときの価値の総和value
                if pre is None:
                    DP[u] = defaultdict(int)
                    DP[u][W[u]] = V[u]
                else:
                    DP[u] = pre.copy()
                    for k in sorted(pre.keys(), reverse=True):
                        if k+W[u] <= LMAX:
                            DP[u][k+W[u]] = max(pre[k]+V[u], DP[u][k+W[u]])
            pre = DP[u]
        m = 0
        for k, val in DP[order[0]].items():
            if k <= L[q]:
                m = max(m, val)
        print(m)

    return


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] for _ in range(n2)]
    tab[0] = [0] * ma
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        aa, bb = vw[i]
        a = tab[j]
        tab[i] = a[:bb] + [0] * (ma - bb)
        b = tab[i]
        for k in range(bb, ma):
            b[k] = max((b[k - 1], a[k - bb] + aa, a[k]))

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] for _ in range(n2)]
    tab[0] = [0] * ma
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        aa, bb = vw[i]
        a = tab[j]
        tab[i] = a[:bb]
        b = tab[i]
        for k in range(bb, ma):
            b.append(max((b[k - 1], a[k - bb] + aa, a[k])))

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] for _ in range(n2)]
    tab[0] = [0] * ma
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        l = 0
        aa, bb = vw[i]
        a = tab[j]
        tab[i] = a[:bb] + [0] * (ma - bb)
        for k in range(bb, ma):
            tab[i][k] = max((tab[i][k - 1], a[k - bb] + aa, a[k]))

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] * ma for _ in range(n2)]
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        l = 0
        aa, bb = vw[i]
        a = tab[j]
        tab[i][:bb] = a[:bb]
        for k in range(bb, ma):
            l = max((l, a[k - bb] + aa, a[k]))
            tab[i][k] = l

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] * ma for _ in range(n2)]
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        a = tab[j][:]
        l = 0
        aa, bb = vw[i]
        aaa = tab[j]
        for k in range(bb, ma):
            l = max((l, aaa[k - bb] + aa, a[k]))
            a[k] = l
        tab[i] = a

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] * ma for _ in range(n2)]
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        l = 0
        aa, bb = vw[i]
        a = tab[j]
        b = tab[i]
        for k in range(bb):
            b[k] = a[k]
        for k in range(bb, ma):
            l = max((l, a[k - bb] + aa, a[k]))
            b[k] = l

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] * ma for _ in range(n2)]
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        l = 0
        aa, bb = vw[i]
        a = tab[j]
        for k in range(bb):
            tab[i][k] = a[k]
        for k in range(bb, ma):
            l = max((l, a[k - bb] + aa, a[k]))
            tab[i][k] = l

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
from decimal import Decimal


INF = 10 ** 13
sys.setrecursionlimit(2147483647)
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
L = []
for i in range(n):
    v, w = LI()
    L += [(v, w)]

q = I()
QD = defaultdict(list)
for k in range(q):
    vz, l = LI()
    QD[vz - 1] += [(l, k)]


def euler_tour(G, root=0):
    n = len(G)
    euler = []
    dq = deque([root])
    dq2 = deque()
    visited = [0] * n
    while dq:
        u = dq.pop()
        euler += [u]
        if visited[u]:
            continue
        for v in G[u]:
            if visited[v]:
                dq += [v]
            # [親頂点、子頂点、子頂点、。。。]と入れていく.その後連結
            else:
                dq2 += [v]
        dq.extend(dq2)
        dq2 = deque()
        visited[u] = 1
    return euler


G = [[] for _ in range(n)]
for i in range(1, n):
    G[i] += [(i - 1) // 2]
    G[(i - 1) // 2] += [i]

euler = euler_tour(G)

ans = [0] * q
D = defaultdict(int)
DD = deque([{0:0}])
pre = -1
for j in euler:
    if pre < j:
        D2 = defaultdict(int)
        D = DD[-1]
        vi, wi = L[j]
        for wj in D:
            D2[wj + wi] = D[wj] + vi
            D2[wj] = max(D2[wj], D[wj])
        DD += [D2]
        LL = [0] + sorted(list(D2.keys()))
        for li, ki in QD[j]:
            ai = D2[LL[bisect_right(LL, li) - 1]]
            ans[ki] = ai
    else:
        DD.pop()
    pre = j

for z in ans:
    print(z)

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] * ma for _ in range(n2)]
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        l = 0
        aa, bb = vw[i]
        for k in range(bb):
            tab[i][k] = tab[j][k]
        for k in range(bb, ma):
            l = max((l, tab[j][k - bb] + aa, tab[j][k]))
            tab[i][k] = l

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [[0] * ma for _ in range(n2)]
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        a = tab[j][:]
        l = 0
        aa, bb = vw[i]
        for k in range(bb, ma):
            l = max((l, tab[j][k - bb] + aa, tab[j][k]))
            tab[i][k] = l

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys


def main():
    input = sys.stdin.readline
    n = int(input())
    vw = [list(map(int, input().split())) for _ in range(n)]

    n2 = max(1, min(n, int(n ** 0.5)))

    ma = 10 ** 5 + 1
    tab = [0 for _ in range(n2)]
    tab[0] = [0] * ma
    for i in range(vw[0][1], ma):
        tab[0][i] = vw[0][0]

    for i in range(1, n2):
        j = (i - 1) // 2
        a = tab[j][:]
        l = 0
        aa, bb = vw[i]
        for k in range(bb, ma):
            l = max((l, tab[j][k - bb] + aa, a[k]))
            a[k] = l
        tab[i] = a

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


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
from decimal import Decimal


INF = 10 ** 13
sys.setrecursionlimit(2147483647)
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
L = []
for i in range(n):
    v, w = LI()
    L += [(v, w)]

q = I()
QD = defaultdict(list)
for k in range(q):
    vz, l = LI()
    QD[vz - 1] += [(l, k)]


def euler_tour(G, root=0):
    n = len(G)
    euler = []
    dq = deque([root])
    dq2 = deque()
    visited = [0] * n
    while dq:
        u = dq.pop()
        euler += [u]
        if visited[u]:
            continue
        for v in G[u]:
            if visited[v]:
                dq += [v]
            # [親頂点、子頂点、子頂点、。。。]と入れていく.その後連結
            else:
                dq2 += [v]
        dq.extend(dq2)
        dq2 = deque()
        visited[u] = 1
    return euler


G = [[] for _ in range(n)]
for i in range(1, n):
    G[i] += [(i - 1) // 2]
    G[(i - 1) // 2] += [i]

euler = euler_tour(G)

ans = [0] * q
D = defaultdict(int)
DD = deque([{0:0}])
pre = -1
for j in euler:
    if pre < j:
        D2 = defaultdict(int)
        D = DD[-1]
        vi, wi = L[j]
        for wj in D:
            D2[wj + wi] = D[wj] + vi
        for k in D:
            D2[k] = max(D2[k], D[k])
        DD += [D2]
        LL = [0] + sorted(list(D2.keys()))
        for li, ki in QD[j]:
            ai = D2[LL[bisect_right(LL, li) - 1]]
            ans[ki] = ai
    else:
        DD.pop()
    pre = j

for z in ans:
    print(z)

Submission status: Wrong Answer

Solution code:
import numpy as np
import sys
input = sys.stdin.readline
from numba import njit


N = int(input())
VW = []
for _ in range(N):
    V, W = map(int, input().split())
    VW.append([V, W])

VW = np.array(VW).reshape(N,2)
V = VW[:,0]
W = VW[:,1]

Q = int(input())
vL = []
for _ in range(Q):
    v, L = map(int, input().split())
    vL.append([v, L])


# inpt N:number W:maxweight
@njit
def solveDP(N, W, value, weight):
    dp = np.zeros((N+1, W+1))
    
    for i in range(N):
        for w in range(W+1):
            if w >= weight[i]:
                dp[i + 1, w] = max(dp[i, w - weight[i]] + value[i], dp[i, w])
            else:
                dp[i + 1, w] = dp[i, w]
    
    return dp[N , W ]
    

for vls in vL:
    v, L = vls
    vv = v
    
    value = [V[v - 1]]
    weight = [W[v - 1]]
    
    while vv > 0:
        vv = vv//2
        value.append(V[vv - 1])
        weight.append(W[vv - 1])
    
    # answer
    print(solveDP(len(value),L,value,weight))

Submission status: Wrong Answer

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

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

dp1=[[0,0] for i in range(2**9)]
dp2=[[0,0] for i in range(2**9)]
for _ in range(int(input())):
    v,l=map(int,input().split())
    t=[]
    while v>0:
        t.append(vw[v])
        v//=2
    
    dp1=[[0,0] for i in range(2**9)]
    dp2=[[0,0] for i in range(2**9)]
    n=len(t)
    dp1[0][0]=0
    dp1[0][1]=0
    k=n//2
    for i in range(1,2**k):
        m=i.bit_length()
        dp1[i][0]=dp1[i-2**(m-1)][0]+t[m-1][1]
        dp1[i][1]=dp1[i-2**(m-1)][1]+t[m-1][0]

    dp2[0][0]=0
    dp2[0][1]=0
    for i in range(1,2**(n-k)):
        m=i.bit_length()
        dp2[i][0]=dp2[i-2**(m-1)][0]+t[m-1+k][1]
        dp2[i][1]=dp2[i-2**(m-1)][1]+t[m-1+k][0]

    dp1.sort()
    dp2.sort()
    ans=0
    for i in range(0,2**9):
        res=dp1[i][1]
        id=bisect.bisect_right(dp2,[l-dp1[i][0],10**20])
        if id!=0:
            res+=dp2[id-1][1]
            ans=max(ans,res)
    print(ans)

Submission status: Wrong Answer

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

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

dp1=[[0,0] for i in range(2**9)]
dp2=[[0,0] for i in range(2**9)]
for _ in range(int(input())):
    v,l=map(int,input().split())
    t=[]
    while v>0:
        t.append(vw[v])
        v//=2
    
    dp1=[[0,0] for i in range(2**9)]
    dp2=[[0,0] for i in range(2**9)]
    n=len(t)
    dp1[0][0]=0
    dp1[0][1]=0
    k=n//2
    for i in range(1,2**k):
        m=i.bit_length()
        dp1[i][0]=dp1[i-2**(m-1)][0]+t[m-1][1]
        dp1[i][1]=dp1[i-2**(m-1)][1]+t[m-1][0]

    dp2[0][0]=0
    dp2[0][1]=0
    for i in range(1,2**(n-k)):
        m=i.bit_length()
        dp2[i][0]=dp2[i-2**(m-1)][0]+t[m-1+k][1]
        dp2[i][1]=dp2[i-2**(m-1)][1]+t[m-1+k][0]

    dp1.sort()
    dp2.sort()
    ans=0
    for i in range(0,2**9):
        res=dp1[i][1]
        id=bisect.bisect_right(dp2,[l-dp1[i][0],10**20])
        if id!=0:
            res+=dp2[id-1][1]
            ans=max(ans,res)
    print("ANS")
    print(ans)

Submission status: Wrong Answer

Solution code:
def calc_rec(node):
    if node in D.keys():
        return D[node]

    do_list=[node]
    while True:
        node//=2
        if node in D.keys():
            break
        else:
            do_list.append(node)
    for node in reversed(do_list):
        new_dp =calc_dp_step(node)
    return new_dp


def calc_dp_step(node_id):
    cur_dp = D[node_id//2]
    (node_val,node_weight) = nodes[node_id]

    new_dp=[0]*Vmax
    for j in range(Vmax):
        if j < node_weight: 
            new_dp[j] = cur_dp[j]
        else:
            new_dp[j] = max(cur_dp[j],cur_dp[j-node_weight]+node_val)
    D[node_id]=new_dp
    return new_dp

N = int(input())

nodes=[None]
for _ in range(N):
    v,w = map(int,input().split())
    nodes.append((v,w))

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

D=dict()
Vmax=10**5+1

#DP[weight]=val
D[0]=[0]*Vmax
Q_ans=dict()
for v,L in query:
    if v//2 not in D.keys():
        cur_dp = calc_rec(v//2)
    cur_val,cur_weight = nodes[v]
    print(D[v//2][L-cur_weight]+cur_val)

Submission status: Wrong Answer

Solution code:
import sys
class Knapsack:
    def __init__(self, VW):
        self.VW = VW
        self.VW.sort(key=lambda vw: vw[0] / vw[1], reverse=True)
        self.n = len(VW)
 
    def solve(self, capacity, ok=0):
        self.ok = ok
        self.capacity = capacity
        return self._dfs(0, 0, 0)
 
    def _dfs(self, i, v_now, w_now):
        if i==self.n:
            self.ok = max(self.ok, v_now)
            return v_now
        ng, f = self._solve_relaxation(i, self.capacity-w_now)
        ng += v_now
        if f:
            self.ok = max(self.ok, ng)
            return ng
        if ng < self.ok:
            return -float("inf")
        res = -float("inf")
        v, w = self.VW[i]
        if w_now + w <= self.capacity:
            res = max(res, self._dfs(i+1, v_now + v, w_now + w))
        res = max(res, self._dfs(i+1, v_now, w_now))
        return res
 
    def _solve_relaxation(self, i, capacity):
        res = 0
        f = True
        for v, w in self.VW[i:]:
            if capacity == 0:
                break
            if w <= capacity:
                capacity -= w
                res += v
            else:
                f = False
                res += v * (capacity / w)
                break
        return res, f
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
        knapsack = Knapsack(vw)
        ans = knapsack.solve(L)
        Ans.append(ans)
    print("\n".join(map(str, Ans)))

main()

Submission status: Wrong Answer

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, cos, radians, pi, sin
from operator import mul
from functools import reduce
from operator import mul
from decimal import Decimal


INF = 10 ** 13
sys.setrecursionlimit(2147483647)
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
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)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]


n = I()
L = []
for i in range(n):
    v, w = LI()
    L += [(v, w)]

q = I()
QD = defaultdict(list)
for k in range(q):
    vz, l = LI()
    QD[vz - 1] += [(l, k)]


def euler_tour(G, root=0):
    n = len(G)
    euler = []
    dq = deque([root])
    dq2 = deque()
    visited = [0] * n
    while dq:
        u = dq.pop()
        euler += [u]
        if visited[u]:
            continue
        for v in G[u]:
            if visited[v]:
                dq += [v]
            # [親頂点、子頂点、子頂点、。。。]と入れていく.その後連結
            else:
                dq2 += [v]
        dq.extend(dq2)
        dq2 = deque()
        visited[u] = 1
    return euler


G = [[] for _ in range(n)]
for i in range(1, n):
    G[i] += [(i - 1) // 2]
    G[(i - 1) // 2] += [i]

euler = euler_tour(G)

ans = [0] * q
D = defaultdict(int)
DD = deque([{0:0}])
pre = -1
for j in euler:
    if pre < j:
        D2 = defaultdict(int)
        D = DD[-1]
        vi, wi = L[j]
        for wj in D:
            D2[wj + wi] = D[wj] + vi
        for k in D:
            D2[k] = max(D2[k], D[k])
        DD += [D2]
        LL = [0] + sorted(list(D2.keys()))
        for li, ki in QD[j]:
            ai = D2[LL[bisect_right(LL, li) - 1]]
            ans[ki] = ai
    else:
        DD.pop()


for z in ans:
    print(z)

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)))

ma = 2 * 10 ** 5
tab = [[0] * ma]
for i in range(wv[0][0], ma):
    tab[0][i] = wv[0][1]

for i in range(1, n2):
    j = (i - 1) // 2
    a = tab[j][:]
    l = 0
    for k in range(wv[i][0], ma):
        l = max(l, tab[j][k - wv[i][0]] + wv[i][1])
        a[k] = l
    tab.append(a)

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

Submission status: Wrong Answer

Solution code:
import bisect
import os
from collections import defaultdict

import itertools
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353

# ガウス記号！おぼえた

N = int(sys.stdin.buffer.readline())
VW = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(N)]
Q = int(sys.stdin.buffer.readline())
VL = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(Q)]

VW = [(0, 0)] + VW
D = N.bit_length()
queries = defaultdict(list)

for i, (v, l) in enumerate(VL):
    queries[v].append((l, i))
ans = [-1] * Q


def solve(wv, i):
    # print(wv,i)
    if not queries[i]:
        return

    wv1 = []
    prev_v = -INF
    for w, v in sorted(wv):
        v = max(prev_v, v)
        wv1.append((w, v))
        prev_v = v

    wva = []
    for j in range(len(wv).bit_length() - i.bit_length()):
        wva.append((VW[i >> j][1], VW[i >> j][0]))

    wv = []
    for choices in itertools.product([True, False], repeat=len(wva)):
        ws, vs = 0, 0
        for j, (w, v) in enumerate(wva):
            if choices[j]:
                ws += w
                vs += v
        wv.append((ws, vs))

    wv2 = []
    prev_v = -INF
    for w, v in sorted(wv):
        v = max(prev_v, v)
        wv2.append((w, v))
        prev_v = v

    for ql, qi in queries[i]:
        ret = 0
        for w2, v2 in wv2:
            idx = bisect.bisect_left(wv1, (ql - w2 + 1, -INF)) - 1
            if idx >= 0:
                ret = max(ret, wv1[idx][1] + v2)
        ans[qi] = ret


def dfs(d, wv, p):
    if p > N:
        return
    solve(wv, p)
    for i in (p << 1, (p << 1) + 1):
        if i > N:
            break
        if d <= MAX_D:
            next_wv = []
            for w, v in wv:
                next_wv.append((w + VW[i][1], v + VW[i][0]))
            dfs(d + 1, wv + next_wv, i)
        else:
            dfs(d + 1, wv, i)


MAX_D = 9
dfs(1, [(0, 0), (VW[1][1], VW[1][0])], 1)
print(*ans, sep='\n')