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.
We need to answer many queries on a rooted binary tree where each vertex has an item (value, weight). For a query (v, L), we can pick a subset of items from vertices on the path from root (1) to v (including v) such that total weight ≤ L, maximize total value. This is basically a knapsack problem limited to at most depth items (depth <= height). N up to 2^18 - 1 (since N<2^18, so depth up to 17? Actually binary tree where vertex i's parent is floor(i/2). That's a perfect binary tree structure (like a binary heap). Height of the tree: since N up to 2^18-1, max depth is about 18 (log2). Actually the deepest vertex number N could be up to 2^18-1, so height = floor(log2(N)) + 1 <= 18. So the path length from root to any vertex is at most 18. That's small! However N can be large (2^18-1 ~ 262k) but depth is small (<=18). So each query involves at most ~18 items. So we could simply do a knapsack per query? But Q up to 1e5, L up to 1e5, and each knapsack of up to 18 items could be done via DP of size O(L) per query? 18 * 1e5 * 1e5 = too high. But we can do a DP per query with complexity O(depth * L) which would be 18*1e5=1.8e6 per query, times 1e5 = 1.8e11, not feasible.
We need faster method. Since depth is small, we can preprocess something. Each path from root to a vertex is at most 18 items. So total number of distinct paths is N (each vertex). For each vertex, we could precompute the DP for its path, but DP size is L up to 1e5, can't store full DP for each vertex (N up to 262k) would be too large (262k * 1e5 = 2.6e10). But note that weights and values are up to 1e5, L up to 1e5.
However depth small suggests using meet-in-the-middle on items per query? But there are only at most 18 items; we could enumerate all subsets (2^18 = 262k) per query, compute weight and value, then answer by scanning subsets? That would be 262k * Q = 2.6e10, too slow.
But we can precompute for each vertex a "knapsack DP" that considers only items on its path, but using some optimization because L is up to 1e5, but the DP could be stored as a piecewise linear function (convex? not necessarily). But typical knapsack DP for small number of items can be done via "sparse DP" using map of weight->value, merging items. Since depth is small (max 18), the number of distinct weight combinations from subsets is at most 2^18 = 262k, but that's only if weights are arbitrary. However we can store for each vertex the list of all subsets (weight, value) but that could be 262k per vertex which is too much.
We need to answer many queries online. Since depth is limited, maybe we can use the property that tree is a binary heap, and queries involve ancestors. Could use heavy-light decomposition? But depth is shallow, maybe we can process queries offline or with bitset DP? With L up to 1e5, we could represent DP as bitset of possible weights? But we need max value for given capacity, not just feasibility.
Alternatively, note that constraints: V_i, W_i up to 1e5, L up to 1e5. The number of items per query is small (<=18). So we can solve each query by performing a DP on the fly with O(depth * L) but that is too high because L can be 1e5. But we can apply the "knapsack with small number of items but large capacity" by using meet-in-the-middle: split the items into two halves (each up to 9 items). Compute all subsets of each half: for each subset compute total weight and total value. Then we need to combine: for each subset from first half, we need the best value from second half with weight <= L - w1. That can be done by sorting the second half by weight and building prefix max on values. So per query: O(2^(d/2) * (d/2) )? Actually generating subsets O(2^(d/2)). d <= 18 => 2^9=512. So per query we could do 512 subsets. That's fine! 512 per query times Q=1e5 => about 51 million operations, which is okay. Let's check: For each query, we need to get the list of items on the path from root to v. Since depth is <=18, we can quickly traverse up to root (by repeatedly halving index) to collect items. Then we have at most 18 items. We can split them into two groups: first half (say first 9 items) and second half (rest). Generate all subsets of each group, compute weight and value. For each group, we have at most 512 entries. For group B, sort by weight, then compute prefix max to get best value for any weight <= some value. Then for each subset from group A, we query the best value from B with weight <= L - wA. Since L up to 1e5, we can use binary search on sorted B weights to find the index of max weight <= remaining capacity, then get prefix max value. Complexity per query: O(2^(d/2) * log(2^(d/2))) ~ 512 * log(512) ~ 5129 = 4608 operations, plus constructing subsets, plus retrieving path. So 1e5 * 5000 = 5e8? Actually 512log(512) ≈ 4600, times 1e5 = 460 million, maybe borderline but likely okay in C++ with optimization. But we can reduce log factor by using two-pointer after sorting both? But we can also for each query just sort B subsets (size up to 512) and compute prefix max O(512 log 512) is fine. 460 million operations might be okay in 2 seconds? Probably a bit high but with efficient code and maybe using arrays, can pass. However we can also precompute for each vertex the list of items on its path? Actually each query we can collect items by walking from v to root: depth ≤ 18, so cheap.
But 460 million operations might be high in Python? The problem is likely from AtCoder (maybe ABC 246 Ex? Actually looks like AtCoder problem "Knapsack for tree" or something). They often expect C++ solution. However we need to produce code, but we are just reasoning. But we can also improve: Since depth ≤ 18, the number of items is fixed small. We can precompute for each vertex the entire subset list? That would be 2^depth per vertex, too much. But we could precompute for each vertex a DP array of size Lmax (1e5) but that's too large.
Another technique: Since depth small, we can do DP with bitset and keep only best value per weight, but merge incrementally along the path. But again per query we would need to recompute DP from scratch on small number of items. The meet-in-the-middle approach is simplest and likely fast enough.
But careful: The constraints: N up to 2^18-1 = 262143, Q up to 1e5. Depth is at most 18, but for numbers near 2^18, depth is 18 (since root depth 1, then index 2^17 = 131072, depth 18? Actually root=1 depth 1. Vertex i: depth = floor(log2(i)) + 1. So max depth = floor(log2(N)) + 1 <= 18 (since N < 2^18, log2(N) < 18, floor <=17, so depth <=18? For N=2^18-1, floor(log2(2^18-1)) = 17, so depth=18. Yes.
So indeed max items per path = 18.
Now meet-in-the-middle: For each query, we need to get the items (v_i, ancestors). Implementation:
Read N, arrays V[1..N], W[1..N].
For each query (v, L):
Build list items: while v > 0: items.append((V[v], W[v])); v //= 2; (until v==0, but root is 1, but we can stop when v==0). Actually v >=1, parent of 1 is floor(1/2)=0, so stop when v==0.
Now we have list of d items (d = depth). Order: from leaf to root (but order doesn't matter for subset selection). Could keep as is.
Split items into two groups: first half (first d//2 items) and second half (remaining d - d//2). Actually typical MITM: split arbitrarily, but we can split by first k = d//2 items and rest.
Generate all subsets for group A: For mask 0..(1<<k)-1: compute sumW, sumV by iterating bits. But we could precompute for each group size up to 9, we can do loops.
For group B: similarly generate all subsets.
For group B: sort by weight, then compress: for same weight keep max value, and ensure that for increasing weight, value is non-decreasing (i.e., prefix max). Since we will binary search for capacity, we need an array of weights and corresponding best value up to that weight. So after generating all subsets of B, we sort by weight, then iterate to create arrays: weights sorted, and bestValue[i] = max( bestValue[i-1], value_i ). But careful: If there are multiple entries with same weight, we take max and then propagate.
Then for each subset in A: if sumW > L, skip; else remaining = L - sumW; find the largest index in B weights <= remaining (binary search), then candidate = sumV + (bestValue[idx] if found else 0). Keep max.
Return max.
Complexity per query: O(2^{k} * k + 2^{d-k} * (d-k) + 2^{k} * log(2^{d-k}) ) but k ~ d/2. So ~ O(2^{d/2} * d). With d=18 => 512 * 18 ≈ 9216 operations plus binary search (log 512=9) for each A subset (512) => 4608, total ~13824 operations per query. Times 1e5 = 1.3824e9 operations, borderline but maybe okay in C++ with optimization (like using vector and preallocation). But we can improve by not using binary search: Since group B size at most 512, we could sort group B and then for each A subset, we could precompute something? Alternatively, we could combine the two lists via two-pointer after sorting both by weight? But we need max value for each A subset, not a single combined max. Could sort A subsets as well and then use two-pointer technique to compute maximum of sumV_A + bestValue_B for each A? Actually we need to consider all pairs where weightA+weightB <= L. That's like classic two-list knapsack. We could sort both by weight, and then for each A subset in increasing weight, maintain a pointer in B for the largest weight <= L - weightA, and since we want max value from B, we can precompute prefix max for B. The pointer can move backwards as weightA increases? Actually if we sort A by weight ascending, as weightA increases, remaining capacity decreases, so the pointer in B (index of max allowed weight) moves left. But we would still need to query the prefix max up to that index. So binary search is fine. Or we can after sorting B and prefix max, we can store an array of weights and bestValues, and binary search.
Alternatively, we could precompute for each vertex a DP using "small number of items" but compress to limited number of weight thresholds? Not needed.
Given that d is at most 18, but actual depths vary; average depth maybe 9? The worst-case is 18, but many queries may involve vertices with smaller depth (like near root). However we should assume worst-case.
But we can further optimize: Since items per query are at most 18, we can directly use DP using bitset of values? Actually standard knapsack DP with array of size L+1 and iterating items in O(d * L) is too heavy. But maybe L is up to 1e5, d=18 => 1.8M per query, times 1e5 = 180B, impossible. So meet-in-the-middle is better.
But perhaps we can preprocess for each vertex a DP using "sparse representation" because the total number of distinct weight combinations from subsets is at most 2^depth, which for depth=18 is 262k. That's per vertex? That would be too much total. But note that many vertices share prefixes. Since the tree is a binary heap, the path from root to a vertex is unique. But we could precompute for each depth (or for each node) the list of subsets, but that would be huge.
We could also use technique of "knapsack on tree with small depth" using DP merging from root: For each node, we could compute DP array of size L_max (1e5) but only for nodes that are at depth <= something? But depth is at most 18, so number of nodes at depth 18 is large (~131k). Storing full DP for each node would be too much.
But we could answer queries offline using divide-and-conquer on the tree? However depth is small so meet-in-the-middle per query is easiest.
Let's evaluate complexity more precisely: Q=1e5, per query we do:
Walk up from v to root: at most 18 steps.
Build two lists of subsets: for group sizes up to 9 each, generate subsets: For each group, we can compute using loops over mask and precomputed per item values? Implementation: For group A size k, we can create vectors of (weight, value) by iterating mask from 0 to (1<<k)-1, and inside the loop we could compute using incremental DP? For each mask we could compute sum by adding one item at a time using lowbit, but simpler: iterate mask and recompute sum by iterating bits. That would be O(2^k * k). For k=9 => 512*9=4608 operations. For group B similarly. Total ~9k.
For each subset in A (512): binary search on B weights (log 512=9) => 4608.
So total operations maybe around 20k per query. 1e5 * 20k = 2e9, which is high for C++? But note that many operations are simple integer additions and comparisons, and 2e9 might be borderline but perhaps with compiler optimizations and using small vectors, it could pass within time limit if time limit is generous (like 2 sec? Might be too slow). However we can further optimize.
Optimization possibilities:
Precompute for each vertex the list of items on its path? That would be depth items, but we still need to compute subsets each query; however we could precompute all subsets for each vertex? That would be 2^depth per vertex, which is at most 262k per vertex, too much.
Precompute for each vertex the meet-in-the-middle structures? That is, for each vertex, we could generate the list of subsets of its ancestors and store them in sorted and compressed form. Since depth <=18, the number of subsets per vertex is at most 2^depth = 262k. But storing that for all vertices: N up to 262k, so total subsets would be sum_{v} 2^{depth(v)}. For a full binary tree of depth D (max depth 18), the number of nodes at depth d is 2^{d-1}. Each such node has depth d, so subsets count = 2^d. So total sum = sum_{d=1}^{D} (2^{d-1} * 2^d) = sum_{d=1}^{D} 2^{2d-1} = (1/2) * sum_{d=1}^{D} 4^d = (1/2)* (4*(4^D -1)/3) approx (2/3)*4^D. For D=18, 4^18 = 2^36 ≈ 6.87e10, far too large.
So not feasible.
Alternative: Use DP with "divide and conquer on queries" (offline) but perhaps we can use technique of "knapsack on a tree with small depth" using DP and then answer queries by merging DP of two halves of the path? Actually the path length is <=18, so maybe we can precompute for each node a DP for the path from root to that node, but only store it in a compressed form using "Pareto optimal" pairs (weight, value). Since for knapsack, not all subsets are Pareto optimal: we only need to keep those with increasing weight and value (i.e., undominated pairs). For a set of items, the number of undominated subsets can be bounded by something like O(2^{d/2})? Actually worst-case can be exponential. But given that weight and value are up to 1e5, maybe the number of Pareto-optimal subsets is limited? However can be as many as combinatorial. For d=18, the maximum number of undominated subsets? For random weights and values, it's often less than thousands. But adversarial could be large? Potentially near 2^d. For example, if items are (weight=1, value=1), (weight=2, value=2), (weight=4, value=4)... then all subsets are Pareto-optimal because weight and value are equal, so each subset has unique weight and value, and they are all nondominated? Actually if weight equals value, then subsets with higher weight have higher value, so they dominate those with lower weight? For dominance: a subset A dominates B if weight_A <= weight_B and value_A >= value_B, and at least one strict. If weight equals value, then for two subsets with w1<w2, we have v1<v2, so neither dominates the other because to dominate you need higher or equal value with less or equal weight. So none dominate, all are Pareto-optimal. So the number of undominated subsets can be up to 2^d. So that doesn't reduce worst-case.
Thus meet-in-the-middle per query is the simplest and maybe acceptable if optimized well.
But we must consider that L is up to 1e5. In meet-in-the-middle, we only need to consider subsets whose total weight does not exceed L. However we still generate all subsets of each half (512 each). That's fine.
Potential micro-optimizations:
Use arrays of fixed size (like using std::array for subsets) because size known; but we can allocate vectors with reserve.
For generating subsets, we can use iterative DP: For group A, start with list containing (0,0), then for each item, we extend list by adding new entries. This yields list of size up to 2^k, but we can also prune entries with weight > L (but since L can be up to 1e5, and weight per item up to 1e5, even after adding items, some combinations may exceed L; we can filter early to reduce list size. For group A, we can stop adding if weight > L (since we only care about subsets that individually ≤ L). But when combining with B, we need those subsets to possibly combine with B; but if weightA > L, it's useless. So we can filter to keep only weight <= L. For group B, we also need to consider subsets that may combine with A; if weightB > L, they could still combine if A weight small? Actually if weightB > L, then even with A weight 0, total > L, so useless. So we can filter out any subset with weight > L. That could reduce the list sizes if many items heavy. However worst-case all weights =1, then all subsets have weight <= d <=18 << L, so no reduction. So not big.
For binary search, we can store B as two arrays: weights (sorted) and prefMax. Then use std::upper_bound to find index of largest weight <= remaining. Or we could store in vector and use binary search.
Since Q is large, we can precompute the depth and ancestor list for each vertex? Actually we can precompute for each vertex the list of (V,W) for its ancestors (including itself). That would be a vector of up to 18 items per vertex. That's okay: N up to 262k, each with at most 18 entries, total ~ 4.7 million pairs, memory fine. Then for each query we just fetch that precomputed list O(1) without walking up. But walking up is cheap (max 18 steps) anyway, but precomputing might speed up a bit. However walking up involves integer division and array accesses. It's fine. But we can also precompute for each vertex the list of items (values, weights) for its path. Let's do that to avoid repeated divisions. But note that N up to 262k, so storing for each vertex an array of depth (max 18) of (v,w). That's about 262k * 18 * 2 ints = ~9.4 million ints, ~ 38 MB, okay. But we also need for each vertex, we might need its depth to split groups? Actually we can just store the list of items in order from root to node (or reverse). For MITM we need the items, order doesn't matter. So we can precompute for each node a vector of items (say array of length depth). Then for query, we fetch that vector. However the vector size varies; we could store as a list of pairs per node. That would be many small vectors, overhead might be high. But we can store in a single array with offsets. Or we can simply compute on the fly: while v>0: add item; v/=2. That's O(depth) which is ≤18, so total operations across all queries: 1e5 * 18 = 1.8 million, negligible. So on-the-fly is simpler and less memory, so we can do that.
So main cost is subset enumeration per query.
We can try to further reduce per query time by using precomputed subsets for each possible set of items? But items vary per vertex. However many vertices may share the same set of ancestors? In a tree, each vertex has a unique path. So no sharing except prefixes. But could we precompute for each depth prefix? Actually we could precompute DP for all nodes at a certain depth? Not helpful.
Alternate approach: Because depth is small, we can precompute for each node a DP array of size Lmax but using "sparse" representation via "convex hull"? Not.
Another angle: Since weights and values are up to 1e5, and L up to 1e5, we could treat this as a 0/1 knapsack with at most 18 items. There is also a technique using "branch and bound" or "meet-in-the-middle with optimization like using arrays for B and then scanning A with two pointers". Let's think about optimization of binary search.
Given B size at most 512, we could store prefix max in an array and then for each A subset, we could linearly scan B? That would be 512*512 = 262k per query, which is about 26e9 for Q=1e5, too high.
But we can also sort both A and B and use two-pointer technique to compute the maximum combined value in O(2^k) after sorting. How? For MITM knapsack we often do: sort B by weight, compute prefix max. Then for each A, binary search. That's fine. Since B size is small, we could even precompute for each possible remaining capacity? Not.
We can also use a technique to combine by iterating over B in descending weight and maintaining best value, while iterating over A in ascending weight. But we need to consider all pairs. Could do: sort A by weight, sort B by weight. Then for each A in increasing weight, as weight increases, the allowed B weight decreases. So we could have a pointer j that moves left over B (starting from highest weight) and we keep track of max value seen in B from j to end? Actually we need for each A, the max value among B with weight <= L - wA. If we sort A ascending, and maintain a pointer in B that moves left as wA increases, we can compute prefix max up to that pointer. But we still need to query the max value among B up to that pointer. We can precompute prefix max for B, but still need to find the pointer index (which we can compute by moving pointer left while B[pointer].weight > L - wA). Since both lists sorted, we can move pointer in O(|B|) total per query if we sweep through A. That would eliminate binary search, but we need to compute pointer index each time. Let's design: Let B sorted by weight ascending. Actually we need largest weight <= remaining. That is like find the rightmost index where weight <= cap. If we process A in decreasing order of weight, then cap increases, so the index moves right. That could be better: sort A by weight descending; then maintain an index in B that goes from 0 upward as cap increases. Since cap = L - wA, as wA decreases (since descending weight), cap increases. So if we sort A descending, then for the first A (largest wA), cap is smallest, so B index low. Then as we go to smaller wA, cap grows, index moves right. So we can maintain a variable bestBValueForCurrentCap as we increase the index, we update the maximum value seen so far among B entries with weight <= cap. Since B is sorted by weight, when we move index to include new B entries, we can update current maxB = max(current maxB, B[index].value). But careful: B entries may have values that are not monotonic with weight. So we need to keep the max value among all B entries with weight <= current cap. So as we increase cap, we can expand index and keep running max. Then for each A, we have current maxB (the best value among B items with weight <= current cap). That gives best combination value for that A (since we don't need to consider weight of B beyond cap). However note: this works only if we consider all B entries with weight <= cap, and we want the maximum value. So we can indeed do: sort B by weight ascending. Compute an array of cumulative max values? Actually we could just precompute prefix max array once; then for each A we binary search cap to get index, then look up prefix max. That's O(log |B|) per A. If we instead sweep, we can get O(|A| + |B|) if we process A in order of increasing cap. Sorting A by wA (which is O(|A| log|A|)) adds overhead but maybe worth it to eliminate binary searches? Sorting A of size up to 512 is O(512 log 512) ~ 4600, similar to binary searching each A (512*9=4600). So overall similar. But we could avoid sorting A by using the fact that we generate subsets A already; we could just iterate over all A subsets without sorting and for each use binary search. That's also 512 * log512 = 4600. If we sort A to do sweeping, we add sorting cost 512 log512 = 4600, plus sweeping O(512+512)=1024, total 5600 vs 4600. So binary search approach might be slightly better. But we can also avoid sorting B? We need B sorted and prefix max. Sorting B costs 512 log512 anyway.
Thus binary search approach is fine.
But can we do better by precomputing for each vertex something like all subset combos sorted? That would be per vertex: 2^depth ~ up to 262k, too much.
Thus I think meet-in-the-middle per query is the intended solution for typical contest. Actually AtCoder problem "ABC 237 Ex?" No, I recall a problem "Knapsack for Tree" from AtCoder typical solution uses meet-in-the-middle because depth is at most 60? Actually there is a problem "AtCoder Beginner Contest 246 Ex" maybe? Not sure.
But let's check constraints: N < 2^18, depth <=17? Actually 2^18 = 262144, so N up to 262143. That ensures depth <=18. So it's designed for MITM.
Let's test with sample: first example, N=3, depth of vertex 2: root->2: depth=2, items: (1,2),(2,3). queries: (1,1) => only item (1,2) weight 2 >1 so 0, correct. (2,5): items (1,2) and (2,3): possible subsets: take both weight 5 value 3, or only one. max=3. (3,5): items (1,2),(3,4): take (1,2) only value 1, or (3,4) only value 3 weight4 <=5, so max=3. Works.
So algorithm is clear.
Implementation details:
We'll read N, arrays V[1..N+1], W[1..N+1].
Read Q.
For each query:
v, L
vector<pair<int,int>> items; // (value, weight) or (weight, value)? We'll need both.
while (v >= 1) {
items.emplace_back(V[v], W[v]); // order maybe from leaf to root.
v >>= 1;
}
int d = items.size();
// split items into two groups: first k = d/2 items? Actually we can split by first half: groupA = items[0..k-1], groupB = items[k..d-1]. But careful: items order (leaf first) arbitrary; splitting equally is fine.
int k = d / 2; // floor
// generate subsets for groupA:
vector<pair<int,long long>> A; // (weight, value)
// Since value up to 1e5, sum up to 181e5 = 1.8e6 fits in int? Actually 181e5=1.8e6, fits 32-bit. But we'll use int.
// Use long long for value? but max sum value = 18*1e5=1.8e6, fits int. So int is fine.
int sizeA = 1 << k;
A.reserve(sizeA);
for (int mask = 0; mask < sizeA; ++mask) {
int w = 0, val = 0;
for (int i = 0; i < k; ++i) {
if (mask & (1 << i)) {
w += items[i].second; // weight
val += items[i].first; // value
}
}
if (w <= L) // we can filter here
A.emplace_back(w, val);
}
// groupB: remaining items count m = d - k
int m = d - k;
vector<pair<int,int>> B;
int sizeB = 1 << m;
B.reserve(sizeB);
for (int mask = 0; mask < sizeB; ++mask) {
int w = 0, val = 0;
for (int i = 0; i < m; ++i) {
if (mask & (1 << i)) {
w += items[k + i].second;
val += items[k + i].first;
}
}
if (w <= L) // filter
B.emplace_back(w, val);
}
// sort B by weight, then compress: for same weight keep max, and prefix max
sort(B.begin(), B.end(), [](auto& a, auto& b) { return a.first < b.first; });
// Build arrays: unique weights with best value
vector bw, bv; // weight and best value up to that weight
for (auto& p : B) {
if (!bw.empty() && bw.back() == p.first) {
bv.back() = max(bv.back(), p.second);
} else {
bw.push_back(p.first);
bv.push_back(p.second);
}
}
// compute prefix max over bv (ensuring non-decreasing)
for (size_t i = 1; i < bv.size(); ++i) {
bv[i] = max(bv[i], bv[i-1]);
}
// Now iterate over A
int ans = 0;
for (auto& a : A) {
int rem = L - a.first;
// find index of largest weight <= rem
auto it = upper_bound(bw.begin(), bw.end(), rem);
if (it == bw.begin()) {
// no B subset with weight <= rem, just consider a alone
ans = max(ans, a.second);
} else {
int idx = distance(bw.begin(), it) - 1;
ans = max(ans, a.second + bv[idx]);
}
}
// also consider only B subsets? Already covered when a is empty (since A includes empty mask). So fine.
print ans
Edge cases: If k=0 (d=1), then groupA has 1<<0 =1 subset (empty). groupB has m=1, etc. Works.
Complexities: For each query, we allocate vectors A, B. That could cause many dynamic allocations, which may be expensive. We can allocate vectors per query and let them be freed, but with 1e5 queries, many allocations could be heavy. To optimize, we could use static arrays of size 512 each, but we need to know the exact size after filtering weight <= L, but we can still allocate with reserve. Alternatively, we can use a fixed-size array and a count variable to simulate vector; but easier to use vector and trust that the memory allocation overhead is not too high (maybe it is). We could also reuse a global vector by clearing each time, but we need separate for A and B. We could preallocate a global vector of capacity 512 and use it as a stack, but then we need to know sizes. Since Q is large, perhaps using thread_local or static vectors with .clear() might reduce allocations. But we can implement with local vectors; with modern C++, small allocations may be fast. But we can also implement using std::array<pair<int,int>, 512> for subsets and a counter. That might be more efficient.
Let's think about implementing enumeration without using vector and dynamic memory: We can have arrays of fixed size 600 (a bit more than 512) for A and B subsets. We'll have a counter for each. For group A: countA = 0; iterate mask 0..(1<<k)-1; compute w,val; if w<=L, store in A[countA++] = {w,val}. Then after generation, we need to sort B and build prefix arrays. For B, we can similarly store raw subsets in array Braw of size up to 512, countB; then sort, but we need to sort a portion of array. We can use std::sort on pointers Braw, Braw+countB. Then compress to arrays bw and bv; we can store those in another fixed-size array (maybe 512 as well). That's fine.
Thus we can avoid dynamic allocations.
But simpler: use vector; hopefully passes.
Now, is there any way to answer queries faster by precomputing something like "for each node, all subset sums"? That would be too big.
Thus we'll implement meet-in-the-middle.
But we need to confirm that this is within time limit for typical contest (like AtCoder). Usually AtCoder time limit is 2 sec for C++. 2e9 operations is too high. But maybe our estimate of operations is overestimated because we counted per query 20k operations, but many of these operations are simple integer operations, and CPU can do billions per second? A modern CPU can do around 3-4 billion operations per second in optimized C++? That's optimistic; typically around 1-2e9 operations per second for simple loops is possible if well-optimized. But with 2e9, it might be borderline. However many queries will have depth less than 18, reducing average operations. But worst-case we need to be safe.
Maybe we can further reduce by using DP with "divide and conquer on tree"? Alternative approach: Since depth <= 18, we can precompute for each node a DP array but using "sparse representation" via "dominance" and merge up the tree. Let's explore that: For each node, we can maintain a list of (weight, value) representing the best value achievable for each weight using items on the path from root to that node. This is essentially a knapsack DP result for that set of items. However the size of this list can be large (up to 2^depth). But maybe we can prune dominated pairs aggressively. In many cases, the number of undominated pairs might be limited because weights and values are up to 1e5? For random data, it's not huge. But worst-case can be 2^depth. However maybe constraints are designed such that worst-case won't happen? AtCoder problems often rely on meet-in-the-middle.
But let's think about another trick: Since L <= 1e5, we can precompute for each node an array dp[0..L_max]? But L_max=1e5, and nodes up to 262k, that's 26 billion entries, impossible.
What about using the fact that queries are many, but we can answer offline by processing nodes in order and using a persistent data structure? The tree is a binary tree; the path from root to a node is just a sequence of nodes. We could maintain a DP array as we walk down the tree, and when we reach a node, we have the DP for that path. Then we could answer queries that ask for that node. Since Q up to 1e5, we could perform a DFS and for each node, we have the DP state (size L_max). But L_max=1e5, and depth <=18, but we cannot store DP for each node visited during DFS because we need to answer queries at specific nodes. However we could do a DFS and maintain a DP array that we update by adding an item when going down, and revert when going up. Since depth is small, we could store the DP as an array of size L+1? But each query may have different L. Actually in query L varies, up to 1e5. If we maintain a DP array for all capacities up to 1e5, we can answer for any L instantly by looking at dp[L] (which is the maximum value for capacity exactly L? Actually we need max value for weight ≤ L, but we can store dp[w] as max value for exact weight, then prefix max. But we can answer by scanning dp up to L, but that would be O(L) per query again. But we could store the best value for each weight and then compute prefix max on the fly? If we have the dp array for that node, we could precompute the prefix max once per node? But that would require storing per node. Alternatively, during DFS we could, when arriving at a node, compute its DP array (from parent's DP by adding its item) and then store it for answering queries later. That would be N * L_max memory too large.
But we can compress DP using "sparse" representation: Since we are only adding one item each step, the DP transition is: new_dp[w] = max(old_dp[w], old_dp[w - wi] + vi). This is classic 0/1 knapsack. The DP array can be represented as a bitset of possible weights with values? But we need maximum value, not just feasibility. However we can store for each weight the maximum value. The DP array is of length L_max+1, and values are at most 1.8e6. The transition per item is O(L_max). That's 1e5 per node, times up to 262k nodes, impossible.
But maybe we can do DP only up to L_max for each node but L_max is 1e5, and depth is 18, so each path has only 18 items. So DP from scratch per path would be O(18*L_max) = 1.8e6. That's the same as earlier. So no.
Thus meet-in-the-middle seems best.
Let's refine meet-in-the-middle per query complexity: Suppose worst-case depth=18, so groups sizes k=9, m=9. Then A and B each have up to 512 subsets. Filtering by w<=L reduces none if all weights small. So 512 each. Sorting B: 512log2(512) ≈ 5129 = 4608 comparisons. Each comparison cheap. Generating subsets: For each mask, we loop over 9 bits to compute sums. That's 512 * 9 = 4608 additions and checks per group, total 9216. Then binary search for each A: 512 * (log2(512) ≈9) = 4608 binary search steps (each step a comparison). So total operations maybe around 20k integer ops. For 100k queries, that's 2e9 operations. This might be okay in C++ if well-coded and with compiler optimizations, but might be near the limit. However we can reduce the constant factor: we can generate subsets using iterative DP technique that avoids iterating bits each time. For example, for group A, we can start with a list of subsets currently, and for each item, we double the list by adding the item. That's still O(2^k * k) but the constant might be lower because we avoid bit loops? Actually the doubling method: start with list = [(0,0)]. For each item (v,w), for each existing entry (we iterate current list and create new ones by adding item). This yields 2^k entries, and each entry is processed once per item? Let's compute: for each item, we iterate over current list (size doubles each step). The total number of operations is sum_{i=0}^{k-1} 2^i = 2^k -1, but each step we produce new entries by copying? Actually we need to copy the old list to create new entries. If we do in-place expansion by iterating backwards over a fixed-size array? For each item, we could take the current list (size s) and for j from s-1 down to 0, we create a new entry list[j] + item and push back. This yields 2 * s entries after processing item. The total number of "additions" (computing new sums) is exactly 2^k -1 (since we start with 1 entry and each item doubles, and we compute one new sum per existing entry per item). However each addition includes adding weight and value. So total operations is (2^k -1) additions. For k=9, that's 511 additions, much less than 5129=4608. But careful: The doubling method produces list of subsets, but it also stores them. The number of operations to generate all subsets is O(2^k), not O(k2^k). That's a big improvement! Let's confirm: Starting with list = [ (0,0) ].
For item 1: we take list (size 1), for each entry we create new entry by adding item. That yields 1 new entry, so total entries =2, operations =1 addition.
For item 2: list size=2, we iterate over both entries and create new ones: 2 additions, total entries=4.
For item 3: 4 additions, total entries=8.
...
For k items: total additions = 1+2+4+...+2^{k-1} = 2^k -1. So indeed O(2^k). The classical method of iterating all masks and checking bits is O(k * 2^k). So we can use the doubling method to generate subsets efficiently. However we need to generate both groups. For group B we can do similarly. This reduces per query operations significantly: For k=9, additions = 511 for A, similarly for B with m=9, additions = 511. Total 1022 additions. Plus we need to sort B, which is O(2^m log(2^m)) = 512 * 9 = 4608 comparisons. But sorting 512 items is cheap.
We also need to combine: for each entry in A (512 entries), we binary search in B (log 512 ~9). That's 4608 binary search steps.
Total maybe around 10k operations per query. 1e5 * 10k = 1e9 operations, which is more manageable.
Additionally, we can further reduce sorting cost by using counting sort? Since weights are up to 1e5, but B size is small, sorting is fine.
We can also consider using a precomputed array for B: after generating B subsets, we could directly compute an array bestB[0..L] by iterating over B entries and taking max value for each weight, then compute prefix max, then for each A we can look up bestB[rem] in O(1). But L up to 1e5, and we would need to fill an array of size L+1 per query, which is 1e5, too high. So not.
Thus the plan: per query, generate A and B subsets via iterative doubling, filter weights > L during generation to prune early? In doubling method, we can prune entries with weight > L as soon as they exceed L because they will never be part of a valid combination (since even adding more items would increase weight). However careful: In the iterative doubling, we generate subsets incrementally; when we add an item to an existing subset that already exceeds L, the new subset will also exceed L (since weights are positive). So we can skip generating those new subsets. Also, we can drop entries that exceed L from the list, as they are useless. This reduces list sizes if L is small relative to total possible weight. But worst-case L=1e5 and total weight of all items on path maybe up to 18*1e5=1.8e6, but many subsets may exceed L. Actually with many items of weight 1e5, many subsets will exceed L quickly. But worst-case all weights are 1, then all subsets have weight <=18, far below L, so no pruning. So worst-case we still have 512 entries each.
Thus algorithm:
For each query (v, L):
// collect items
items.clear();
while (v) {
items.push_back({V[v], W[v]});
v >>= 1;
}
d = items.size();
k = d / 2;
// split items: first k items -> group1, rest -> group2
// but note: items are from leaf to root. Splitting equally will give groups that are not necessarily balanced in terms of number of items? But any split works.
// Actually we might want to split such that both groups have roughly equal number of items. Since d <= 18, we can set k = d//2.
// Generate subsets for first k items using doubling:
vector<pair<int,int>> A;
A.reserve(1<<k);
A.emplace_back(0,0);
for (int i = 0; i < k; ++i) {
int vi = items[i].first, wi = items[i].second;
int sz = A.size();
for (int j = 0; j < sz; ++j) {
int new_w = A[j].first + wi;
if (new_w <= L) { // prune if exceeds L
int new_v = A[j].second + vi;
A.emplace_back(new_w, new_v);
}
}
// Note: we are appending new subsets to the end, but we are iterating over original size. This works because we are using separate loop with fixed initial size.
}
// A now contains all subsets of first k items with weight <= L (including empty). It may contain dominated ones but that's okay.
code
// Generate B similarly for remaining items (m = d - k)
int m = d - k;
vector<pair<int,int>> B;
B.reserve(1<<m);
B.emplace_back(0,0);
for (int i = k; i < d; ++i) {
int vi = items[i].first, wi = items[i].second;
int sz = B.size();
for (int j = 0; j < sz; ++j) {
int new_w = B[j].first + wi;
if (new_w <= L) {
int new_v = B[j].second + vi;
B.emplace_back(new_w, new_v);
}
}
}
// sort B by weight, then compress and prefix max
sort(B.begin(), B.end());
// compress: For each weight, keep max value, and ensure prefix max.
// We can do in-place compression: since sorted by weight, we can iterate and build new vectors.
vector<pair<int,int>> Bopt; // (weight, best value up to this weight)
for (auto& p : B) {
if (Bopt.empty() || Bopt.back().first != p.first) {
// new weight
Bopt.emplace_back(p.first, p.second);
} else {
Bopt.back().second = max(Bopt.back().second, p.second);
}
}
// prefix max
for (size_t i = 1; i < Bopt.size(); ++i) {
if (Bopt[i].second < Bopt[i-1].second)
Bopt[i].second = Bopt[i-1].second;
}
// Now iterate over A
int ans = 0;
for (auto& a : A) {
int rem = L - a.first;
// binary search in Bopt for weight <= rem
// Since Bopt is sorted by weight, we can use upper_bound on weight
auto it = upper_bound(Bopt.begin(), Bopt.end(), make_pair(rem, 1<<30));
if (it != Bopt.begin()) {
int bestB = (it-1)->second;
ans = max(ans, a.second + bestB);
} else {
ans = max(ans, a.second); // only A
}
}
print ans
We need to ensure we include the case where only B subsets are used (A empty included). That's covered.
Now we must consider that A and B subsets include the empty set. Good.
Potential optimization: Since Bopt size is at most 512, we could use an array and manual binary search, but STL is fine.
Now complexity per query: generation: for A, number of additions is at most 2^k -1, but we also have condition check new_w <= L. For each addition we compute new_w, new_v, and if condition true we push back. So roughly 511 ops for k=9. Similarly B ~511. Sorting B: 512 log 512 ~ 4600 comparisons. Bopt building: ~512. Iterate A: 512 binary searches each ~9 comparisons => 4600. Total ~ (511+511) + 4600 + 512 + 4600 ≈ 10k. That's 10k per query, 1e9 total. Should be okay with C++ if optimized.
But we can reduce sorting overhead by sorting B via counting sort? Not needed.
Maybe we can pre-sort B using some property? Not.
But perhaps we can use integer arrays and manual loops to reduce constant.
Also note that Q up to 1e5, but N up to 2^18-1 ~ 262k. So reading input and processing queries is fine.
Now, we should also check if we need to use 64-bit for value sums? Max total value = sum of up to 18 items each max 1e5 = 1.8e6, fits in 32-bit signed int. So int is fine.
Now implement in C++.
Potential improvements:
Use arrays instead of vectors to avoid dynamic allocations. For each query, we could use static arrays of size 600 for A and B and use a count variable. However with the iterative doubling method, we need to dynamically expand the list; we can still use an array and an integer size variable, and for each item, we set new entries by iterating over the current portion. For example:
pair<int,int> A[1<<9]; // but size up to 512
int asz = 1;
A[0] = {0,0};
for each item in groupA:
for (int j = 0; j < asz; ++j) {
int new_w = A[j].w + wi;
if (new_w <= L) {
A[asz + j] = {new_w, A[j].v + vi}; // careful: we need to write to new positions without overwriting old ones. We can use separate destination index.
}
}
But we need to double the array, so we can loop j from asz-1 down to 0 to write new entries after asz? Actually we can do: for (int j = asz-1; j >=0; --j) { compute new; A[asz + j] = new; } then asz += number_of_new. However we need to know how many new entries we add (some may be skipped if exceed L). So we can maintain two sizes: old size and new size. Simpler: use vector.
Given the number of allocations, we could allocate vectors outside the loop and reuse them by clearing, but we need to reset size to 0 and then push_back. However the vector capacity will remain, so no new allocations after first few queries. We can declare vector<pair<int,int>> A, B outside and .clear() each query. But careful: we need to reserve capacity. We can reserve 512 initially (or maybe 600). Then each query we clear and push_back. That would avoid repeated allocations. Good.
We'll do:
vector<pair<int,int>> A, B;
A.reserve(1<<9); B.reserve(1<<9);
Then inside query loop:
A.clear(); B.clear();
A.emplace_back(0,0);
// generate A...
// similarly B
But note: A will be built incrementally; we will use A.size() during generation. After clearing, size=0, so we need to start with empty? Actually we need to start with A containing (0,0). So we push back after clear.
Yes.
Now for B, after generation we need to sort and compress. We could use another vector Bopt, also reserve 512.
But we also need to collect items. We can use a small array items[20]; we know max depth 18, so we can use static array of size 20.
Implementation steps:
Read N.
Use 1-indexed arrays: V[N+1], W[N+1].
Read N lines: V[i], W[i].
Read Q.
Pre-allocate vectors: A, B, Bopt, maybe also items vector (but we can use array).
For each query:
Read v, L.
Depth count = 0; while (v) { items[depth++] = {V[v], W[v]}; v >>=1; } // store in array items[0..depth-1] where items[0] is the leaf (v itself). Actually order doesn't matter. But we'll use this order.
d = depth.
k = d / 2; // first k items (0..k-1) go to A.
Generate A:
A.clear();
A.emplace_back(0,0);
for (int i=0; i<k; ++i) {
int vi = items[i].first, wi = items[i].second;
int sz = A.size();
for (int j=0; j<sz; ++j) {
int nw = A[j].first + wi;
if (nw <= L) {
int nv = A[j].second + vi;
A.emplace_back(nw, nv);
}
}
}
Generate B:
B.clear();
B.emplace_back(0,0);
for (int i=k; i<d; ++i) {
int vi = items[i].first, wi = items[i].second;
int sz = B.size();
for (int j=0; j<sz; ++j) {
int nw = B[j].first + wi;
if (nw <= L) {
int nv = B[j].second + vi;
B.emplace_back(nw, nv);
}
}
}
Sort B:
sort(B.begin(), B.end());
Build Bopt:
Bopt.clear();
for (auto& p : B) {
if (Bopt.empty() || Bopt.back().first != p.first) {
Bopt.emplace_back(p.first, p.second);
} else {
Bopt.back().second = max(Bopt.back().second, p.second);
}
}
for (size_t i=1; i<Bopt.size(); ++i) {
if (Bopt[i].second < Bopt[i-1].second) {
Bopt[i].second = Bopt[i-1].second;
}
}
ans = 0;
for (auto& a : A) {
int rem = L - a.first;
// binary search in Bopt
// using lower_bound/upper_bound
auto it = upper_bound(Bopt.begin(), Bopt.end(), make_pair(rem, INT_MAX));
if (it != Bopt.begin()) {
ans = max(ans, a.second + (it-1)->second);
} else {
ans = max(ans, a.second);
}
}
Print ans
Potential micro-optimizations:
Use arrays for items: pair<int,int> items[20]; int d=0; while(v){ items[d++]={V[v],W[v]}; v>>=1; }
Use integer arrays for A and B: but vector fine.
Use reserve for A and B: since max size 512, we can reserve 512 at start.
For binary search, we can use manual binary search on Bopt array to avoid constructing pair each time: use lower_bound on Bopt.first. We can store two separate arrays for weights and values, but Bopt is small.
Also note: In A generation, we are using A.emplace_back inside loop that also reads A.size(). Since we are adding new elements, A.size() increases; we stored original sz before loop, so it's safe.
v=1, L=1.
items: v=1 => items[0]=(1,2). depth=1.
d=1, k=0 (d/2=0). So A generated from 0 items: A = {(0,0)}.
B generated from items[k..d-1] i.e., items[0..0] since k=0, m=1? Actually d-k=1, so B will have the one item.
B generation: start with (0,0); then for i=0 (item (1,2)), wi=2, vi=1. For each existing B entry (only (0,0)), new_w=2, if <=1? no, so no addition. So B = {(0,0)} only.
Sort B: (0,0). Bopt = [(0,0)].
A has (0,0). For a=(0,0): rem=1. Bopt: upper_bound for (1,?) => it=end? Actually Bopt weights: [0]. upper_bound(1) returns end, it-1 -> last element weight 0. bestB=0. ans = 0. So output 0. Good.
v=2, L=5.
items: v=2: (2,3); v=1: (1,2). So items[0]=(2,3), items[1]=(1,2). depth=2, k=1.
A: first 1 item: items[0]=(2,3). Start A={(0,0)}; process item: wi=3, vi=2. sz=1; j=0: new_w=3 <=5 => add (3,2). So A={(0,0),(3,2)}.
B: remaining items: from i=k=1 to d-1: only items[1]=(1,2). B start {(0,0)}; process: wi=2, vi=1; new_w=2<=5 => add (2,1). So B={(0,0),(2,1)}.
Sort B: (0,0),(2,1). Bopt: (0,0),(2,1). prefix max: (0,0),(2,1). (since 1>0)
Now iterate A:
a=(0,0): rem=5; upper_bound for weight 5: it points to end? Bopt weights [0,2]; upper_bound(5) -> end; it-1 -> (2,1); ans = 0+1=1.
a=(3,2): rem=2; upper_bound(2) -> points to element after weight 2? Actually upper_bound returns first >2, so it points to index 2 (end) if no >2? Bopt weights: 0,2. upper_bound(2) returns end because 2 is not >2, so first >2 is none, so it = end; it-1 -> (2,1); ans = max(1, 2+1=3) => 3.
Also consider only B? Already covered when A empty. So ans=3. Good.
v=3, L=5.
items: v=3: (3,4); v=1: (1,2). Actually parent of 3 is floor(3/2)=1. So items[0]=(3,4), items[1]=(1,2). depth=2, k=1.
A: first item (3,4): start {(0,0)}; process: wi=4<=5 => add (4,3). So A={(0,0),(4,3)}.
B: item (1,2): B start {(0,0)}; process: wi=2<=5 => add (2,1). B={(0,0),(2,1)}.
Sort B: (0,0),(2,1). Bopt: (0,0),(2,1).
A iteration:
a=(0,0): rem=5 -> bestB=1 => candidate=1
a=(4,3): rem=1 -> bestB from Bopt: upper_bound(1) returns iterator to first weight>1, that is weight 2? Actually Bopt weights: 0,2. upper_bound(1) returns iterator to weight 2 (index1). it-1 -> weight 0, value 0. So candidate=3+0=3. ans=3. Good.
Second sample we can test later.
Now edge case: if depth is 0? v always >=1, so depth>=1.
Now consider if k=0 (d=1). A generation: loop over i<0 does nothing, A remains {(0,0)}. B generation: m=1, B will be built from the single item. Good.
Now consider if m=0 (when d=0? impossible). When d=0 not.
Now we need to ensure that we handle large L (1e5) but the subset weights may be up to 1.8e6; we prune >L so subsets with weight > L are not added. That's good.
Now about sorting B: B may contain many entries with same weight; our compression merges them and keeps max value. That's correct.
Now about prefix max: We need for each weight, the maximum value for any subset with weight <= that weight. So after sorting and merging same weight, we compute cumulative max.
Now about A: We don't need to sort A because we just iterate all. But we may also prune A entries that exceed L (already done). However note: In combination, even if a subset A has weight <= L, when combined with B subset, total weight might exceed L; but we enforce by checking rem. So fine.
Potential micro: In generating A, we used condition if (nw <= L) to add new subset. However, we also keep subsets that are within L but some may be dominated? Not needed.
Now, is there any case where we need to consider only B subsets without A? Already covered.
Now memory: vectors A,B,Bopt reserved with capacity 512, and items array size 20.
Now complexity: For each query, we also do sorting of B. Sorting 512 int pairs is cheap. However note that B may have less than 512 entries due to pruning (if some subsets exceed L). But worst-case it's 512.
Now we should also consider that depth can be up to 18, but we split by d/2, which yields k=9, m=9 for d=18; but if d=17, k=8, m=9 (since integer division). That's fine; sizes: A up to 2^8=256, B up to 2^9=512. So operations smaller. So worst-case d=18 gives maximum operations.
Now total operations about: generating A: 2^9-1=511 additions; B: 2^9-1=511; sorting B: 512 log2 512 ~ 4600; building Bopt: 512; iterating A: 512 binary searches ~ 4600; total ~ 10k. That's per worst-case query. 100k * 10k = 1e9, which as argued might be okay.
But we can further reduce the constant of sorting: Since B size is at most 512, we could use insertion sort? Not. But we can also avoid sorting by using a "meet-in-the-middle" approach that doesn't require sorting if we use two-pointer after sorting both? Actually we need sorted B for binary search. However we can also use a technique where we precompute for each vertex the list of subsets sorted and compressed. But that's too memory.
Wait, maybe we can precompute for each vertex the list of subsets for the first half (ancestors near root) and second half (near leaf) and then for queries just combine? But since items differ per vertex, still per vertex we would store 2^(depth) subsets. Too large.
Alternatively, we can observe that the tree is a binary heap, and the ancestors of a node are exactly the binary representation of the node index (excluding leading zero). So the set of ancestors is determined by the bits of v. Could we precompute something like DP for each possible prefix of bits? Since depth <= 18, there are at most 2^18 possible paths? Actually each node number corresponds to a unique path from root (the binary representation of its index). So number of distinct paths equals N, up to 2^18-1. So not many distinct paths? Actually N itself is number of nodes, each node has a unique path. So there are N paths.
But we could precompute for each node the "subset list" of all combinations? That would be huge. However maybe we can precompute for each node the best value for each possible total weight up to Lmax? That would be 1e5 per node, too large.
Maybe we can precompute for each node the list of Pareto-optimal subsets, and hope it's small. But worst-case could be 2^depth.
Thus MITM per query seems the intended solution.
Now let's check if there is a known AtCoder problem: "Knapsack for Tree" (typical solution: since depth <= 18, use meet-in-the-middle per query). I've seen similar problem: AtCoder ABC 179 F? Not sure.
I'll check the sample input 2 to see if output matches? Not necessary now.
But we need to be careful about one more thing: In the doubling generation method, the order of subsets is not sorted, but that's fine.
Now we need to ensure that we include the empty subset in both groups. We start with (0,0). Good.
Now finalize.
Potential improvements:
Use arrays for A and B with fixed size and indices to avoid vector growth overhead. But vector with reserve is fine.
Use binary search manually: since Bopt size small, we could just iterate over Bopt to find the max value with weight <= rem, but that would be O(|Bopt|) per A, which would be 512*512=262k per query, too high.
Use two-pointer technique after sorting both A and B by weight. Actually we could sort A as well, and then we can use two-pointer to compute max combined value in O(|A|+|B|) by scanning A ascending and B descending? Let's think: If we sort both A and B by weight. We want max_{a,b} (val_a+val_b) s.t. w_a + w_b <= L. Classic two-list maximum sum with weight constraint can be solved by sorting B by weight, and for each a, binary search. Another method: sort A by weight descending, and maintain a pointer in B for increasing weight? Not simpler.
But we could also use "max convolution" but not.
Given small sizes, binary search is fine.
Now we must pay attention to time for reading input and output. Use scanf/printf or fast IO.
Implementation details:
We'll use:
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
scanf("%d", &N);
vector V(N+1), W(N+1);
for (int i=1; i<=N; ++i) {
scanf("%d %d", &V[i], &W[i]);
}
int Q;
scanf("%d", &Q);
// Pre-allocate vectors
vector<pair<int,int>> A, B, Bopt;
A.reserve(1<<9);
B.reserve(1<<9);
Bopt.reserve(1<<9);
// items array
pair<int,int> items[20]; // first: value, second: weight? Actually we need both. Let's store as value, weight.
code
while (Q--) {
int v, L;
scanf("%d %d", &v, &L);
// collect ancestors
int d = 0;
while (v) {
items[d++] = {V[v], W[v]}; // value, weight
v >>= 1;
}
int k = d / 2; // first k items for A
// generate A
A.clear();
A.emplace_back(0,0); // weight, value
for (int i=0; i<k; ++i) {
int vi = items[i].first, wi = items[i].second;
int sz = A.size();
for (int j=0; j<sz; ++j) {
int nw = A[j].first + wi;
if (nw <= L) {
int nv = A[j].second + vi;
A.emplace_back(nw, nv);
}
}
}
// generate B
B.clear();
B.emplace_back(0,0);
for (int i=k; i<d; ++i) {
int vi = items[i].first, wi = items[i].second;
int sz = B.size();
for (int j=0; j<sz; ++j) {
int nw = B[j].first + wi;
if (nw <= L) {
int nv = B[j].second + vi;
B.emplace_back(nw, nv);
}
}
}
// sort B
sort(B.begin(), B.end()); // sorts by first (weight) then second (value)
// compress and prefix max
Bopt.clear();
for (auto& p : B) {
if (Bopt.empty() || Bopt.back().first != p.first) {
Bopt.emplace_back(p.first, p.second);
} else {
Bopt.back().second = max(Bopt.back().second, p.second);
}
}
for (size_t i=1; i<Bopt.size(); ++i) {
if (Bopt[i].second < Bopt[i-1].second) {
Bopt[i].second = Bopt[i-1].second;
}
}
int ans = 0;
for (auto& a : A) {
int rem = L - a.first;
// binary search in Bopt for weight <= rem
auto it = upper_bound(Bopt.begin(), Bopt.end(), make_pair(rem, INT_MAX));
if (it != Bopt.begin()) {
int bestB = (it-1)->second;
ans = max(ans, a.second + bestB);
} else {
ans = max(ans, a.second);
}
}
printf("%d\n", ans);
}
return 0;
}
But we need to be careful: In Bopt building, we used p.second as value. In sorting B, default sorting sorts by first then second; that's fine.
Now test with sample input.
I'll run mental test for sample 2? Not necessary.
Potential bug: In upper_bound, we use make_pair(rem, INT_MAX). This ensures that any pair with first == rem is considered not greater? Actually upper_bound returns first element > value. So if we have weight exactly rem, we want to include it. Since we use > rem, we need to set the key as (rem, something). The comparator for pair compares first, then second. So if we use (rem, INT_MAX), then any pair with first == rem and second <= INT_MAX will be considered <=? Actually standard upper_bound uses operator<. For pair (a,b) < (rem, INT_MAX) if a<rem or (a==rem and b<INT_MAX). So for any pair with weight == rem, it is less than (rem, INT_MAX) because b (value) < INT_MAX is true. So such pairs would be considered less than the key, thus they would be placed before the key. The upper_bound returns first element > key, so elements with weight == rem are not > key? Check: Is (rem, value) > (rem, INT_MAX)? No, because first equal and second value <= INT_MAX, so value < INT_MAX? Actually if value < INT_MAX, then (rem, value) < (rem, INT_MAX) because second is smaller. So (rem, value) is less than key. So the first element > key would be the first element with weight > rem. Good. So upper_bound gives iterator to first weight > rem. Then it-1 gives last weight <= rem. So correct.
Alternatively we can use lower_bound for weight > rem? lower_bound returns first element not less than key. If we key = (rem+1, -inf), but easier as above.
We could also use: auto it = upper_bound(Bopt.begin(), Bopt.end(), rem, [](int val, const pair<int,int>& p) { return val < p.first; }); That is also fine.
Now, we should also consider that Bopt may be empty? If B generation only produced empty subset? That can happen if all items exceed L? Actually if all items weight > L, then during generation B will only have (0,0) because adding any item would exceed L and be skipped. So B will contain at least (0,0). So Bopt non-empty. Good.
Now time complexity: The code uses vector operations; each query we clear vectors, but clearing doesn't free memory; it just sets size to 0. So A.clear() and B.clear() are O(1) (since they just set size to 0). However they still need to deconstruct elements? For int pairs, trivial. So fine.
Now we need to ensure that A and B do not exceed capacity. For depth=18, k=9 => A max size 2^9 =512, but we may generate less due to pruning. So capacity of 512 suffices. For d=17, k=8 => A size up to 256, B up to 512. So capacity 512 for both is fine.
Now potential issue: In A generation, we push back new entries while iterating over original size. This works because we stored original size before loop. However we must be careful that when we add new entries, they are added to the end, and we are not iterating over them in the same loop. So fine.
Now we need to check correctness for depth=18 with k=9 and m=9. Should be fine.
Now, is there any scenario where we need to handle more than 512 subsets due to not pruning? No, maximum subsets for 9 items is 512. So capacity is safe.
Now, maybe we can further micro-opt: Use array for A and B and manual size variables. But vector is fine.
Now we consider if we can reduce the number of binary searches by using the fact that for each a, we can precompute something? Not.
Now, let's test with a random small case to ensure no bugs. We'll simulate mentally with d=3, k=1? Actually d=3: items: 0,1,2. k=1 => A from item0, B from items1,2. A size up to 2, B up to 4. Works.
Now, one more nuance: The order of items in groups: we split the items as they appear in the items array (leaf first). That's fine. However, any split is fine because subsets are independent.
Now, consider possibility of overflow: sum of values could be up to 1.8e6, fits in int. So ans int fine.
Now, I'll run through sample 2 quickly to check first query output: N=15, etc. Hard to manually verify, but trust.
Now, think about alternative: Using 64-bit for ans? Not needed.
Now, finalize code.
But we must be careful about reading input: N can be up to 262143, Q up to 100000. Use scanf.
Now, ensure to flush output after each line.
Now, complexity wise: 1e9 operations might be heavy, but maybe with -O2 it passes. However we can try to reduce constant factor further.
Possible improvements:
Use C arrays instead of vectors for A and B. Let's try to implement with static arrays to avoid dynamic allocations and bounds checks? Vectors are fine but we can experiment.
Use manual binary search without upper_bound (since Bopt size small, we could linear scan from end? But linear scan for each A would be 512*512=262k per query, too high). But we can precompute for each possible rem? Not.
Use the fact that Bopt size is small, we could for each query precompute an array bestForRem of size L+1? No.
Another idea: Since L <= 1e5 but Bopt size <=512, we can for each query create an array bestB of size up to maxWeight in Bopt? Not needed.
Maybe we can improve the generation of subsets by using bitset representation and using precomputed sums for all masks? Not.
Alternatively, we could precompute for each vertex the "subset list" of its path, but only store the list of (weight, value) after pruning dominated ones. However as argued worst-case can be exponential, but maybe constraints are such that V_i and W_i are random and the number of undominated subsets is small. But we cannot rely on that.
Given the time limit typical for AtCoder problems (like 2 sec) I'd expect the meet-in-the-middle solution to pass. I recall a problem "ABC 246 Ex - 01? Queries?" Not that.
Wait, I recall a problem from AtCoder: "ABC 179 F - Parentheses" no.
Maybe this is from AtCoder "ARC 117 C"? Not.
Let's search memory: There's a known problem "Knapsack for Tree" from JOI? Actually JOI has a problem "JOI 2014 Final" with tree knapsack? Not.
But the constraints N < 2^18 is a strong hint that depth <= 17, and meet-in-the-middle is intended.
I'll check the sample 2 output to see if it matches our algorithm's expected output. Not necessary.
Now, we should also consider that the path includes the vertex itself and ancestors. Our collection includes the vertex itself as the first item (since we start from v). That's correct.
Now, we need to be careful about the parent definition: parent of i is floor(i/2). That's correct for a 1-indexed binary heap.
Now, confirm that while(v) stops when v=0. Since root's parent is 0, and we don't have vertex 0. So we collect items from v up to root inclusive.
Now, we must ensure that we don't accidentally include vertex 0 if v becomes 0. Loop condition while(v) will stop when v==0, so we don't add vertex 0.
Now, we used items array of size 20, but depth could be up to 18, so 20 is enough.
Now, potential bug: In B generation, we used items[i].first for value, .second for weight. That's consistent.
Now, think about using pair<int,int> for weight and value. In A and B we store (weight, value) because we sort by weight later. Good.
Now, we might want to add a small optimization: If A is empty? It always has at least (0,0). So fine.
Now, we should also consider the case where L is very small, causing many subsets to be pruned. That reduces sizes.
Now, regarding vector clearing: after clearing, the capacity remains, so no reallocation. However we also need to ensure that after clearing, when we push_back, we don't exceed capacity; but capacity is reserved to 512, so it's fine.
But what about when depth is 18 and k=9, A size could be 512, which fits capacity. So we reserved 512. But for d=18, k=9, A size exactly 512. For d=17, k=8, A size 256, B size 512. So B capacity 512 is enough.
Now, one more improvement: We can avoid building Bopt as separate vector by using B directly with prefix max after sorting and merging duplicates. But merging duplicates in-place in B would be messy; easier to use Bopt.
Alternatively, we could sort B and then compress in-place: After sorting, we can keep two pointers to compress B into a new size, but B is a vector; we can do it in-place. However simpler to use Bopt.
Now, we might want to use integer arrays for A and B to avoid overhead of pair's constructor? Not necessary.
Now, consider potential speed bottleneck: The binary search uses upper_bound, which is logarithmic but may involve function calls? That's fine.
Now, total operations: 1e5 * ( generation 1022 + sorting 4600 + prefix 512 + binary search 4600 ) ≈ 1e5 * 10,734 ≈ 1.07e9. Might be borderline but with -O2 perhaps 1e9 operations per second? Actually modern CPUs can do about 3-4e9 simple ops per second in C++? Not exactly; each operation may be multiple cycles. Usually 1e9 operations may take around 0.3-0.5 seconds if extremely optimized, but with branches and memory accesses, it may be slower. But 1e9 could be near 1 second. But we have overhead of vector accesses and sorting (which involves swaps). Sorting 512 elements 1e5 times means 100k * 512 * log2(512) ~ 100k * 4600 = 460 million comparisons. Each comparison is cheap. I think it can pass within 2 sec.
But to be safe, we can implement with static arrays.
Let's try to implement with arrays for A and B to see if we can reduce overhead.
We'll declare:
pair<int,int> A[1<<9];
int a_sz;
pair<int,int> B[1<<9];
int b_sz;
pair<int,int> Bopt[1<<9];
int bopt_sz;
Then we manually manage sizes.
Generation for A:
a_sz = 1;
A[0] = {0,0};
for (int i=0; i<k; ++i) {
int vi = items[i].first, wi = items[i].second;
int old_sz = a_sz;
for (int j=0; j<old_sz; ++j) {
int nw = A[j].first + wi;
if (nw <= L) {
A[a_sz++] = {nw, A[j].second + vi};
}
}
}
Similarly for B.
Sorting B: we can use std::sort(B, B+b_sz). Since B is array, sort works with pointers.
ans = 0;
for (int i=0; i<a_sz; ++i) {
int rem = L - A[i].first;
// binary search in Bopt
auto it = upper_bound(Bopt, Bopt+bopt_sz, make_pair(rem, INT_MAX));
if (it != Bopt) {
ans = max(ans, A[i].second + (it-1)->second);
} else {
ans = max(ans, A[i].second);
}
}
This avoids vector overhead. Could be slightly faster.
We must be careful that a_sz may exceed array size? Max a_sz for k up to 9 is 512, array size 512 fine. But what if k=9 and we prune none, a_sz = 512 exactly. Array size 1<<9 = 512, so we need index 0..511, a_sz max 512, but if a_sz becomes 512, last index 511, okay. However we need to ensure we don't write beyond 512. For k=9, initial a_sz=1; after processing 9 items, a_sz will be exactly 2^9 = 512. So array size of 512 is enough. But we need to allow storing up to 512 entries; index 512 would be out of bounds. So we should declare size 513 to be safe? Actually if a_sz becomes 512, the highest valid index is 511. Starting from a_sz=1 (index0). After processing, a_sz increments to 512, last assigned index is 511. So array of size 512 (indices 0..511) is enough. However if we use a_sz as the count, we need to ensure that we don't attempt to assign to A[512] because a_sz after increment becomes 512, but the last assigned index was 512-1=511. So array size 512 works. But to be safe, we could allocate 520.
Similarly for B: max size 1<<9 =512 (if m=9). So array size 512 is fine.
Now, note that for d=18, k=9, m=9, both arrays size 512. For d=17, k=8, A size 256, B size 512. So B array size 512 is enough.
Now, we need to declare Bopt size also 512.
Now, we must be careful that Bopt may have fewer entries than B after compression.
Now, we also need items array size maybe 20.
Now, overall memory is small.
Now, we must ensure that sorting uses correct range: sort(B, B+b_sz). That's fine.
Now, one more micro-optimization: For B, we can sort using std::sort with lambda that compares first only, but default is fine.
Now, we need to include for sort and upper_bound.
Now, we can implement.
Now, check that we didn't forget to reset a_sz and b_sz each query. We'll set them at start.
Now, potential bug: In A generation, we use A[j] for j from 0 to old_sz-1. But while we add new entries, A gets overwritten? Since we are writing to A[a_sz] which initially is beyond old_sz, and we are reading from indices < old_sz, which are not overwritten. That's fine.
Now, confirm that we are using items[i].first as value, .second as weight. In A and B we store (weight, value). That's fine.
Now, we might consider swapping order to (value, weight) but we need to sort by weight, so we store weight first.
Now, finalize code.
Now, we need to test with sample inputs.
We'll simulate sample 1 with array implementation:
First query: v=1,L=1. items: d=1, k=0. A generation: a_sz=1, A[0]=(0,0). No loop for i<0. B generation: since k=0, m=1. B: b_sz=1; B[0]=(0,0). For i from k to d-1 => i=0. vi=1, wi=2. old_sz=1. For j=0: nw=2>1, skip. So b_sz remains 1. B sorted: trivial. Bopt: Bopt[0]=(0,0). bopt_sz=1. Iterate A: a[0]=(0,0), rem=1. upper_bound on Bopt with (1,INT_MAX): Bopt has (0,0). Since (0,0) < (1,INT_MAX) because 0<1, so upper_bound returns Bopt+1 (end). it != Bopt => true, it-1 = Bopt, bestB=0. ans=0. Output 0. Good.
Second query: v=2,L=5. items: d=2: items[0]=(2,3), items[1]=(1,2). k=1. A: a_sz=1; i=0: vi=2, wi=3; old_sz=1; j=0: nw=3<=5 => A[1]=(3,2); a_sz=2. So A = [(0,0),(3,2)].
B: m=1; b_sz=1; i=1: vi=1, wi=2; old_sz=1; j=0: nw=2<=5 => B[1]=(2,1); b_sz=2. B sorted: (0,0),(2,1). Bopt: after compress: (0,0),(2,1); prefix max: (0,0),(2,1). Now iterate A: a0: rem=5 => upper_bound(5) -> end, it-1 -> (2,1) => ans=0+1=1; a1: rem=2 => upper_bound(2) -> end (since no >2), it-1 -> (2,1) => 2+1=3; ans=3. Good.
Now, we must ensure that we use correct data types: int for all, but sum of values could be up to 1.8e6, fits in 32-bit signed.
Now, we could also use short loops.
Now, final code:
#include
#include
using namespace std;
const int MAX_SUB = 1<<9; // 512
int main() {
int N;
scanf("%d", &N);
int V[N+1], W[N+1];
for (int i=1; i<=N; ++i) {
scanf("%d %d", &V[i], &W[i]);
}
int Q;
scanf("%d", &Q);
// pre-allocate arrays for meet-in-the-middle
pair<int,int> A[MAX_SUB], B[MAX_SUB], Bopt[MAX_SUB];
pair<int,int> items[20]; // value, weight
code
while (Q--) {
int v, L;
scanf("%d %d", &v, &L);
// collect ancestors
int d = 0;
while (v) {
items[d++] = {V[v], W[v]}; // value, weight
v >>= 1;
}
int k = d / 2;
// generate A (first k items)
int a_sz = 1;
A[0] = {0, 0}; // weight, value
for (int i=0; i<k; ++i) {
int vi = items[i].first, wi = items[i].second;
int old_sz = a_sz;
for (int j=0; j<old_sz; ++j) {
int nw = A[j].first + wi;
if (nw <= L) {
A[a_sz++] = {nw, A[j].second + vi};
}
}
}
// generate B (remaining items)
int b_sz = 1;
B[0] = {0, 0};
for (int i=k; i<d; ++i) {
int vi = items[i].first, wi = items[i].second;
int old_sz = b_sz;
for (int j=0; j<old_sz; ++j) {
int nw = B[j].first + wi;
if (nw <= L) {
B[b_sz++] = {nw, B[j].second + vi};
}
}
}
// sort B by weight
sort(B, B+b_sz);
// compress B and prefix max
int bopt_sz = 0;
for (int i=0; i<b_sz; ++i) {
if (bopt_sz == 0 || Bopt[bopt_sz-1].first != B[i].first) {
Bopt[bopt_sz++] = B[i];
} else {
if (B[i].second > Bopt[bopt_sz-1].second)
Bopt[bopt_sz-1].second = B[i].second;
}
}
for (int i=1; i<bopt_sz; ++i) {
if (Bopt[i].second < Bopt[i-1].second)
Bopt[i].second = Bopt[i-1].second;
}
int ans = 0;
for (int i=0; i<a_sz; ++i) {
int rem = L - A[i].first;
// binary search for largest weight <= rem in Bopt
auto it = upper_bound(Bopt, Bopt+bopt_sz, make_pair(rem, 2000000000));
if (it != Bopt) {
ans = max(ans, A[i].second + (it-1)->second);
} else {
ans = max(ans, A[i].second);
}
}
printf("%d\n", ans);
}
return 0;
}
We used 2000000000 as large second; INT_MAX would be better but we can define.
Now, we need to include and perhaps . Already included.
Now, check: In B generation, we used B[0] = {0,0} and then add. Good.
Now, what about the case where k=0? Then the loop for A generation is skipped, a_sz remains 1 with (0,0). Good. For B, loop from i=k (0) to d-1. That processes all items. Good.
Now, for d=0? Not possible.
Now, finalize.
But we should test edge case: N=1, Q=1, v=1, L=some. items: only (V1,W1). d=1, k=0. A: (0,0). B: generate from item: (0,0) and possibly if weight <= L, add (W1,V1). Then combine: A(0,0) with B best. Works.
Now, potential issue: In Bopt building, we need to ensure that Bopt is sorted by weight, which it is because B is sorted.
Now, we used auto it = upper_bound(Bopt, Bopt+bopt_sz, make_pair(rem, 2000000000)); The comparator for pair uses first then second. So if rem is, say, 5 and Bopt has (5,100), then (5,100) < (5,2000000000) because second is less, so upper_bound returns first element > (5,2000000000). Since there is no element with first >5 or first==5 and second >2000000000, it returns end. So (it-1) is the last element, which includes (5,100) if it's the last. Good. If there are multiple (5,*) entries, they are merged into one with max value, so fine.
Now, we could also use a custom comparator: upper_bound(Bopt, Bopt+bopt_sz, rem, [](int val, const pair<int,int>& p) { return val < p.first; }); That would be more direct. Let's maybe implement that to avoid constructing pair. But it's okay.
Now, consider if rem < 0: Since we only consider A subsets with weight <= L (we prune those > L), rem is non-negative. So fine.
Now, final answer.
Now, let's consider possible further optimization: If L is very large (like 1e5) but total weight of all items is small (<= 180), we could cap L to total weight of items on path. But not necessary.
Now, we might also consider that Q up to 1e5, and we are using printf for each answer, which is fine.
Now, we need to ensure we include and .
Now, I think this will pass.
Now, as a final check, I'll run through a case with depth 18 to ensure arrays don't overflow. For d=18, k=9, a_sz max 512, array size 512; but a_sz becomes 512, which means we need indices 0..511. That's okay. For B, b_sz max 512. So array size 512 is enough.
But note: When generating B, we start with b_sz=1, then for each of m=9 items, we potentially double. So after 9 items, b_sz becomes 512. So final index 511 used. Array size 512 provides 512 elements, indices 0..511. So it's fine.
Now, one more nuance: In the loops for generating A and B, we use "int old_sz = a_sz;" then loop j from 0 to old_sz-1. Within loop, we may add new entries to A. That's correct.
Now, we must ensure that we don't exceed array bounds when adding. When a_sz < MAX_SUB, we can add. Since we start with a_sz=1, after each item we can add up to old_sz new entries. So maximum a_sz = 1 * 2^{k} = 512. So at the moment before adding the last item, a_sz = 256. old_sz = 256. We will attempt to add up to 256 new entries, which would bring a_sz to 512. So we need to ensure that A has size at least 512. Yes.
Now, all good.
Now, code final.
But wait, there is a subtle bug: In items array, we store value first, weight second. In generation, we correctly use .first as value, .second as weight. However, in A and B we store (weight, value). That's fine.
But when we later sort B, we sort by weight first then value. That's correct.
Now, consider if we have duplicate weights with different values; after merging duplicates, we keep max value. Then we compute prefix max. That ensures for each weight, we have the best value for that weight or less.
Now, finalize.
Now, before final answer, I'll think about possible alternative solution: Use DP with "small depth" but compress using "dominance". But we've settled.
Now, produce final answer.
But the problem statement includes: "All values in input are integers." and constraints. Good.
Now, we output each answer on its own line.
Now, test with sample 2? I can simulate quickly but not necessary.
Now, I'll write the final solution.
One more thought: The root's parent is floor(1/2)=0, so our while(v) loop stops when v becomes 0, so we don't add item for 0. Good.
Now, confirm that we don't need to handle 0-indexing.
Now, final code.
Now, I'll produce answer. ```cpp
#include
#include
using namespace std;
const int MAX_SUB = 1 << 9; // 512, the maximum number of subsets in one half
int main() {
int N;
scanf("%d", &N);
int V[N + 1], W[N + 1];
for (int i = 1; i <= N; ++i) {
scanf("%d %d", &V[i], &W[i]);
}
code
int Q;
scanf("%d", &Q);
// work arrays for meet‑in‑the‑middle
pair<int, int> A[MAX_SUB], B[MAX_SUB], Bopt[MAX_SUB];
pair<int, int> items[20]; // (value, weight) on the current path
while (Q--) {
int v, L;
scanf("%d %d", &v, &L);
// collect the items on the path from v to the root
int d = 0;
while (v) {
items[d++] = {V[v], W[v]};
v >>= 1;
}
int k = d / 2; // first k items -> group A
// ---- generate all subsets of group A (weight ≤ L) ----
int a_sz = 1;
A[0] = {0, 0}; // (weight, value)
for (int i = 0; i < k; ++i) {
int vi = items[i].first, wi = items[i].second;
int old_sz = a_sz;
for (int j = 0; j < old_sz; ++j) {
int nw = A[j].first + wi;
if (nw <= L) {
A[a_sz++] = {nw, A[j].second + vi};
}
}
}
// ---- generate all subsets of group B (weight ≤ L) ----
int b_sz = 1;
B[0] = {0, 0};
for (int i = k; i < d; ++i) {
int vi = items[i].first, wi = items[i].second;
int old_sz = b_sz;
for (int j = 0; j < old_sz; ++j) {
int nw = B[j].first + wi;
if (nw <= L) {
B[b_sz++] = {nw, B[j].second + vi};
}
}
}
// sort B by weight
sort(B, B + b_sz);
// compress: keep only the best value for each weight
// and build prefix maximum (best value for weight ≤ w)
int bopt_sz = 0;
for (int i = 0; i < b_sz; ++i) {
if (bopt_sz == 0 || Bopt[bopt_sz - 1].first != B[i].first) {
Bopt[bopt_sz++] = B[i];
} else {
if (B[i].second > Bopt[bopt_sz - 1].second)
Bopt[bopt_sz - 1].second = B[i].second;
}
}
for (int i = 1; i < bopt_sz; ++i) {
if (Bopt[i].second < Bopt[i - 1].second)
Bopt[i].second = Bopt[i - 1].second;
}
// ---- combine the two groups ----
int ans = 0;
for (int i = 0; i < a_sz; ++i) {
int rem = L - A[i].first;
// last element with weight ≤ rem
auto it = upper_bound(Bopt, Bopt + bopt_sz, make_pair(rem, 2000000000));
if (it != Bopt) {
ans = max(ans, A[i].second + (it - 1)->second);
} else {
ans = max(ans, A[i].second);
}
}
printf("%d\n", ans);
}
return 0;