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: Runtime Error

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=[]
  while v>=1:
    VV.append(V[v-1])
    WW.append(W[v-1])
    v=v//2
  V1=VV[0:n//2]
  V2=VV[n//2:n]
  W1=WW[0:n//2]
  W2=WW[n//2:n]
  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: Runtime Error

Solution code:
/*
    author:  Maksim1744
    created: 13.06.2020 15:29:39
*/

#include <bits/stdc++.h>

using namespace std;

#define ll   long long
#define ld   long double

#define mp   make_pair
#define pb   push_back
#define eb   emplace_back

#define sum(a)     ( accumulate ((a).begin(), (a).end(), 0ll))
#define mine(a)    (*min_element((a).begin(), (a).end()))
#define maxe(a)    (*max_element((a).begin(), (a).end()))
#define mini(a)    ( min_element((a).begin(), (a).end()) - (a).begin())
#define maxi(a)    ( max_element((a).begin(), (a).end()) - (a).begin())
#define lowb(a, x) ( lower_bound((a).begin(), (a).end(), (x)) - (a).begin())
#define uppb(a, x) ( upper_bound((a).begin(), (a).end(), (x)) - (a).begin())

template<typename T>             vector<T>& operator--            (vector<T>& v){for (auto& i : v) --i;            return  v;}
template<typename T>             vector<T>& operator++            (vector<T>& v){for (auto& i : v) ++i;            return  v;}
template<typename T>             istream& operator>>(istream& is,  vector<T>& v){for (auto& i : v) is >> i;        return is;}
template<typename T>             ostream& operator<<(ostream& os,  vector<T>& v){for (auto& i : v) os << i << ' '; return os;}
template<typename T, typename U> istream& operator>>(istream& is, pair<T, U>& p){is >> p.first >> p.second;        return is;}
template<typename T, typename U> ostream& operator<<(ostream& os, pair<T, U>& p){os << p.first << ' ' << p.second; return os;}
template<typename T, typename U> pair<T,U> operator-(pair<T,U> a, pair<T,U> b){return mp(a.first-b.first, a.second-b.second);}
template<typename T, typename U> pair<T,U> operator+(pair<T,U> a, pair<T,U> b){return mp(a.first+b.first, a.second+b.second);}
template<typename T, typename U> void umin(T& a, U b){if (a > b) a = b;}
template<typename T, typename U> void umax(T& a, U b){if (a < b) a = b;}

#ifdef HOME
#define TAG_LENGTH       25
#define LR_LEFT          left
#define LR_RIGHT         right
#define LR_VALUE         value
#define LR_SECOND_VALUE  mn
#include "C:/C++ libs/print.cpp"
const int H = 2;
#else
#define showl            42;
#define shows            42;
#define show(...)        42;
#define showm(...)       42;
#define showt(...)       42;
#define printTree(...)   42;
#define printGraph(...)  42;
#define printLRTree(...) 42;
#define printMatrix(...) 42;
#define printWGraph(...) 42;
#define debug     if (false)
const int H = 8;
#endif

int main() {
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

    int n;
    cin >> n;
    vector<int> v(n + 1), w(n + 1);
    for (int i = 1; i <= n; ++i) {
        cin >> v[i] >> w[i];
    }

    vector<int> h(n + 1);
    h[1] = 1;
    for (int i = 2; i <= n; ++i)
        h[i] = h[i / 2] + 1;
    vector<map<int, int>> prepos(n + 1);
    vector<vector<pair<int, int>>> pos(n + 1);
    prepos[1][0] = 0;
    prepos[1][w[1]] = v[1];
    for (int i = 2; i <= n && h[i] <= H; ++i) {
        prepos[i] = prepos[i / 2];
        for (auto wwvv : prepos[i / 2]) {
            int ww, vv;
            tie(ww, vv) = wwvv;
            prepos[i][ww + w[i]] = max(prepos[i][ww + w[i]], vv + v[i]);
        }
    }
    for (int i = 1; i <= n; ++i) {
        pos[i] = vector<pair<int, int>>(prepos[i].begin(), prepos[i].end());
        for (int j = 1; j < pos[i].size(); ++j)
            pos[i][j].second = max(pos[i][j].second, pos[i][j - 1].second);
    }

    // if (n == 15) {
    //     show(pos[1]);
    //     show(pos[2]);
    //     show(pos[4]);
    //     show(pos[9]);
    // }

    int q;
    cin >> q;
    for (int i = 0; i < q; ++i) {
        int u, L;
        cin >> u >> L;
        if (h[u] <= H) {
            int ind = lowb(pos[u], make_pair(L, -1));
            if (ind == pos[u].size() || pos[u][ind].first > L) --ind;
            cout << pos[u][ind].second << '\n';
            continue;
        }
        vector<pair<int, int>> vars;
        int x = u;
        while (h[x] > H) {
            vars.eb(w[x], v[x]);
            x /= 2;
        }
        map<int, int> mm;
        for (int i = 0; i < (1 << vars.size()); ++i) {
            int ww = 0, vv = 0;
            for (int j = 0; j < vars.size(); ++j) {
                if ((i >> j) & 1) {
                    ww += vars[j].first;
                    vv += vars[j].second;
                }
            }
            mm[ww] = max(mm[ww], vv);
        }
        vector<pair<int, int>> vv(mm.begin(), mm.end());
        for (int j = 1; j < vv.size(); ++j)
            vv[j].second = max(vv[j].second, vv[j - 1].second);
        int ans = 0;
        int ind = pos[x].size() - 1;
        for (auto wv : vv) {
            int w, v;
            tie(w, v) = wv;
            if (w > L) break;
            while (ind == pos[x].size() || pos[x][ind].first > L - w) --ind;
            ans = max(ans, pos[x][ind].second + v);
        }
        cout << ans << '\n';
    }

    return 0;
}

Submission status: Runtime Error

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 i in range(q):
  v,w=map(int,input().split())
  VV=[]
  WW=[]
  while v>=1:
    VV.append(V[v-1])
    WW.append(W[v-1])
    v=v//2
  V1=VV[0:n//2]
  V2=VV[n//2:n]
  W1=WW[0:n//2]
  W2=WW[n//2:n]
  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: Runtime Error

Solution code:
import numpy as np
import sys
input = sys.stdin.buffer.readline

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

dp = np.zeros((N, 10**5+1), np.int64)
dp[0, vws[0][1]:] = vws[0][0]
for i in range(1, N):
    v, w = vws[i]
    dp[i] = dp[(i-1)//2]
    dp[i, w:] = np.maximum(dp[(i-1)//2, :-w]+v, dp[i, w:])

Q = int(input())
for _ in range(Q):
    V, L = map(int, input().split())
    print(dp[V-1][L])

Submission status: Runtime Error

Solution code:
import numpy as np
n = int(input())
v = [0 for _ in range(n)]
w = [0 for _ in range(n)]
for i in range(n):
	v[i], w[i] = map(int,input().split())
Q = int(input())
for _ in range(Q):
	c, l = map(int,input().split())
	cnt = c
	sl = []
	while cnt >= 1:
		sl.append((v[cnt-1], w[cnt-1]))
		cnt >>= 1
	dp = np.full(l+1, 0, dtype=np.int64)
	for i, j in sl:
		dp[j:] = np.maximum(dp[j:], dp[:l+1-j] + i)
	print(dp[l])