We are given n and s_i: for each i (1-indexed), s_i = sum_{j < i, p_j < p_i} p_j.
We need to reconstruct the permutation p_1..p_n.
We need to find p_i such that these sums hold.
This is a known problem: reconstruct permutation from prefix smaller sums. There is a typical solution using Fenwick tree or BIT over positions 1..n (values). Since p is a permutation of 1..n, we need to assign each p_i a distinct value from 1 to n. The condition relates to the sum of previous numbers that are smaller than p_i.
Think from the end: If we process from i=n down to 1, we can determine p_i based on s_i and the set of remaining unused numbers? However s_i is sum of smaller previous numbers. That depends on the values that appear before i, which we haven't determined if we go backwards? But we could consider constructing permutation in reverse: If we process from right to left, we could determine p_i as the smallest number such that the sum of all smaller numbers among the already placed ones (to the right) equals something? Wait s_i involves earlier indices, not later. So processing from left to right: we know p_1..p_{i-1} when we assign p_i. However we don't know p_i's value, but we can choose it such that the sum of earlier smaller numbers equals s_i. Since we know the set of used numbers and their positions? But positions only matter for order: earlier elements are fixed. So we can maintain a data structure of values already used, and for a candidate p_i, compute sum_{j < i, p_j < p_i} p_j. We need that to equal s_i. But p_i is unknown. This seems like we need to find a value such that the cumulative sum of smaller used values equals s_i. Since we know the set of used numbers (which are values already assigned to earlier positions), we can compute for any candidate value v, the sum of used numbers < v. That must equal s_i. And v must be unused. Also s_i is given. So we need to find v such that sum_{used < v} = s_i and v is unused. Because the sum only depends on used numbers less than v, not on order.
But note: The permutation is unique, so there will be exactly one such v.
We can process i=1..n. Initially used set empty. For i=1: s_1 = 0 (since no j < 1). So condition: sum of used numbers less than p_1 must be 0. Since used empty, any value would satisfy? But we also need that p_1 is unused. However if used empty, sum_{used < v} = 0 for any v. So p_1 could be any number? But the permutation must be valid and later constraints will restrict. However from given s, they guarantee a unique permutation. For i=1, s_1=0 always? Let's check examples: first example s = [0,0,0], second [0,1], third [0,1,1,1,10]. Indeed s_1 is always 0 because there is no j<1. So s_1 is always 0. So p_1 is not determined uniquely by s_1 alone, but by the whole sequence. So we cannot determine p_1 just by that. Instead we need to choose p_1 such that future s_i can be satisfied.
Thus forward processing with only condition sum_{used<v}=s_i is insufficient: that condition is necessary but not sufficient because future sums depend on which values are used and in which order. However, maybe it's also sufficient: because if we always pick the smallest possible v? Or maybe there is a known approach: Since s_i is sum of earlier smaller numbers, if we process from right to left, we can determine p_i by considering the set of numbers that will be placed after? There is known problem "Reconstructing permutation from prefix sums of smaller numbers" can be solved using BIT and binary search, akin to "order statistic by sum". Actually there is a known Codeforces problem: "Recover the permutation from the given s array". I recall a problem: 1208D? Or maybe 1746C? Not sure. Let's think.
We have p permutation of 1..n. For each i, define s_i = sum of p_j for j < i and p_j < p_i. Given s, find p.
This is reminiscent of the concept of "inverse Fenwick tree" or "construct permutation from prefix smaller sums". Another viewpoint: If we think about processing from the largest value down to smallest, maybe we can reconstruct positions.
Alternatively, define for each i, the set of indices j < i with p_j < p_i. The sum of p_j in that set is s_i. But p_j are numbers from 1..n.
Maybe we can consider the permutation in terms of a binary indexed tree that tracks values used. Suppose we have an array BIT of size n that initially has all numbers 1..n present (i.e., each position value = 1). The permutation is built from left to right: we need to assign a value to p_i such that the sum of values less than p_i among already assigned ones equals s_i. But we haven't assigned earlier ones? Actually earlier ones are already assigned. So we know exactly which numbers have been used. So we can compute prefix sums of used numbers. However we need to choose p_i from the unused numbers. The condition: prefix sum of used numbers below p_i equals s_i. Let used = set of numbers assigned so far. Then for each candidate v in unused, compute S(v)= sum_{x in used, x < v} x. We need S(v) = s_i. Since used grows over time, we need to choose v that matches. But is there always exactly one such v? It seems plausible because s_i values are derived from some hidden permutation, so as we process in order, the correct v will satisfy exactly. But could there be multiple unused v giving same S(v)? Possibly if the used set has gaps. For example, used = {1,4}. Then S(2)=1, S(3)=1, S(5)=1+4=5. So both 2 and 3 give S=1. So there could be ambiguity. However the real permutation would have p_i be one of them. But then later constraints might break ambiguity. So we need a deterministic way to resolve which one to pick. Perhaps the algorithm processes from right to left and uses the fact that later s_i give more information.
Let's try to formulate inversion: Let's denote for each value x (1..n), the sum of smaller values that appear before it? Actually s_i is defined per position. Could we think of constructing the permutation by iterating values from n down to 1, determining their positions? For each value v, consider where it appears in the permutation. The contribution of v to s_i for indices after its position: v will be added to s_i for any i such that p_i > v and i > pos(v). That is, for each later element with greater value, v contributes to its s_i. So if we know the positions, we can compute s_i as sum of all smaller values appearing earlier. Conversely, if we process values from largest to smallest, we can determine the position of the current value based on s_i values of later indices? Let's attempt.
Let pos[k] = index i such that p_i = k. We know n unknown positions.
For each index i, s_i = sum_{v < p_i} v * [pos[v] < i]. That is, sum over values less than p_i that appear before i.
Alternatively, for each value v, it contributes v to s_i for all i > pos[v] such that p_i > v.
So if we process values in decreasing order, we can use the s_i values to determine where v should be placed, maybe by considering cumulative sums.
Define an array t_i that initially is some kind of "prefix sums of placed smaller numbers"? Not exactly.
Another approach: Use a binary indexed tree (Fenwick) over indices 1..n where each index initially holds the candidate s_i? Hmm.
I recall a known solution: We can reconstruct p from s using a BIT that stores the numbers 1..n, and we find the last element first: For i=n, s_n = sum of all p_j < p_n for j < n. Since all previous n-1 numbers are smaller than p_n if p_n is the maximum? Not necessarily. But we can try to deduce p_n.
Observation: The total sum of all numbers 1..n is T = n(n+1)/2. The sum of s_i over all i? Might not help.
Maybe we can find each p_i from the end using a BIT that maintains available numbers and we need to find a value v such that the sum of all smaller available numbers equals something? Let's try reverse processing.
Consider processing i from n down to 1. At step when we consider i, we have already determined p_{i+1}..p_n. We need to determine p_i. The condition for s_i involves only j < i, i.e., numbers that are to the left of i, which we haven't determined yet? Actually if we are going backward, at step for i, we know the values that will be placed to the right (p_{i+1}..p_n), but we do not know the values to the left (p_1..p_{i-1}). However, we might be able to deduce p_i from s_i and the known values? Because s_i is sum of p_j for j < i with p_j < p_i. That sum only includes values that are left of i. Since we don't know them, it's not directly helpful. But perhaps we can consider total sum of all numbers that are less than p_i and appear before i equals s_i. However we might also know the total set of numbers that appear before i (the left side) is the complement of numbers placed after i (the right side) minus p_i itself? Actually the set of all numbers is {1..n}. At step i (processing backward), we have already assigned values to indices > i, i.e., set R = {p_{i+1},...,p_n}. The remaining numbers, including p_i and those for indices < i, are L_rem = all numbers \ R. We need to assign p_i from L_rem. The sum s_i is the sum of numbers from L_rem (excluding p_i) that are less than p_i and will appear before i. But we don't know which of those numbers will appear before i; they all will (since all indices < i will be filled with the remaining numbers). So all numbers in L_rem except p_i will eventually be placed before i. Therefore, the set of numbers that appear before i is exactly L_rem \ {p_i}. So s_i = sum of all numbers in L_rem \ {p_i} that are less than p_i. That's a key insight! Because when processing from right to left, the indices to the left of i are all unfilled yet, but they will eventually be filled with the remaining numbers (except p_i). The order of those left numbers doesn't affect the sum of those that are less than p_i appearing before i: any order, as long as all those numbers are placed before i (since all indices < i will be taken by exactly those numbers). So indeed, for a given candidate value v for p_i, and given the set of remaining numbers (excluding v) which are all placed before i, s_i should equal the sum of all numbers in that remaining set that are less than v. That sum depends only on v and the set of remaining numbers (excluding v). So we can compute for each candidate v in the remaining set, let S_rem(v) = sum of all numbers x in remaining set (excluding v) such that x < v. That must equal s_i. Since s_i is known, we can solve for v.
Now, is this uniquely determined? The remaining set is known (the numbers not yet placed to the right). For each v in that set, we can compute the sum of smaller remaining numbers (excluding v). The condition S_rem(v) = s_i. Since the hidden permutation satisfies this, there must be exactly one v that meets the condition. And we can find it.
But we have to ensure that for each i, when we go backward, the condition is exactly that: s_i = sum_{x in L_rem, x < p_i} x. Because all indices j < i will be occupied by exactly the numbers in L_rem \ {p_i}. The order among them doesn't matter because the condition only cares about which numbers are less than p_i and appear before i. Since all of them appear before i (as j < i), it's simply all numbers from the remaining set (excluding p_i) that are less than p_i. So indeed, this is correct.
Thus we can reconstruct p_n, p_{n-1}, ..., p_1 by maintaining the set of numbers not yet used (i.e., those that will be placed to the right? Actually as we go backwards, we start with an empty set of used numbers for the right side. Initially, for i=n, the set of numbers placed after n is empty (since no indices > n). So the remaining set L_rem is all numbers {1..n}. For i=n, we have s_n = sum of all numbers less than p_n that appear before n. But before n are all other numbers (since they will be placed at indices 1..n-1). So indeed, s_n = sum of all numbers in the full set (1..n) that are less than p_n, excluding p_n itself? Actually careful: For i=n, L_rem = all numbers not yet placed to the right? At step i=n, we haven't placed any numbers to the right (since none). The set of numbers that will be placed to the left (indices < n) is all numbers except p_n. So s_n = sum_{x in {1..n} \ {p_n}, x < p_n} x. That is sum of all numbers less than p_n. This uniquely determines p_n: given s_n, we need to find v such that sum_{x=1}^{v-1} x = s_n. Because all numbers less than v are exactly 1..v-1. But note: the set of numbers less than v and not equal to v is exactly {1,2,...,v-1} provided that v is between 1 and n and all those numbers are present (they are, as it's a permutation). So s_n = (v-1)v/2. So p_n is the smallest v such that (v-1)v/2 >= s_n? Actually we need equality. Since sum of 1..v-1 = v(v-1)/2. So given s_n, we can solve for v. However, note that v could be such that some numbers less than v are not all present because they might be placed to the right? But there are no numbers to the right. So all numbers less than v are indeed present in the left side. So v is determined by s_n = v(v-1)/2. But is that always integer? For the hidden permutation, yes. So we can compute p_n as the integer v satisfying v(v-1)/2 = s_n. Since s_n is given, we can compute v = floor((1+sqrt(1+8s_n))/2). But we must also ensure that v is within 1..n. However, there might be a twist: What if some numbers less than v are not actually all present before i? But they are, because all indices < i are filled with all numbers except p_i. So indeed the left side contains all numbers except p_i. So all numbers less than p_i are present if they are not equal to p_i. But wait, if p_i is less than some numbers, numbers greater than p_i are also present left, but they don't matter. So for i=n, s_n = sum of all numbers less than p_n. So yes.
But check with examples: Example 1: n=3, s=[0,0,0]. For i=3, s_3=0. We need v such that sum_{x<v}=0 => v=1 (since sum of numbers <1 is 0). So p_3 =1? But the output says p = [3,2,1], so p_3=1. Yes, that matches. Example 2: n=2, s=[0,1]. For i=2, s_2=1. We need v such that sum_{x<v}=1 => v=2? Because sum of 1..(v-1) =1 when v-1=1 => v=2. So p_2=2. Output says p=[1,2]. Good. Example 3: n=5, s=[0,1,1,1,10]. For i=5, s_5=10. Sum 1+2+3+4 =10 => v-1=4 => v=5. So p_5=5. Output says last element is 5. Yes.
Now for i=n-1: After determining p_n, the remaining set (numbers that will go to the left of i=n-1) is all numbers except those already placed to the right (i.e., p_n). Actually when processing backward, after fixing p_n, the set of numbers that are to the right of i=n-1 (i.e., indices > n-1) is {p_n}. So the remaining numbers L_rem for i=n-1 is all numbers except those placed to the right? Wait careful: When we are at i = n-1, the indices > n-1 are n only, which has p_n already determined. So the set of numbers that will be placed after i is R = {p_n}. The numbers that will be placed before i (indices < n-1) plus p_i itself are the complement of R: that is all numbers except p_n. But among those, p_i is at index i, and the rest go to indices 1..n-2. So indeed, the numbers that appear before i (j < n-1) are exactly the set of all numbers except p_n and except p_{n-1} (i.e., the remaining after removing R and p_i). So L_rem_before_i = all numbers \ (R ∪ {p_i}) = {1..n} \ {p_n, p_{n-1}}.
Thus, for i=n-1, s_{n-1} = sum of all numbers in L_rem_before_i that are less than p_{n-1}. That is sum of numbers x in the set (all numbers except p_n and p_{n-1}) such that x < p_{n-1}. So s_{n-1} = (sum of all numbers less than p_{n-1}) - (if p_n < p_{n-1} then p_n else 0) because the set of all numbers less than p_{n-1} is {1,2,...,p_{n-1}-1}. However, some of those numbers might be p_n if p_n < p_{n-1}. Also, note that p_{n-1} itself is not included. So we need to subtract from the total sum of numbers less than p_{n-1} any numbers that are not in the left side, i.e., numbers that are placed to the right (p_n) and are less than p_{n-1}. Since the only number to the right is p_n, we subtract p_n if p_n < p_{n-1}. So s_{n-1} = (p_{n-1}(p_{n-1}-1)/2) - (p_n if p_n < p_{n-1} else 0). And we know p_n already. Then we can solve for p_{n-1}. But careful: The left side also includes numbers that are not less than p_{n-1}? No. So equation holds.
But more generally, when processing backwards, we maintain a data structure (like a Fenwick tree) over the values 1..n that initially have all values present (value=1 meaning available). As we determine p_i, we remove that value from the set (since it's placed at position i). But we need to compute for a candidate v the sum of all numbers < v that are still available (i.e., not yet assigned to positions > i, i.e., those that will be placed to the left? Actually at step for i, the set of numbers that are still available (not yet assigned to positions > i) is the complement of the set of numbers already assigned to positions i+1..n. Let's denote the set of values assigned to the right as R. These have been removed from our available set. The remaining set (available) includes p_i and all numbers that will go to the left. We need to compute for each candidate v in the available set, the sum of numbers in the available set that are less than v, excluding v itself, which is exactly s_i.
But careful: s_i = sum_{j < i, p_j < p_i} p_j. The numbers that are placed to the left are exactly the available set minus {p_i}. So we need sum of available numbers < p_i (excluding p_i). That equals s_i.
Thus, if we maintain a data structure over values 1..n that initially has all values present (value = 1 meaning it's still available). As we iterate i from n down to 1, we need to find a value v such that the sum of available numbers less than v equals s_i. Then set p_i = v, and remove v from the available set (since it's now placed at i). This will give the correct permutation.
But is this condition sufficient and will produce a unique v? Since the hidden permutation satisfies it, yes. But we must ensure that for each i, there is exactly one v meeting that condition given the current available set and s_i. Could there be multiple v with the same sum of smaller available numbers? Possibly, as earlier example with used set {1,4} gave same sum for 2 and 3. But in that scenario, the available set would contain 1,2,3,4? Actually if available set = {1,2,3,4} and we remove none? But we process backward, available set initially all numbers. For i=n, sum of smaller available numbers for v is sum_{x<v} x because all numbers are available. That's strictly increasing with v? Actually sum_{x=1}^{v-1} x is increasing as v increases, and it's strictly increasing because each step adds v-1. So it's injective, so unique v.
For later steps, when some numbers have been removed (those placed to the right), the sum of smaller available numbers for v may not be strictly increasing? Let's test. Suppose available set = {1,2,4}. For v=2: sum of available <2 = 1. For v=3: v=3 not in set, but we only consider v in set. For v=4: sum of available <4 = 1+2=3. So it's increasing but not necessarily strictly? 1->3, yes strictly because as v increases, the set of smaller available numbers includes all those for previous v plus possibly additional numbers? Not exactly: If available set has gaps, it's still monotonic non-decreasing, but could be equal for consecutive values? For v=2 and v=3: but 3 not in set. For v=4 and v=5 (5 not in set). If both v1 and v2 are in set with v1 < v2, then the sum of available numbers less than v2 includes sum of available numbers less than v1 plus sum of available numbers in [v1, v2) (i.e., between v1 inclusive? Actually less than v2 includes numbers less than v1 plus numbers in [v1, v2) that are available. Since v1 itself is less than v2, but sum of available numbers less than v2 includes v1 if v1 is available and < v2. However, v1 is itself not included because it's less than v2? Actually v1 < v2, so v1 is included in sum_{x<v2} if v1 is available. But sum_{x<v1} does not include v1. So sum_{x<v2} = sum_{x<v1} + (sum of available numbers x where v1 <= x < v2). Since there is at least v1 itself (if v1 is available), which is positive, then sum_{x<v2} > sum_{x<v1}. So strictly increasing. More formally, for any two available values v1 < v2, the set {x in available: x < v2} includes {x in available: x < v1} ∪ {v1} ∪ (other numbers between v1 and v2). Since v1 is in available and v1 < v2, and v1 is not in the first set (since x < v1 excludes v1), the sum increases by at least v1 > 0. So the sum function is strictly increasing over the sorted list of available values. Therefore, for a given s_i, there is at most one available v satisfying sum_{available < v} = s_i. And since the true permutation yields such a v, it is unique.
Thus the backward approach works: maintain a sorted data structure (like Fenwick tree) that supports:
- For a given sum s, find the smallest v such that the prefix sum (sum of values of elements <= v) is > s? Wait we need sum of available numbers less than v equals s. Since sum_{available < v} = s. We can compute prefix sums up to v-1. Equivalent to find v such that cumulative sum up to v-1 equals s and v is present in the set (since we need to pick v). Because the sum function is strictly increasing over available v, we can binary search for v where prefix sum (excluding v) equals s.
Alternatively, we can think: We have a BIT where each value x has weight x (or maybe weight 1 for counting? Actually we need sum of values, not count). So we need to store the values themselves as weights to compute sum of existing numbers. But we also need to remove numbers once used. So BIT over 1..n with initial values: for each x, we set BIT[x] = x (or maybe we need to update point). But typical BIT stores sums; we can set initial array A[x] = x for all x. Then prefix sum up to k is sum_{x=1}^{k} x = k(k+1)/2 initially. As we remove numbers, we set A[x]=0 for those removed. Then we need to find v such that sum_{x=1}^{v-1} A[x] = s_i. However we must also ensure that v is still present (A[v] > 0). Since the sum of A[x] for x<v is s_i, and we know that v is present, we can find v via binary search on BIT using the cumulative sums.
But note: The sum we need is sum of available numbers less than v, which is exactly prefix sum up to v-1. So we need to find v such that prefix(v-1) = s_i. However, we also know that v is the smallest value where prefix(v) > s_i? Because prefix(v) = prefix(v-1) + A[v]. Since A[v] = v if v is present else 0. But if v is present, prefix(v) = s_i + v. So we can find the smallest v such that prefix(v) > s_i, because then v must be the one where prefix(v-1) = s_i and A[v] > 0. But we must ensure that prefix(v-1) exactly equals s_i; if there is a gap, prefix(v) might be > s_i even if v is not present? Let's consider: Suppose available set = {1,4}. A[1]=1, A[2]=0, A[3]=0, A[4]=4. Prefix sums: prefix(0)=0, prefix(1)=1, prefix(2)=1, prefix(3)=1, prefix(4)=5. For s_i=1, we want v such that sum of available < v =1. Candidates: v=2? But 2 not available. v=3 not available. v=4? sum of available <4 =1, so v=4 works. Also v=2? Not available, can't choose. So we need to choose the available v. For s_i=1, we look for smallest v such that prefix(v) > s_i. prefix(1)=1 not >1, prefix(2)=1 not >1, prefix(3)=1 not >1, prefix(4)=5 >1. So smallest v with prefix(v) > s_i is 4, which is available. Does this always hold? If the sum function is strictly increasing over available values, then the values of prefix at indices that are available will jump by v. For non-available indices, prefix stays the same. So the condition prefix(v) > s_i will be satisfied at the first available v for which prefix(v-1) <= s_i and prefix(v) > s_i, but note that for a non-available v, prefix(v) = prefix(v-1) (since A[v]=0). So prefix(v) > s_i will not become true until we hit an available v where prefix(v) = prefix(v-1) + v > s_i. So the smallest v (in terms of index) such that prefix(v) > s_i is exactly the smallest available v with prefix(v-1) <= s_i and prefix(v-1)+v > s_i. Since prefix(v-1) is sum of available numbers < v, which is monotonic non-decreasing and jumps only at available numbers. For the true v (the one we need), we have prefix(v-1) = s_i, and then adding v gives > s_i. So v satisfies prefix(v) > s_i and also prefix(v-1) = s_i. But could there be a scenario where prefix(v-1) < s_i but the next available v is such that prefix(v-1)+v > s_i and prefix(v-1) < s_i? That would mean s_i is not exactly equal to prefix(v-1) for any available v, which cannot happen because the true v satisfies equality. So the smallest v with prefix(v) > s_i will be the true v, because for any smaller w (including non-available) prefix(w) <= s_i. Since prefix(v-1) = s_i (for true v), then for indices < v, prefix(.) <= s_i (since at true v-1 it equals s_i, but note v-1 might not be available; if v-1 is not available, prefix(v-1) = prefix(v-2) = something; but we need to ensure that prefix(v-1) exactly equals s_i. However, what if v-1 is not available, then prefix(v-1) = prefix(v-2) which might be less than s_i? Actually for the true v, we have sum of available < v = s_i. The set of available numbers less than v may not include v-1. So the largest available number less than v could be less than v-1. The prefix sum at index v-1 (which includes all numbers <= v-1) equals sum of available numbers <= v-1, which is same as sum of available numbers < v because v is not included and any number equal to v-1 if available is < v. So prefix(v-1) = sum_{available < v}. That's exactly s_i. So regardless of whether v-1 is available, prefix(v-1) = s_i. Because v-1 is not v, and numbers <= v-1 are exactly numbers < v. So yes, prefix(v-1) = s_i. Therefore, for the true v, prefix(v-1) = s_i, and prefix(v) = s_i + v if v is available (which it is). So the smallest index where prefix > s_i is v (since for any index u < v, prefix(u) <= prefix(v-1) = s_i). And for u = v, prefix(v) = s_i + v > s_i. So indeed, we can find v as the smallest index such that prefix(v) > s_i.
But careful: What if there are multiple available numbers with the same prefix(v-1)? No, because prefix is non-decreasing and only increases at available numbers. The smallest v such that prefix(v) > s_i will be the first available v after the point where prefix reaches s_i. Since prefix(v-1)=s_i, v is that first available. So this works.
Thus algorithm:
-
Initialize BIT (Fenwick tree) of size n, where each position x initially has value x (or we store the actual number x). But BIT typically stores sums of weights. We need to support point updates (set to 0 when removed) and prefix sum queries. We also need to find the smallest index v such that prefix sum up to v > s (given s). That's a typical "find by order" operation but based on cumulative sum threshold. BIT can support binary lifting to find first index where prefix sum exceeds a value.
-
Since the weights are not uniform (they are the numbers themselves), we can implement a Fenwick tree that stores the sum of values at each index. Initially, set tree such that A[x]=x, and BIT built accordingly. We'll need to perform n steps:
For i from n down to 1:
- Given s_i, we need to find v = smallest index such that prefix_sum(v) > s_i.
- Set p_i = v.
- Update BIT at position v: subtract v (set to 0). (i.e., remove v from available set).
But wait: Does this exactly correspond to sum of available numbers less than v? prefix_sum(v) includes v if v is still present. Since we query before removal, prefix_sum(v) includes v. So prefix_sum(v) > s_i condition is correct.
Let's test on examples.
Example1: n=3, s=[0,0,0].
Initialize BIT: values 1,2,3.
i=3: s_3=0. Find smallest v with prefix_sum(v) > 0.
prefix_sum(1)=1 >0 => v=1. p_3=1. Remove 1: set A[1]=0.
Now BIT: values 0,2,3.
i=2: s_2=0. Find smallest v with prefix_sum(v) > 0.
prefix_sum(1)=0 (since removed) ≤0; prefix_sum(2)=0+2=2 >0 => v=2. p_2=2. Remove 2.
BIT: values 0,0,3.
i=1: s_1=0. prefix_sum(1)=0, prefix_sum(2)=0, prefix_sum(3)=3 >0 => v=3. p_1=3.
Result: [3,2,1] matches.
Example2: n=2, s=[0,1].
Init: 1,2.
i=2: s_2=1. Find smallest v with prefix_sum(v) > 1.
prefix_sum(1)=1 >1? Actually 1 is not >1, it's equal. So condition is > s_i, so need >1. prefix_sum(1)=1 <=1, prefix_sum(2)=1+2=3 >1 => v=2. p_2=2, remove 2.
Now BIT: 1,0.
i=1: s_1=0. prefix_sum(1)=1 >0 => v=1. p_1=1.
Result: [1,2] matches.
Example3: n=5, s=[0,1,1,1,10].
Init: 1,2,3,4,5.
i=5: s_5=10. Find smallest v with prefix_sum(v) >10.
prefix_sum(1)=1 <=10; prefix_sum(2)=1+2=3 <=10; prefix_sum(3)=6 <=10; prefix_sum(4)=10 <=10; prefix_sum(5)=15 >10 => v=5. p_5=5, remove 5.
BIT: 1,2,3,4,0.
i=4: s_4=1. Find smallest v with prefix_sum(v) >1.
prefix_sum(1)=1 <=1; prefix_sum(2)=1+2=3 >1 => v=2. So p_4=2? But output says p_4=2? Actually output: 1 4 3 2 5, so p_4=2. Yes.
Remove 2: BIT: 1,0,3,4,0.
i=3: s_3=1. Find smallest v with prefix_sum(v) >1.
prefix_sum(1)=1 <=1; prefix_sum(2)=1+0=1 <=1; prefix_sum(3)=1+3=4 >1 => v=3. p_3=3. Remove 3: BIT: 1,0,0,4,0.
i=2: s_2=1. Find smallest v with prefix_sum(v) >1.
prefix_sum(1)=1 <=1; prefix_sum(2)=1 <=1; prefix_sum(3)=1 <=1; prefix_sum(4)=1+4=5 >1 => v=4. p_2=4. Remove 4: BIT: 1,0,0,0,0.
i=1: s_1=0. prefix_sum(1)=1 >0 => v=1. p_1=1.
Result: [1,4,3,2,5] matches.
Great.
So algorithm is valid.
Now we need to implement efficiently for n up to 2e5. BIT with point updates and prefix sum queries in O(log n) and a "find by sum" operation to get the smallest index such that prefix sum > s_i. Since BIT stores sums of values, we can implement binary search on BIT using its tree structure (like lifting). Or we can do binary search on index with O(log^2 n). Since n=2e5, O(n log^2 n) might be okay (2e5 * (log n)^2 ~ 2e51818 ~ 64.8e5? Actually 2e5*324 ≈ 64.8 million, which might be okay in C++ with optimization, but we can do O(log n) per query with BIT's find_kth (or find by sum) using binary lifting. However typical BIT find_kth works for frequencies (counts) where each position contributes 1. Here weights are values (x). So we need to find smallest index such that prefix sum > s. This can be done with a segment tree storing sums, or BIT with binary lifting if we store sums and we want to find first index where cumulative sum exceeds a value. BIT can support that if we use the technique of climbing the tree from most significant bit downward, assuming we have a BIT array of size power of two? Actually classic BIT can be used to find the smallest index with cumulative sum >= given value when the array is non-negative, by using the binary lifting method. The method: initialize position = 0, then for step from highest power of two <= n down to 1, if pos + step <= n and tree[pos + step] <= target, then subtract and advance. But that finds largest index where prefix sum <= target, then answer is pos+1. Since we need first index where prefix sum > target, we can find the index with prefix sum <= target and then +1. However we must ensure that the value at that index is present (non-zero). The method works because we are looking for prefix sum > target, which is equivalent to the smallest index i such that prefix_sum(i) > target. This is equal to (largest index i such that prefix_sum(i) <= target) + 1. So we can compute idx = lower_bound(target) + 1. But we must handle case where target is negative? Not needed. So we can implement BIT that supports prefix sum query and a find_ge (or find_by_order) for sum.
But careful: The BIT stores sums of values, which can be up to about n(n+1)/2 ~ 2e5200001/2 = 20e9, which fits in 64-bit (max sum about 2e52e5 = 4e10, actually 2e5*2e5=4e10, which is > 2^31, so need 64-bit). Use long long.
Implementation steps:
-
Read n, read array s[1..n].
-
Initialize BIT of size n. For i from 1 to n: add(i, i). (We can build by setting BIT[i] = i and then building cumulatively? Typically we initialize by adding each element.)
-
Create result array p of size n+1.
-
For i from n down to 1:
- Let target = s_i (0-index? careful: s_i given in order 1..n, we use s[i]).
- Find index v = find(target) + 1, where find(target) returns maximum index idx such that prefix_sum(idx) <= target. Then v is the answer.
- Set p[i] = v.
- Update BIT at v: add(v, -v) to remove.
-
After loop, output p[1..n] in order.
We need to ensure find works correctly when target is large or zero.
Now test edge cases:
-
n=1: s=[0]. BIT initially: value 1. target=0. find(0): we need max idx such that prefix_sum(idx) <= 0. prefix_sum(0)=0, prefix_sum(1)=1 >0, so max idx=0. Then v=1. Remove 1. p[1]=1. Output 1. Correct.
-
Check scenario where target equals prefix_sum of some index but that index is not available? For example, with available set {1,4}, target=1. prefix_sum(1)=1, prefix_sum(2)=1, prefix_sum(3)=1, prefix_sum(4)=5. find(1) should return max idx with prefix_sum <=1. That could be 3 because prefix_sum(3)=1 <=1. So idx=3. Then v=4. That's correct because v should be 4. However, we need to ensure that v is present (A[v] != 0). Since find returns idx such that prefix_sum(idx) <= target, and then v = idx+1, v might correspond to an index that is not present? Let's test: available {1,4}. BIT: A[1]=1, A[2]=0, A[3]=0, A[4]=4. prefix sums: idx1=1, idx2=1, idx3=1, idx4=5. target=1. The max idx with prefix_sum <=1 is idx=3 (since prefix_sum(3)=1). Then v=4. That's present. Could v be a non-present index? Suppose available set {2,3}. A[1]=0, A[2]=2, A[3]=3. target=0. We need v such that prefix_sum(v) >0. The smallest v with prefix_sum >0 is v=2 because prefix_sum(1)=0, prefix_sum(2)=2>0. Using find(0): max idx with prefix_sum <=0 is idx=1? prefix_sum(1)=0? Actually prefix_sum(1)=0 (since A[1]=0) <=0, so idx could be 1. Then v=2, present. If target=2? Let's see: target=2. We need v such that prefix_sum(v)>2. prefix_sum(2)=2 not >2, prefix_sum(3)=5>2 => v=3 present. find(2) returns max idx with prefix_sum <=2. prefix_sum(2)=2 <=2, prefix_sum(3)=5>2, so idx=2. v=3 present. So seems fine.
But what if target is such that the next index after the found idx is not present? For example, available set {1,5}. A[1]=1, A[2]=0, A[3]=0, A[4]=0, A[5]=5. target=1. prefix_sum(1)=1, prefix_sum(2)=1, prefix_sum(3)=1, prefix_sum(4)=1, prefix_sum(5)=6. find(1): max idx with prefix_sum <=1 is idx=4 (since prefix_sum(4)=1). Then v=5, present. Good.
What about target=0 in that set: prefix_sum(1)=1 >0? Actually prefix_sum(1)=1 >0, so smallest v>0? Let's compute: target=0, find(0): max idx with prefix_sum <=0. prefix_sum(0)=0, prefix_sum(1)=1>0, so idx=0. v=1 present.
Seems always v is the next index after the last index where prefix_sum <= target. Since prefix_sum only increases at indices where value is present, the next index where it increases is exactly the smallest present index with cumulative > target. So v will be present.
But we must be careful: our BIT stores sums, not counts. The standard BIT find by sum method works if we want the smallest index with prefix sum >= target. But we want > target. We'll implement as described.
Let's design BIT find function:
Let tree array of size n+2 (1-indexed). We'll implement two functions: sum(i) returns prefix sum up to i. update(i, delta).
For find(target), we want the maximum index i such that sum(i) <= target.
We can use binary lifting. Typical method (for BIT with non-negative values) uses:
int idx = 0;
int bitMask = highest power of two <= n;
for (; bitMask != 0; bitMask >>= 1) {
int next = idx + bitMask;
if (next <= n && tree[next] <= target) {
target -= tree[next];
idx = next;
}
}
return idx;
But careful: This works if the BIT stores cumulative frequencies in a certain way. Actually the method for BIT find kth (smallest index where prefix sum >= k) uses tree built from frequencies (counts). Here we have sums, but the structure is the same: the BIT stores sums of ranges. The method to find the largest index with prefix sum <= target is indeed:
int idx = 0;
for (int i = LOG; i >= 0; i--) {
int next = idx + (1 << i);
if (next <= n && BIT[next] <= target) {
target -= BIT[next];
idx = next;
}
}
return idx;
But this requires that the BIT is built such that tree[i] stores sum of a range of length lowbit(i). The method works because when we traverse bits from high to low, we are effectively constructing the index with cumulative sum <= original target. At the end, idx is the largest index such that sum(idx) <= original_target. However, I recall that for the typical "find by order" (kth smallest) with BIT storing frequencies, we start with idx=0 and iterate over bits descending, and compare cumulative sum + tree[next] < k (or <=). But there are two variants: to find smallest idx such that prefix sum >= k, we use < k. For our case, we want largest idx such that prefix sum <= target. The method above (with condition BIT[next] <= target) yields the largest idx with sum(idx) <= original_target? Let's test with a simple BIT.
Suppose we have array A[1]=3, A[2]=1, A[3]=4. BIT representation: tree[1]=3, tree[2]=3+1=4, tree[3]=4. prefix sum:
sum(1)=3, sum(2)=4, sum(3)=8.
We want largest idx with sum(idx) <= 5. Should be idx=2 (sum=4). Using method:
n=3, highest power of two = 2 (since 2 <= n, 4 > n). Let's assume we use bitMask from largest power of two <= n: bitMask=2.
idx=0, next=0+2=2, tree[2]=4 <= 5 => target-=4 => target=1, idx=2.
bitMask>>=1 =>1. next=2+1=3 <= n? yes, tree[3]=4 (since tree[3] = sum of range (3-lowbit(3)+1..3) = sum(3..3)=A[3]=4). But 4 <= target? target=1, 4<=1 false, so skip.
bitMask>>=1 =>0, exit. idx=2. That's correct.
Now test with target=4. Should return idx=2 (since sum(2)=4).
idx=0, next=2, tree[2]=4 <=4 => target-=4 => target=0, idx=2.
next=3, tree[3]=4 <=0? false. idx=2. correct.
target=3: largest idx with sum <=3 should be idx=1 (sum1=3).
idx=0, next=2, tree[2]=4 <=3? false. next=1 (after bitMask=1), next=0+1=1, tree[1]=3 <=3 => target-=3=0, idx=1. bitMask=0, done. idx=1. correct.
target=0: largest idx with sum <=0 should be idx=0.
idx=0, next=2, tree[2]=4 <=0? false. next=1, tree[1]=3 <=0? false. idx remains 0. correct.
So it works.
But we must be careful that we use the tree array where tree[i] is the sum of range (i - lowbit(i) + 1, i). This is standard BIT. The method works if we start with idx=0 and use powers of two up to >= n? Typically we need the largest power of two less than or equal to n. We'll compute as 1 << (floor(log2(n))) maybe.
So we can implement:
int find_idx(ll target) {
int idx = 0;
ll sum = 0; // Actually we can use the method that subtracts from target.
// But we need the BIT array to be accessible.
for (int step = highest_power; step; step >>= 1) {
int next = idx + step;
if (next <= n && tree[next] <= target) {
target -= tree[next];
idx = next;
}
}
return idx; // this is the max index with prefix sum <= original target
}
But note: The variable 'target' is passed by value and we modify it. That's okay.
Then v = idx + 1.
One nuance: The BIT initially contains sums of values. After removals, some values become zero. The method still works because tree entries are updated accordingly.
We must ensure that the BIT is built with size n, and we can compute highest power: e.g., int bit = 1; while (bit <= n) bit <<= 1; bit >>= 1; That gives highest power of two <= n.
Alternatively, we can use a segment tree with binary search, but BIT is simpler.
Complexity: O(n log n).
Now verify with more cases:
Consider a permutation where duplicates? Not possible.
Edge: s_i can be as large as n(n-1)/2, e.g., when p_i = n and all previous numbers are smaller (always true), then s_i = sum of all numbers from 1 to n-1 = n(n-1)/2. That's maximum.
Our method will work because prefix sums can go that high.
We need to use 64-bit ints (long long) for sums.
Now confirm the reasoning formally: At step i (from n down to 1), we have a set S of numbers that have not yet been assigned (i.e., those that will be placed at indices i..n?). Actually we start with all numbers in the set. For i=n, S = all numbers. For each step, we pick v from S such that sum of elements in S that are < v equals s_i. Then we set p_i = v and remove v from S. This works because, as argued, for the hidden permutation, when we consider i, the set of numbers that will appear before i is exactly S \ {v}. Since we haven't placed any numbers to the left yet, the condition s_i = sum_{x in S, x < v} x must hold. And because the sum function is strictly increasing over the sorted S, there is a unique v. The algorithm finds it via BIT.
Thus solution is correct.
Now we should also consider if there is any alternative interpretation: The problem statement says s_i equals sum of all p_j such that j < i and p_j < p_i. This is exactly what we used.
We should also check corner case where s_i = 0 for many i. Our method will pick the smallest available number? Not exactly: For i=n, if s_n=0, we pick v=1, which is the smallest. For i=n-1, after removing 1, if s_{n-1}=0, we would pick the smallest available number that yields sum of smaller available numbers =0. That would be the smallest available number (since if the smallest available number is >1, then sum of smaller available numbers =0 because there are no smaller available numbers). For example, after removing 1, the smallest available is 2, and sum of smaller available =0. So we pick 2. That yields descending order if all s_i=0: p = [n, n-1, ..., 1]. Indeed matches example1.
Now complexity: O(n log n) with BIT and binary lifting find. n up to 200k, fine.
Now implement:
Pseudo:
int n;
vector s(n+1);
vector p(n+1);
FenwickTree tree(n); // using long long
for i in 1..n: tree.add(i, i);
int highest = 1;
while (highest <= n) highest <<= 1;
highest >>= 1;
for i from n down to 1:
long long target = s[i];
int idx = 0;
for (int step = highest; step; step >>= 1) {
int next = idx + step;
if (next <= n && tree.sumRange(next) <= target) {
target -= tree.sumRange(next); // Actually tree.tree[next] is not prefix sum, it's the tree node value representing sum of a range. In the find method we need to use the internal BIT array 'bit' where bit[i] stores sum of (i - lowbit(i)+1, i]. That is exactly what we need to use directly, not the prefix sum function. The method uses bit[next] which is that internal value. So we should have an array 'bit' storing the Fenwick tree structure, and we use that directly in the binary lifting.
idx = next;
}
}
int v = idx + 1;
p[i] = v;
tree.add(v, -v); // remove
But note: In the binary lifting method, we use the internal BIT array (call it BIT[]). The condition if (next <= n && BIT[next] <= target) is correct, but note that BIT[next] is not the prefix sum up to next; it's the sum of a range of length lowbit(next) ending at next. The method works because we are essentially reconstructing the prefix sum by accumulating those ranges. The invariant is that idx holds the current cumulative index and target holds the remaining sum we can still allocate. Starting from most significant bit, we check if adding the range of the next segment would keep the cumulative sum <= original target. This is a standard way to find the largest idx such that prefix sum <= target when the array elements are non-negative. However, it requires that we use the BIT array in a specific way: we need to have the ability to get the value of BIT[node] quickly and it should represent the sum of the segment. That's true. The loop uses BIT[next] as the sum of that segment. However, we need to ensure that we are using the updated BIT after removals. That's fine.
Alternatively, we can use a segment tree with binary search, but BIT is simpler.
But I need to be careful: The method as described works for finding the smallest index such that prefix sum >= target (when using < target condition). But for <= target we use <= target and subtract. However, I've seen implementations for finding largest index with prefix sum < value. Let's double-check with a BIT that has arbitrary values, not necessarily frequencies of 1. The method for find by sum (largest prefix sum <= target) is indeed:
int find_by_sum(int target) {
int idx = 0;
int bitMask = highestPowerOfTwo <= n;
for (; bitMask != 0; bitMask >>= 1) {
int tIdx = idx + bitMask;
if (tIdx <= n && fenwick[tIdx] <= target) {
target -= fenwick[tIdx];
idx = tIdx;
}
}
return idx;
}
This returns the maximum index with prefix sum <= original target. It works because fenwick[tIdx] contains the sum of a range that starts at tIdx - lowbit(tIdx) + 1 and ends at tIdx. When we add that range, we are moving forward in index while ensuring the cumulative sum doesn't exceed the target.
Let's test with a BIT that has values after some updates.
Initialize BIT with values: 1,2,3,4,5. (n=5)
After removing 5: BIT values at positions: we updated add(5,-5). So BIT representation changes.
We'll test the find for target=10 (before removal). That gave v=5.
After some removals, let's test with available set {1,4} as earlier.
Initialize BIT: add all.
Then remove 5,2,3? Actually to get {1,4} we need after some steps: start with all, remove 5, remove 2, remove 3? That would leave {1,4}. Let's simulate: initially tree with 1,2,3,4,5.
Remove 5: update(5,-5).
Now set {1,2,3,4}. BIT internal? We'll not compute manually but trust method.
Suppose we then remove 2: update(2,-2). Then remove 3: update(3,-3). Now set {1,4}. Now we need to find for target=1. Expect v=4.
Now BIT internal after these updates? Hard to manually compute but the method should work.
Now what about the highest power of two? Since n can be up to 2e5, we can compute highest = 1 << (__lg(n)) or simply use:
int highest = 1;
while (highest <= n) highest <<= 1;
highest >>= 1;
Now, during the loop, the step starts from highest and halves. However, note that after we remove elements, the total sum in BIT decreases. But we still use the same step values. That's fine.
One nuance: The BIT's internal array fenwick[0...n] where fenwick[0] unused. The binary lifting method sometimes initializes idx = 0 and then loops over powers of two from the highest power less than or equal to n down to 1. But the step sizes must be powers of two. That's fine.
Implementation detail: We need to compute highest power of two such that 1<<k <= n. We'll compute as:
int highest = 1;
while (highest * 2 <= n) highest *= 2;
Or using bit operations: highest = 1 << (31 - __builtin_clz(n)); // __builtin_clz returns count leading zeros, so highest = 1 << (floor(log2(n))).
Now after we find v = idx+1, we need to ensure v <= n. It will be because idx <= n-1? Possibly if target is equal to total sum of all remaining numbers, then the largest idx with prefix sum <= target might be n (since sum(n) = total sum). Then v = n+1? Let's check: If target = total sum of all remaining numbers? But s_i is sum of numbers less than p_i, which is always less than total sum of all remaining numbers except p_i? Actually for i, the sum of numbers in S less than v is at most sum of all numbers less than the maximum in S, which could be total sum minus max. But can s_i equal total sum of all remaining numbers (excluding v)? Suppose v is the maximum in S. Then sum of numbers less than v = total sum of S - v. So s_i = total_sum_remaining - v. Since v is at least 1, s_i is less than total_sum_remaining. So target s_i is strictly less than total sum of S (the sum of all remaining numbers). The total sum of all remaining numbers is sum_{x in S} x. Since we are finding the largest idx such that prefix_sum(idx) <= target, and target < total sum, idx will be at most the index of the largest number less than v. But v is present, and its index is > that idx. So idx+1 should be <= n and correspond to v which is present. But could idx become n? If target = total sum of all numbers except the maximum, then prefix_sum(n) = total sum of all numbers (since maximum is included). But total sum of all numbers except maximum = total - max. That is less than total, so prefix_sum(n) = total > target. So the largest idx with prefix_sum <= target is less than n. So idx < n. So idx+1 <= n.
Edge: if target is such that prefix_sum of all existing numbers <= target? But target is strictly less than total sum, so not.
Thus v = idx+1 is within [1,n].
Now ensure that v is indeed present. Since prefix_sum only jumps at positions where A[v] > 0, the next index after idx where prefix_sum increases is exactly the smallest index with A>0 and cumulative > target. That is v. Since we maintain that there is exactly one such v, it's fine.
Now we should also think about correctness proof in more detail: The backward process uses the property that all numbers not yet placed are exactly those that will appear at or before current index. But wait, when processing i from n down to 1, we assume that the numbers we have not yet assigned (i.e., still in BIT) are exactly the set of numbers that will appear at positions 1..i (including i). Because we start with all numbers (positions 1..n). At step i=n, we assign p_n, remove it, so remaining numbers correspond to positions 1..n-1. At step i=n-1, the remaining numbers correspond to positions 1..n-1 (since we haven't assigned those yet, and they will be placed in indices 1..n-1). However, we haven't determined the order of those numbers among indices 1..n-1. But the condition for s_{n-1} only depends on which numbers are in the set of positions 1..n-1 (excluding p_{n-1}) and their values relative to p_{n-1}, not on their order. So it's valid. Similarly for earlier steps.
Thus algorithm correct.
Now time to implement.
Implementation steps in C++:
- Read n.
- vector s(n);
For i=0..n-1: read s[i] (0-index). We'll later use 1-index for convenience.
- Fenwick class with:
int n;
vector bit;
Fenwick(int n) : n(n), bit(n+1, 0) {}
void add(int idx, long long delta) {
while (idx <= n) {
bit[idx] += delta;
idx += idx & -idx;
}
}
long long sum(int idx) {
long long res = 0;
while (idx > 0) {
res += bit[idx];
idx -= idx & -idx;
}
return res;
}
// Find largest index with prefix sum <= target
int find(ll target) {
int idx = 0;
int bitMask = 1;
while (bitMask <= n) bitMask <<= 1;
bitMask >>= 1; // highest power of two <= n
for (; bitMask; bitMask >>= 1) {
int next = idx + bitMask;
if (next <= n && bit[next] <= target) {
target -= bit[next];
idx = next;
}
}
return idx; // max idx such that sum(idx) <= original target
}
But careful: The method using bit[next] works only if we are using the tree array in the way that bit[next] is the sum of the segment that would be added when moving from idx to next. This is standard for BIT when we want to find prefix sum threshold. However, note that the standard method for "find smallest index with prefix sum >= k" for a BIT of frequencies (where each index has weight 1) uses a similar approach but compares with the tree value. But here we have arbitrary weights. The method I wrote for largest index with prefix sum <= target should work as long as we interpret bit[next] correctly. However, I recall that the typical BIT "find by order" algorithm uses the property that the BIT stores cumulative frequencies, and we start with idx=0 and for each step we check if idx + bitMask is within range and if the cumulative sum + tree[idx+bitMask] < target (or <=). But that algorithm assumes that tree[i] stores sum of frequencies from i - lowbit(i) + 1 to i. That's exactly what our bit array does. So the method for "largest idx with prefix sum <= target" uses condition tree[idx+bitMask] <= target (where target is the remaining value after subtracting previous additions). Let's test with our earlier example after some removals.
Let's construct BIT from scratch for n=5, initial values: add(1,1), add(2,2), add(3,3), add(4,4), add(5,5). After removals (5,2,3) we have only values at 1 and 4. Let's compute bit array manually to confirm the find method.
First, understand BIT representation: bit[i] = sum of a[i] for indices (i - lowbit(i) + 1) to i.
Initially with all values:
a: [1,2,3,4,5]
bit[1] = a1 =1
bit[2] = a1+a2 =1+2=3
bit[3] = a3 =3
bit[4] = a1+a2+a3+a4 =1+2+3+4=10
bit[5] = a5 =5
Now remove 5: add(5, -5). So bit[5] becomes 0; also bit[?] due to propagation: BIT update: idx=5: bit[5] += -5 => bit[5]=0; idx+=lsb: 5+1? Actually 5 + lowbit(5)=5+1=6 >5 stop. So only bit[5] changes.
Now remove 2: add(2, -2). Update: idx=2: bit[2] += -2 => was 3, becomes 1; idx=4: bit[4] += -2 => was 10, becomes 8; idx=8 out of range.
Now remove 3: add(3, -3). idx=3: bit[3] += -3 => was 3, becomes 0; idx=4: bit[4] += -3 => was 8, becomes 5; idx=8 out.
Now final bit:
bit[1]=1
bit[2]=1
bit[3]=0
bit[4]=5
bit[5]=0
Now a values: a1=1, a2=0, a3=0, a4=4, a5=0. Check bit[2] = a1+a2 =1+0=1, correct. bit[4] = a1+a2+a3+a4 =1+0+0+4=5, correct.
Now we do find(target=1). We want largest idx with prefix sum <=1. Let's compute prefix sums manually: sum(1)=1, sum(2)=1, sum(3)=1, sum(4)=5, sum(5)=5. So the largest idx with sum <=1 is 3? Actually sum(3)=1 <=1, sum(4)=5 >1, so idx=3. But idx=3 corresponds to prefix sum up to 3 being 1. However, our BIT find method using bit array:
highest power of two <=5 is 4.
Initialize idx=0, bitMask=4.
next=0+4=4 <=5, bit[4]=5 <= target(1)? No -> skip.
bitMask=2.
next=0+2=2 <=5, bit[2]=1 <=1? Yes, so target-=1 => target=0, idx=2.
bitMask=1.
next=2+1=3 <=5, bit[3]=0 <=0? Yes, so target-=0 => target=0, idx=3.
bitMask=0 -> stop. idx=3. This matches the largest idx with prefix sum <=1. Good.
Then v = idx+1 = 4, which is the correct v.
Now test find(target=0) after same set. prefix sums: sum(1)=1 >0, sum(0)=0. Largest idx with sum <=0 is 0.
highest=4, idx=0, next=4 bit[4]=5 <=0? no.
next=2 bit[2]=1 <=0? no.
next=1 bit[1]=1 <=0? no.
So idx remains 0. v=1, correct.
Now test find(target=2) after same set? target=2. prefix sums: sum(1)=1 <=2, sum(2)=1 <=2, sum(3)=1 <=2, sum(4)=5 >2, so largest idx is 3.
Our method:
target=2, idx=0, bitMask=4: bit[4]=5<=2? no.
bitMask=2: next=2, bit[2]=1<=2? yes, target=1, idx=2.
bitMask=1: next=3, bit[3]=0<=1? yes, target=1, idx=3.
Thus idx=3, v=4. But does v=4 satisfy sum of available <4 =1? That equals s_i? For target=2, we would need sum_{available<v}=2, but actually sum_{available<4}=1. So v=4 wouldn't satisfy. But in our algorithm, target is s_i. For this set, s_i can be 1 or maybe 5? Actually with available {1,4}, the possible sums are: for v=1, sum<1=0; for v=4, sum<4=1. So s_i can only be 0 or 1. So target=2 would never occur in a valid scenario. So we don't need to worry.
Thus the find method works.
Now, we must be cautious about the highest power of two. Since n can be up to 200k, highest power of two is 2^17 =