We need to find a subsequence (contiguous? Actually we are cutting down some trees, so remaining trees are in original order, not necessarily contiguous? The problem statement: "woodland belt as a sequence of trees. The Smart Beaver calculated that he needed the following effects: The first objective is to please the Beaverette: the sum of esthetic appeal of the remaining trees must be maximum possible; the second objective is to surprise the Beaverette: the esthetic appeal of the first and the last trees in the resulting belt must be the same; and of course, the walk should be successful: there must be at least two trees in the woodland belt left."
We can cut down any trees, leaving a subsequence (preserving order). The sum of remaining trees must be maximum possible, with constraints: first and last have same value, at least 2 trees. Also we need to output which trees to cut down (i.e., indices to remove). Among all possible subsets to remove (i.e., all possible resulting subsequences that meet constraints), choose one that maximizes sum. If multiple, any.
So basically we need to select a subsequence (not necessarily contiguous) of the original array, preserving order, such that: length >=2, first element equals last element, and the sum of the selected elements is maximized. Output the sum, number of removed trees (i.e., n - len(selected)), and the indices of removed trees.
We can rephrase: we need to pick two positions i<j (i and j are indices of the first and last trees in the resulting belt) such that a[i]==a[j], and then we can optionally include any trees between i and j (and possibly before i or after j? Actually if first is at i and last is at j, then we cannot have trees before i or after j, because first and last define boundaries. So the selected subsequence must be exactly a subset of the segment from i to j inclusive, containing i and j as the first and last selected elements. But can we also include trees outside i..j? That would change first or last. So no. So the selected subsequence must be a subset of indices from i to j, containing i and j, and it is the entire set of selected indices. Additionally, we can also decide to skip some trees between i and j. The sum is sum of a[i] + a[j] + sum of any selected indices between i and j. To maximize sum, given we are free to include or exclude any elements between i and j, we would include all positive elements (since they increase sum) and exclude all negative elements (since they decrease sum). However careful: we cannot skip i or j because they are fixed as first and last. Also we must keep at least two trees, i and j. For any pair (i,j) with a[i]==a[j], we can compute the maximum sum we can achieve by selecting a subsequence from i to j that includes i and j and includes all positive numbers between i and j. But is it always optimal to include all positive numbers? Yes, because including any positive element will increase total sum, and we are allowed to include any subset of the interior (excluding i and j) without affecting the condition on first and last. So the optimal sum for a given pair (i,j) is: a[i] + a[j] + sum of all positive values among indices k with i<k<j. (Because we can include all positive ones and exclude all negative ones.) But wait, what about zero? Zero doesn't change sum, we can include or exclude; either is fine. For simplicity we can include them? It doesn't affect sum. But including them doesn't break condition. However, including zero may be counted as a tree? The condition only requires at least two trees; adding zeros doesn't hurt. But we might want to minimize number of cut trees? Not required; any solution maximizing sum is acceptable. So we can include zeros if we like. However, if we include all positive and zeros, sum remains same. But careful: If we include zeros, it adds to the count of remaining trees; but we don't care about that. However, maybe we might want to exclude zeros because it makes the output of removed trees list different. But any solution is fine. So we can include all non-negative numbers? Actually positive and zero are non-negative. But negative numbers we exclude.
Thus, the overall problem reduces to: find a pair (i,j) with i<j, a[i]==a[j], such that value = a[i]+a[j] + sum_{k=i+1}^{j-1} max(0, a[k]) is maximized. Since n up to 3e5, we need O(n log n) or similar.
We can think of grouping positions by value. For each distinct value v, we have a list of indices where a[i]=v. For any two indices i<j in that list, the candidate sum is: v+v + sumPositive(i,j) where sumPositive(i,j) is sum of positive numbers between i and j (excluding i,j). However, the positive sum between i and j is not simply a prefix sum of positives because we only consider indices strictly between i and j, not including i and j. So we can precompute an array b[k] = max(0, a[k])? Actually b[k] = max(0, a[k]), but we need to sum b[k] for k in (i,j). So if we define prefix sum P[i] = sum_{t=1}^{i} b[t], then sum_{k=i+1}^{j-1} b[k] = P[j-1] - P[i]. So candidate sum = 2v + P[j-1] - P[i].
So for each value v, we want to maximize over pairs i<j in its positions: (2v + P[j-1] - P[i]) = 2v + (P[j-1] - P[i]). Since 2v is constant for that value, we need to maximize (P[j-1] - P[i]) over i<j in the list. That's essentially: maximize (P[j-1] - P[i]) for i<j. But careful: The positions are indices. Let positions list for value v: p1, p2, ..., pm sorted ascending. For any pair (pi, pj) with i<j (meaning earlier and later), the candidate sum = 2v + P[pj-1] - P[pi]. But note that pj-1 may be less than pi? Since pj > pi, pj-1 >= pi? Actually pj >= pi+1, so pj-1 >= pi. So it's fine. So for each value, we need to find max over i<j of (P[pj-1] - P[pi]).
We can precompute prefix sums P[0..n], where P[0]=0, P[i]= sum_{t=1}^{i} b[t] = sum of max(0, a[t]). Then for each value, for each position p, we consider some value like P[p-1] as something and P[p] as something? Actually the expression uses P[pi] and P[pj-1]. So we can think of each position p, we have two numbers: left value L = P[p] (or maybe P[p-1]? We need both). For a given pi as first index, we subtract P[pi]. For a given pj as last index, we add P[pj-1]. So if we iterate through positions in order, we can keep track of the minimum P[pi] encountered so far, and then for each subsequent pj, compute candidate = P[pj-1] - min_P_sofar. So that yields the maximum difference. But careful: The minimum P[pi] should come from a pi that is before pj. Since we process in increasing order, we can maintain the minimum value of P[pi] among positions seen so far (or maybe P[pi]? Actually we need P[pi], not P[pi-1]? Yes, it's P[pi] because in formula we subtract P[pi] where pi is the index of the first tree. Wait check: sum_{k=pi+1}^{pj-1} b[k] = P[pj-1] - P[pi]. Because P[pi] = sum_{t=1}^{pi} b[t]. So yes subtract P[pi]. So we need for each pi we consider P[pi]. Then for each pj, candidate = P[pj-1] - min(P[pi]) where pi < pj. So indeed we can compute for each value v, scanning its positions in order, maintain minPrefix = INF, and for each position p (starting from first), we could compute candidate using minPrefix from earlier positions? But we must ensure that we have at least one earlier position. So we can start with minPrefix = P[p1] after processing first? Actually for each pj, we need min over previous positions pi of P[pi]. So we can initialize minPrefix = P[first_position], then for each subsequent p, compute candidate = P[p-1] - minPrefix, update best, and then update minPrefix = min(minPrefix, P[p]) (since p can become a future pi). But careful: When we update minPrefix after computing candidate for p, we should use P[p] for future pi. Yes.
But is it correct to use P[p-1] for pj? Because pj is the last index, and we need P[pj-1]. But what if pj = pi+1? Then the interior is empty, sum=0, and candidate = 2v + 0. That is valid. In that case, pj-1 = pi, and P[pj-1] = P[pi]. So candidate = 2v + P[pi] - P[pi] = 2v. That's fine. So using P[p-1] works even when p = pi+1.
Thus for each value v, we can compute maxDiff = maximum over ordered pairs of (P[pj-1] - P[pi]) where pi and pj are positions of v, pi < pj. This is simply maximum difference of these prefix values with order constraint: we want later P[pj-1] - earlier P[pi] maximized. But note that P[pj-1] is not necessarily a value associated with a v position; it's just a prefix value at index pj-1, which could be any. So it's essentially scanning and for each pj, we subtract the smallest P[pi] seen so far. So O(m) per value. Sum of m over all values = n, so overall O(n) after precomputing P. That is good.
But wait: The candidate sum = 2v + maxDiff. However, we need to ensure that the resulting subsequence has at least two trees (which it does because we pick two distinct positions). Also we need to output which trees to cut down. So we need to also record the specific pair (i,j) that achieves the maximum sum. And then we need to output the list of indices to remove, i.e., all indices except the ones we keep. The kept indices are: i, j, plus any indices k between i and j for which a[k] > 0? Actually we might also include zero? As said, doesn't matter, but to achieve maximum sum, we include all positive numbers (and optionally zeros). But to be precise: The maximum sum is achieved by including i and j and all k in (i,j) with a[k] > 0. Including zeros doesn't change sum, but it also doesn't affect objective. However, there could be multiple ways: maybe we could also include some negative numbers if they are needed to satisfy something? No, we want maximum sum, so exclude negatives. So the set of kept indices for that optimal pair is: K = {i, j} ∪ {k : i<k<j and a[k] > 0}. But what about zeros? Including them is optional; but to minimize removal count? Not needed. But if we want to output any valid solution, we could either include or exclude zeros. Simpler: we can decide to include all non-negative numbers (a[k] >= 0) between i and j. But is that always optimal? Yes because non-negative numbers add non-negative sum; including them doesn't reduce sum. But careful: if a[k]=0, sum unchanged; including it doesn't hurt, but maybe it increases number of trees kept. That's fine. However, we need to output the list of cut down trees. So we could choose to keep all a[k] >= 0 between i and j. But we must ensure the first and last are i and j (which are positive or negative? They could be negative, but we have to keep them anyway because they are the first and last. So they might be negative, but we have to include them because they satisfy the equal condition. That's okay.)
But does including zero or positive numbers ever cause the first and last to not be the first and last? If we include an index before i, then i wouldn't be first. So we must only include indices between i and j (inclusive) and we are including i and j. So we can include any subset of indices between i and j. Including all non-negatives is fine, and it's still a subsequence because we keep order.
Thus, for the optimal pair (i,j) we can construct the kept set as: all indices k such that (k == i or k == j or (i<k<j and a[k] > 0)). Or we could also include zeros if we want; either is fine. Let's just include all indices with a[k] >= 0? But what about the case where a[k]=0, we may include them. But then the sum remains same. However, note that the objective is to maximize sum; zeros do not affect sum. So both are optimal. We can choose to include zeros for simplicity, because then the kept set is all indices from i to j that are non-negative? But there could be negative numbers between i and j that we exclude. So we need to output which trees to cut down: i.e., all indices not in kept set. That includes all indices before i, after j, and indices between i and j that are negative (or if we decide to exclude zeros, zeros too). So we need to output those indices. To generate output, we must produce list of cut down trees, not kept. So we must compute the complement.
Now, is it always valid to take the pair that maximizes 2v + (P[j-1] - P[i])? There is a nuance: The sum we compute as 2v + sum_{k=i+1}^{j-1} max(0, a[k]) is indeed the maximum sum achievable with first i and last j, because we can independently choose to include any interior elements with positive contribution. However, we also have the possibility of including interior elements that are negative if they allow us to include other positive ones? No, each element is independent; we can pick any subset. So yes, we maximize sum by including all positive interior elements, excluding negatives. So that's correct.
Now, is there any possibility to achieve a higher sum by picking a subsequence where the first and last are equal but there might be other elements before the first or after the last? No, by definition first and last are boundaries, so no elements outside.
Thus, our approach is to find i<j with equal a[i]=a[j] to maximize S = a[i]+a[j] + sum_{k=i+1}^{j-1} max(0,a[k]). Compute this efficiently.
We can precompute P[0]=0, for i from 1 to n: P[i] = P[i-1] + max(0, a[i]).
Now, for each value v, we have positions list pos. To compute max diff = max_{l<r} (P[pos[r]-1] - P[pos[l]]), we can scan left to right.
Algorithm:
- Input n, array a[1..n].
- Compute b[i] = max(0, a[i]).
- Compute prefix sum P[0..n], P[0]=0, for i=1..n: P[i]=P[i-1]+b[i].
- Create map/dict from value to list of indices.
- Initialize bestSum = -inf (or sentinel), best_i = -1, best_j = -1.
- For each value v and its list L (sorted ascending):
- Let m = len(L).
- If m >= 2:
- Let minPrefix = P[L[0]] // P at first index.
- For idx from 1 to m-1:
- Let pj = L[idx]
- Compute candidate = P[pj-1] - minPrefix
- If 2v + candidate > bestSum:
bestSum = 2v + candidate; best_i = L[some index of min? Actually we need to record which i (the one giving minPrefix) and which j (current pj). Since minPrefix might have been updated from multiple previous positions, we need to store the specific index that gave the minPrefix at that time. So we maintain best_i_for_min = the index among processed positions that gave the current minPrefix. So we store minIdx = L[0] initially. Then for each pj, compute candidate and compare. If better, set best_i = minIdx, best_j = pj. Then after comparison, we check if P[pj] < minPrefix: if so, update minPrefix = P[pj], and minIdx = pj.
- Also note: Could the optimal pair be with i being not the one giving the minimal P[i]? Because we are maximizing P[pj-1] - P[i]. For a given pj, the best i is the one with smallest P[i] among earlier positions. So scanning as above yields the maximum difference for each pj. But what about the case where there are multiple pairs? We only care about one best. So scanning works.
One nuance: The expression uses P[pj-1] not P[pj]. That is okay. However, when we later update minPrefix, we compare P[pj] (not P[pj-1]) because the next future pj' will use its own pj'-1, but for i candidate we use P[i] where i is a potential first index. So we update with P[pj] after processing pj.
But we must also consider candidate where i is L[0] and j is L[1] etc. In our loop, we start with minPrefix = P[L[0]], then for idx=1, we compute candidate using pj = L[1]. That gives the candidate for i = L[0], j = L[1]. Good. Then after that, we might update minPrefix with P[L[1]] if it is smaller. So correct.
Thus we can compute bestSum and the corresponding pair (i,j). However, there is a subtlety: Does the sum include only positive interior numbers? Yes. But what about the case where a[i] or a[j] themselves are positive? They are added as a[i]+a[j]. That's already included. So the sum computed is exactly that.
But wait: The interior sum we include only positive numbers. But is it always optimal to include all positive interior numbers? What if some positive numbers are excluded to satisfy something else? No other constraints. So yes.
Now, after we have best pair (i,j) that maximizes S, we need to output the total esthetic appeal after cut (i.e., S) and the number of cut trees k = n - (number of trees we keep). And the list of cut trees.
But we must verify that our computed S indeed equals the maximum sum possible. However, is there any scenario where the optimal solution includes some negative interior numbers because they enable including some extra trees outside i..j? No, the boundaries are fixed to i and j, we cannot include outside. So interior negatives only reduce sum. So excluding them is always better.
Thus, the problem reduces to find (i,j) with a[i]==a[j] maximizing 2a[i] + sum_{k=i+1}^{j-1} max(0,a[k]). That is as above.
Now, we must output which trees to cut down. The kept set K = {i, j} ∪ {k | i<k<j and a[k] > 0}? Or optionally include zeros. We need to produce a valid set that achieves the sum S. If we include zeros, the sum stays same. But would that affect the condition that first and last are the same? No, because zeros are interior. So it's still fine. However, we must ensure that the first and last are indeed i and j. If we include any element with index less than i or greater than j, that would change first/last. So we must exclude all indices < i and > j. Also exclude indices between i and j that are not kept. So the cut set is: all indices < i, all indices > j, and all indices k with i<k<j and a[k] <= 0 (if we exclude negatives and maybe zeros). But we need to decide whether to include zeros. Since zeros don't affect sum, either is fine. But we must output some solution. Typically, to minimize the number of cuts (maybe not required, but any solution), we could keep zeros. That would reduce number of cut trees. But does the problem require to output the number of cut trees? Yes, we need to output k. The number of cut trees will vary depending on whether we include zeros. But the problem statement: "In the first line print two integers — the total esthetic appeal of the woodland belt after the Smart Beaver's intervention and the number of the cut down trees k." So k must correspond to the cut down trees we list. It does not say we need to minimize k; any k for a solution with maximum sum is acceptable. So we can choose to include zeros to keep more trees, thereby cutting fewer, but it's still valid. However, we should be consistent: the sum must be exactly S. If we include zeros, sum remains S. So it's fine.
But note: Our computed S includes only positive interior numbers. If we include zeros, sum unchanged. So that's fine. But if we include negative numbers, sum would be lower, so that wouldn't achieve the maximum sum. So we must not include negative numbers. So interior negatives must be cut. Zeros are optional. So we can decide either. Usually, it's simpler to keep all non-negative interior numbers (a[k] >= 0) because we don't have to check sign; but careful: a[k] might be zero; that's non-negative. So we could keep all a[k] >= 0. That yields the same sum. So kept set: all indices k with (i <= k <= j) such that either k == i or k == j or (i<k<j and a[k] >= 0). But wait: if a[i] or a[j] themselves are negative, we still keep them because they are the endpoints. That's fine.
But is it allowed that we keep interior negative numbers? That would reduce sum, not achieving maximum. So we must not keep them.
Thus, we can compute cut indices as: all indices not in K.
But we need to be careful: Our computed S uses sum of a[i]+a[j]+ sum of max(0,a[k]) for i<k<j. If we keep zeros, that sum adds zero, so S unchanged. Good.
Now, we need to output k and the list of cut indices. The number of cut indices is n - |K|.
Now, verify with examples:
Example 1:
n=5, a=[1,2,3,1,2]
Compute b = [1,2,3,1,2] (all positive). So P = [0,1,3,6,7,9] (P[0]=0, P[1]=1, P[2]=3, P[3]=6, P[4]=7, P[5]=9)
Now find pairs with equal values:
Value 1: indices [1,4]
For i=1, j=4: sum = 1+1 + sum_{2..3} max(0,a) = 2+ (2+3)=7? Wait sum_{2..3}=2+3=5, plus 2 =7? Actually 1+1=2, plus 5 =7. But the output says total esthetic appeal = 8 and they cut tree 1. Let's check: They cut tree 1 (index 1), so remaining trees: indices 2,3,4,5? Wait they cut tree 1, so remaining: 2,3,4,5. But then first tree is 2 (value 2) and last tree is 5 (value 2). They are equal. Sum = 2+3+1+2 = 8. That corresponds to i=2, j=5? Actually indices 2 and 5 are both 2. Then sum interior: indices 3,4: 3+1=4, plus endpoints 2+2=4, total 8. So that pair gives sum 8. Let's compute candidate for value 2: indices [2,5]. For i=2, j=5: 2+2=4, interior sum of positives (since all positive) indices 3,4: 3+1=4 total 8. So best sum is 8. Our algorithm for value 2:
positions = [2,5]. minPrefix = P[2] = 3? Actually P[2]=3? Wait P[2] = sum b[1..2] = max(0,1)+max(0,2)=1+2=3. Then for idx=1: pj=5, candidate = P[4] - minPrefix = P[4] = sum b[1..4] = 1+2+3+1=7? Actually P[4]=7. So candidate = 7 - 3 =4. Then 2v + candidate = 4+4=8. So best is 8. Good.
Value 1 gave candidate: minPrefix = P[1]=1, pj=4: candidate = P[3] - 1 =6-1=5? Actually P[3]=6? Wait P[3]=1+2+3=6. So candidate=5, 2v+candidate = 2+5=7. So 8 is larger. So best pair is (2,5). So our algorithm would find that.
Now output: they cut tree 1. So kept: 2,3,4,5. That matches our kept set if we keep all non-negative between 2 and 5 (both inclusive but we keep only those with a>=0? All are non-negative, so keep all from 2 to 5. That yields sum=8. So we would output k=1, cut tree 1. But our algorithm as described would produce kept set: i=2, j=5, plus interior positives (3,4) -> which are already included. Since all are positive, kept = {2,3,4,5}. So cut = {1}. That matches.
Example 2:
n=5, a = [1, -2, 3, 1, -2]
b = [1,0,3,1,0] (max(0,...) -> -2->0, -2->0)
P: P[0]=0, P[1]=1, P[2]=1, P[3]=4, P[4]=5, P[5]=5.
Value 1: indices [1,4]
For i=1, j=4: candidate = P[3] - P[1] = 4 - 1 =3, 2v+candidate = 2+3=5. So sum = 5. Check: a[1]=1, a[4]=1, interior: indices 2,3: we include positive only: index2=-2 (exclude), index3=3 (include). So sum =1+1+3=5. Indeed output total 5.
Value -2: indices [2,5] v=-2: 2v=-4. Compute: minPrefix = P[2]=1 (P[2] = b1+b2=1+0=1). For pj=5: candidate = P[4] - minPrefix =5-1=4, total = -4+4=0. So 0 <5. Also other possibilities: if we consider i=2, j=5, sum = -2 + -2 + interior positives (3? index3=3, index4=1 but careful: interior indices 3 and 4? Actually between 2 and 5: indices 3,4: both positive, so sum = -2-2+3+1=0. Yes. So best is 5.
Now output says "5 2" and cuts trees 2 and 5? Actually output: "5 2\n2 5". That means they cut down trees 2 and 5. Then remaining: indices 1,3,4: values 1,3,1. First=1, last=1, sum=1+3+1=5. So kept set: 1,3,4. That matches our rule: i=1, j=4, interior positive include index3=3, exclude index2=-2. So cut set = {2,5}? Wait also index5 is beyond j (j=4), so index5 is cut as well. So cut = {2,5}. Yes. So our algorithm yields that.
Now we need to generate cut indices: all indices not in K. K = {i, j} ∪ {k: i<k<j and a[k] > 0}? In this case a[3]=3 >0, a[2] negative, so keep index3. Also, index5 is >j, so cut. So cut = {2,5}. Works.
So algorithm is straightforward.
But wait, is there any case where we might need to include some negative interior numbers to maintain at least two trees? The condition says "there must be at least two trees in the woodland belt left." That is satisfied by having i and j distinct, so at least two. So no need to include extra if interior is empty. So fine.
Now we need to ensure that we consider all pairs. The scanning per value yields the maximum difference (P[j-1] - P[i]) for i<j. But is there any other nuance? What if the best sum involves picking first and last equal but also we could choose to exclude some positive interior numbers? That would only reduce sum, so not optimal.
But wait: There is also possibility that the optimal sum might involve not including all positive numbers? For example, if including a positive number would cause the first and last not to be the first and last? No, because interior inclusion does not affect endpoints. So including positive always increases sum. So it's optimal to include all positive interior numbers.
Thus the solution is correct.
Now complexities: n up to 3e5, so we need O(n) or O(n log n). Our method is O(n) after grouping. Use dictionary (unordered_map) for grouping; but values up to 1e9, so use hash map.
Now we need to output the cut indices. So after finding best_i and best_j, we need to output k and list of indices not kept. But the list may be large (up to n-2). We need to output them in increasing order? The problem says: "In the next line print k integers — the numbers of the trees the Beaver needs to cut down." It does not specify order, but typically they expect increasing order. In examples, they print increasing order (1 in first example, 2 5 in second). So we should output in increasing order.
Thus we will iterate through indices 1..n, and for each index, decide if it is kept based on criteria: Keep if index == best_i or index == best_j or (index between best_i and best_j and a[index] > 0? Or >=0?). We'll decide to keep non-negative interior values? But note that zero is non-negative; keeping it doesn't change sum, but might reduce cut count. Let's decide to keep all interior indices with a[k] >= 0. That will produce a valid solution. However, we must verify that the sum of kept values equals the computed bestSum. Because if we include zeros, sum unchanged. So bestSum should be equal to sum of a[i] + a[j] + sum_{i<k<j, a[k]>0} (positives only). But if we also include zeros, sum remains the same (since zero adds nothing). So the sum of kept values with zeros added will still be bestSum? Actually if we include zeros, total sum = sum of a[i] + a[j] + sum_{i<k<j, a[k]>0} + sum_{i<k<j, a[k]==0}*0 = same. So it's fine.
But careful: Could there be negative values? We exclude them. So indeed, sum remains bestSum. So we can include zeros to keep them, or exclude them, either way.
Now, what about indices exactly at i and j? They might be negative. But they are kept regardless. So sum includes them.
Thus, we can define kept set: i <= k <= j, and (k == i or k == j or a[k] >= 0). But wait: Is it always true that a[i] and a[j] are equal, but they could be negative. That's okay.
But we also need to consider indices before i and after j: cut them all.
Now output: First line: bestSum and k (n - |K|). Then second line: list of indices not in K, in increasing order.
Now need to be careful: The bestSum we computed is 2v + (P[j-1] - P[i]), where v = a[i] = a[j]. But is that sum exactly the sum of a[i] + a[j] + sum_{i<k<j and a[k]>0}? Yes because P[j-1] - P[i] = sum_{i+1}^{j-1} max(0, a[k]). So bestSum is that. Good.
Now we also need to ensure that the solution we output indeed has that sum. If we keep all interior a[k] >=0, the sum becomes a[i] + a[j] + sum_{i<k<j, a[k] >= 0}. But note that if a[k] == 0, that's included, but our computed sum didn't include zeros, but zeros add 0, so same. So it matches.
Now one nuance: What if there are positive numbers that we include but some of them are zero? No issue.
Now we need to confirm that the condition "the first and the last trees in the resulting belt must be the same" is satisfied by our kept set: The first kept index is i (since all indices before i are cut), and the last kept index is j (since all indices after j are cut, and we are keeping j). But what if we are also keeping some interior indices that are after j? No, we only keep indices between i and j inclusive, plus maybe we could also keep indices after j? No, because that would make j not last. So we must cut all after j. So our rule (cut all indices > j) ensures that.
Now, what about indices between i and j that we decide to cut? They are cut, but we keep all non-negative ones; we cut the negative ones. So j remains last because any index after j is cut, and any index between i and j that we keep are before j, so j remains last. Similarly, i remains first because all before i are cut.
Thus valid.
Now we need to ensure that we have at least two trees. Since i != j, yes.
Now we must be careful: The problem says: "It is guaranteed that at least two trees have equal esthetic appeal." So there is always a solution.
Now potential pitfalls: The maximum sum might be negative? Since we must have at least two trees, sum could be negative if both endpoints are negative and there are no positive interior numbers. But it's possible. However the problem does not forbid negative sums. So we need to handle that. Our algorithm will compute bestSum maybe negative. Should work.
Now about the prefix sums: P[i] = sum_{t=1}^{i} max(0, a[t]). Since values can be up to 1e9, P can be up to 3e14 (since n up to 3e5, each positive up to 1e9). Use 64-bit integer (long long in C++). Python int fine.
Now implement:
Steps:
- Read n, array a (1-indexed).
- Compute b[i] = max(0, a[i]).
- Compute prefix sums P[0..n] (P[0]=0, for i in 1..n: P[i]=P[i-1]+b[i]).
- Create dictionary mapping value -> list of indices (1-indexed).
- Initialize bestSum = -inf (maybe -10**18), best_i, best_j = None.
- For each value v, list L (sorted; they are already in increasing order as we collect in order).
- m = len(L)
- If m >= 2:
- minPrefixVal = P[L[0]]
- minIdx = L[0]
- For idx from 1 to m-1:
pj = L[idx]
candidate = P[pj-1] - minPrefixVal
current_sum = 2*v + candidate
if current_sum > bestSum:
bestSum = current_sum
best_i = minIdx
best_j = pj
Update minPrefix if P[pj] < minPrefixVal
if P[pj] < minPrefixVal:
minPrefixVal = P[pj]
minIdx = pj
- After loop, we have best_i and best_j.
Now confirm: Could there be a scenario where the optimal pair is not found by this scanning? Because we are scanning and updating minPrefix with P[pj] after using pj as j. That is correct: for each new pj, we consider all previous pi with smallest P[pi]. However, is it always optimal to consider the smallest P[pi]? Yes, because we want to maximize P[pj-1] - P[pi], and P[pj-1] is fixed for given pj, so minimize P[pi]. So scanning works.
But careful: The expression uses P[pj-1] which is based on pj, not P[pj]. So for each pj we compute that. However, when we later update minPrefix, we use P[pj] (not P[pj-1]), because the next pj' will use P[pj'-1] and we need the min over pi of P[pi] among all previous pi. Since pi are just indices, and the value to minimize is P[pi], we store P[pi] as is. That is correct.
Now, consider edge: pj might be such that pj-1 < pi? That cannot happen because pi < pj, so pj-1 >= pi. So P[pj-1] - P[pi] is defined and may be negative. But that's okay.
Now, we might also consider the possibility that we could choose first and last being the same index? Not allowed because at least two trees, so distinct.
Now, after obtaining best_i and best_j, we need to construct kept set.
We could compute list cut = [].
We will iterate over indices 1..n.
- If index < best_i or index > best_j: cut.append(index)
- Else if best_i < index < best_j:
if a[index] < 0: cut.append(index)
else: keep (do nothing)
- Else (index == best_i or index == best_j): keep.
But what about index == best_i and a[index] might be negative? Keep anyway.
Now, is it possible that we might want to cut some interior non-negative values? Not needed.
Thus cut list is determined.
Now we need to output bestSum and len(cut). Then output cut list (space separated). Ensure that cut list order is increasing; our iteration from 1 to n already ensures that.
Now test with examples:
Example1: best_i=2, best_j=5. Then:
Indices:1 (<2) -> cut; 2 keep; 3 (2<3<5, a[3]=3>=0) keep; 4 keep (a[4]=1>=0); 5 keep. So cut=[1] -> matches.
Example2: best_i=1, best_j=4. Then:
1 keep; 2 (1<2<4, a[2]=-2<0) cut; 3 keep (a[3]=3>=0); 4 keep; 5 (>4) cut. So cut=[2,5] matches.
Now need to ensure that bestSum computed matches sum of kept values: In example2, sum kept = a1 + a3 + a4 = 1+3+1=5. Good.
Now consider some other cases.
Case: all numbers negative, but at least two equal. For instance, n=3, a = [-5, -5, -10]. Here we must pick two equal values: indices 1 and 2 both -5. Sum = -5 + -5 = -10 (since no interior positives). That is the best possible? Could also pick 1 and 2? Also maybe 1 and 2 only. Could we pick 1 and 2 and also include interior? There is none. So best sum = -10. Our algorithm: b = [0,0,0], P all 0. Value -5: positions [1,2]. For i=1, j=2: candidate = P[1] - P[1]? Wait pj=2, candidate = P[1] - P[1] =0-0=0, current_sum = 2*(-5)+0 = -10. That's best. So best_i=1,best_j=2. Kept: 1 and 2, cut: index3. Sum = -10. Works.
But check if there is any possibility to get a better sum by including some negative interior? That would lower sum further, so not optimal. So okay.
Case: values with zeros. Example: n=4, a=[0,0,0,0]. All zeros. b=[0,0,0,0], P all 0. P[0]=0. For value 0: positions [1,2,3,4]. Compute best diff: For any i<j, candidate = P[j-1] - P[i] = 0-0=0. So sum = 0. Many pairs. Our scanning: For v=0, positions sorted. minPrefix = P[1]=0, minIdx=1. For pj=2: candidate = P[1]-0=0, sum=0. bestSum initially -inf -> update to 0, best_i=1,best_j=2. Then update minPrefix: P[2]=0 not <0, so minPrefix stays 0, minIdx stays 1? Actually if equal we might not update; but if we update only if strictly less, minIdx remains 1. For pj=3: candidate = P[2]-0=0, sum=0, not > bestSum (0). So best remains (1,2). For pj=4: candidate = P[3]-0=0, same. So best is (1,2). Then kept: i=1,j=2, interior none; we may also include interior non-negative (zeros) if we want. But our cut rule: indices <1? none; >2: indices 3,4 cut? Wait we keep indices between 1 and 2? There is none. For indices between 1 and 2, none. For indices >2, cut. So kept = {1,2}, cut = {3,4}. Sum = 0. But could we have kept more zeros to have larger sum? Sum would still be 0. But also we could have a solution with sum 0 that cuts fewer trees, e.g., keep all trees: sum 0, first=0, last=0, so it also satisfies constraints and has same sum. But our solution cuts 2 trees, which is valid but not necessarily maximizing sum? The objective is only to maximize sum, not minimize cuts. So any sum-maximizing solution is acceptable. Our solution yields sum 0, which is maximum (since all zeros). So it's valid. But could there be a solution with sum >0? No.
But note: we could also choose a pair (1,4) and keep all interior zeros, sum = 0, but cut 0 trees? Actually keep all: indices 1,2,3,4. First=0,last=0, sum=0. That also yields maximum sum 0. But our algorithm selected (1,2) which yields a smaller kept set. That's fine.
However, there is a nuance: When there are multiple pairs achieving the same maximum sum, we can output any. So (1,2) is acceptable.
Now, consider a case where the best sum involves a pair where the interior sum of positives is high, but there might be a tie. Our algorithm picks the first encountered best, but any is fine.
Now, what about the possibility of using a pair where a[i]==a[j] and we can also include some positive numbers outside i..j? No, because they'd change endpoints.
Now, is there any scenario where the best sum is not captured by a pair because we could have more than two trees with same value at ends? But we only need first and last equal; interior may also have that value. But the first and last are determined by the first kept and last kept. So if we have a subsequence where the first element equals the last element, it's fine. That pair is exactly the first and last indices of the subsequence. So it's covered by a pair (i,j) with a[i]==a[j]. So our scanning over all pairs covers all possibilities.
Thus, the solution seems correct.
Now we need to implement efficiently. n up to 3e5, so O(n) scanning per value is fine.
One more nuance: The prefix sum P is used, but we need to be careful with indices: P[0]=0. For index i, P[i] = sum_{1..i} b[t]. So for pj, P[pj-1] is defined when pj>=2? But what if pj=1? That can't be because we need i i, so j>=2. So pj-1>=1? Actually if pj = i+1, then pj-1 = i, and P[i] - P[i] = 0. So it's fine. But pj could be 1? The smallest j is 2 because there must be at least two positions. So pj>=2, so pj-1>=1. So P[pj-1] is valid.
Now what about using P[pj] for updating min? That's fine; pj>=1.
Now we need to store the list of indices per value. Since we read sequentially, we can append indices to dictionary lists.
Now one more subtlety: The maximum sum might be large (up to 21e9 + n1e9 = up to 3e14). So use Python int (unlimited).
Now we need to output the cut trees. We'll build a list of cut indices as described. But note that we might end up with a large list; printing them space-separated in one line. n up to 3e5, so output size could be large but okay.
Now, edge case: Could the optimal sum be achieved by a pair where i and j are such that we keep interior non-negative numbers but also we might decide to keep some negative numbers if they are necessary? No, negative numbers would reduce sum, so not optimal. So cut all negative interior numbers.
Now we should consider if zeros should be kept or not. In our cut rule, we keep interior a[k] >= 0. That includes zeros. That yields sum unchanged. So it's valid.
But one more nuance: What if a[i] or a[j] is negative? They are kept. That's fine.
Now confirm with another test: Suppose a = [5, -100, 5]. P: b=[5,0,5], P[0]=0,P[1]=5,P[2]=5,P[3]=10. Value 5 positions [1,3]. For i=1, j=3: candidate = P[2] - P[1] =5-5=0, sum = 10+0=10? Wait 2v = 10, sum =10. But actually sum = 5+5+ (positive interior? interior index2=-100, exclude) =10. So best sum=10. Our algorithm: minPrefix = P[1]=5, pj=3: candidate = P[2]-5=0, sum=10. That's best. So keep i=1,j=3, cut index2. So output cut: 2. That's fine.
Now what if there is a pair where interior includes many positives but also a negative that is large magnitude? Not relevant.
Now, what if there are multiple values? We'll process all.
Now, implementation steps in Python:
def solve():
import sys
input = sys.stdin.readline
n = int(input().strip())
a = list(map(int, input().split()))
# make 1-indexed for convenience
a = [0] + a # index from 1 to n
b = [0](n+1)
for i in range(1,n+1):
if a[i] > 0:
b[i] = a[i]
else:
b[i] = 0
P = [0](n+1)
for i in range(1,n+1):
P[i] = P[i-1] + b[i]
from collections import defaultdict
pos = defaultdict(list)
for i in range(1,n+1):
pos[a[i]].append(i)
best_sum = -10**18-5 # very negative
best_i = best_j = -1
for v, lst in pos.items():
if len(lst) < 2:
continue
# scan
min_prefix = P[lst[0]]
min_idx = lst[0]
for j_idx in range(1, len(lst)):
pj = lst[j_idx]
candidate = P[pj-1] - min_prefix
cur_sum = 2v + candidate
if cur_sum > best_sum:
best_sum = cur_sum
best_i = min_idx
best_j = pj
# update min_prefix if needed
if P[pj] < min_prefix:
min_prefix = P[pj]
min_idx = pj
# Now best_i, best_j set.
# Construct cut list
cut = []
for idx in range(1, n+1):
if idx < best_i or idx > best_j:
cut.append(idx)
elif best_i < idx < best_j:
if a[idx] < 0:
cut.append(idx)
# else keep (including zeros)
# else idx == best_i or idx == best_j: keep
k = len(cut)
# Print output
print(best_sum, k)
if k > 0:
print(' '.join(map(str, cut)))
else:
# but k could be 0 if we cut no trees; however we need at least 2 trees left, so k <= n-2. k=0 possible? If we keep all trees and they satisfy first==last? Possibly if whole array first==last and we cut none. But then sum might not be maximum? Could be if the whole array already has first==last and we cut nothing yields max sum? But is that always optimal? Our algorithm might produce a pair where we cut nothing if the whole array is already satisfying? Let's see: For the whole array to be kept without cuts, first and last must be equal. That corresponds to a pair (1,n) with a[1]==a[n]. Our algorithm would consider that pair. If it yields best sum, then best_i=1, best_j=n. Our cut construction would then cut indices <1? none; >n? none; interior indices with a<0? That would cut negatives, so if there are negatives, we would cut them, reducing sum? But wait, if we keep the whole array, sum would be total sum. However, our algorithm's sum for pair (1,n) is 2a[1] + sum_{i=2}^{n-1} max(0,a[i]). That may be greater than total sum if there are negatives, because total sum includes negatives, while our computed sum excludes negatives. So if we cut nothing, we would include negatives, which would reduce sum below the computed optimum. So we wouldn't cut nothing because we need to cut negatives to achieve the maximum sum. So our cut list will include at least the interior negatives. So k may be >0. However, if all numbers are non-negative, then sum for pair (1,n) would be total sum (since all are non-negative). And if that is best sum, then our algorithm might pick (1,n) or some other pair. If it picks (1,n), then our cut construction: indices <1 none; >n none; interior indices between 1 and n with a<0 none (all non-negative). So cut = [] -> k=0. That would be valid? Condition: at least two trees left. With cut none, we keep all n trees. n>=2 (given). So it's fine. So we need to handle k=0: print empty line? The output spec: "In the next line print k integers — the numbers of the trees the Beaver needs to cut down." If k=0, we should print an empty line? Usually they expect just newline. In example, they printed a line with the numbers (even if maybe one number). For k=0, we could print an empty line (just newline). That is acceptable. We'll just print after the first line, if k>0 print numbers else print nothing (an empty line). In Python, we can do: print(' '.join(map(str, cut))) if cut else print() maybe. But to be safe, we can always print a newline. So after printing best_sum and k, we can print the line (maybe blank). But careful: if k=0, we should not print any numbers, but we still need a newline? Typically yes. So we can do: print(best_sum, k); if k>0: print(' '.join(map(str, cut))) else: print().
Now verify with scenario: all numbers non-negative, first and last equal? Let's test: n=3, a=[1,2,1]. b=[1,2,1], P:0,1,3,4. Value 1: positions [1,3]. min_prefix=P[1]=1, pj=3: candidate=P[2]-1=3-1=2, cur_sum=2+2=4. That's total sum? a[1]+a[2]+a[3]=1+2+1=4. So best sum=4, best_i=1,best_j=3. Cut list: indices <1 none; >3 none; interior index 2: a[2]=2>=0, keep. So cut = [] => k=0. Output: "4 0" then newline. That's valid.
Now consider if there are multiple values and we need to output any optimal. Our scanning picks the first encountered best. That's fine.
Now we must consider one more nuance: The sum S = 2v + (P[j-1] - P[i]) accounts for interior positives only. But what about the possibility of including interior elements that are positive but we might also include the endpoints? Already included. However, note that if a[i] or a[j] are positive, they are already added as 2v. If they are negative, we still include them because they are endpoints. But is it always optimal to keep endpoints even if they are negative? Because we need them to satisfy the equal condition. But could there be a solution where we keep more than two trees and the first and last are equal, but the actual first tree in the kept subsequence is not the original i but some later index? In our formulation, we are selecting i and j as first and last. So we must keep them. However, consider a scenario where the endpoints are negative and the sum is negative, but maybe there is another solution where we use different endpoints with larger sum. That's fine. Our algorithm considers all pairs.
But is there a scenario where the optimal sum is achieved by a subsequence where the first and last are equal, but the first tree is not