题面
来源:USACO 官网。模型收到的是同一份题面的文字。
**Note: The time limit for this problem is 3s, 1.5x the default.**
You are given a length-$N$ integer array $a_1,a_2,\dots,a_N$ ($2\le N\le 10^6, 1\le a_i\le N$). Output the sum of the answers for the subproblem below over all $N(N+1)/2$ contiguous subarrays of $a$.
Given a nonempty list of integers, alternate the following operations (starting with the first operation) until the list has size exactly one.
- Replace two consecutive integers in the list with their minimum.
- Replace two consecutive integers in the list with their maximum.
Determine the maximum possible value of the final remaining integer.
For example,
[4, 10, 3] -> [4, 3] -> [4] [3, 4, 10] -> [3, 10] -> [10]
In the first array, $(10, 3)$ is replaced by $\min(10, 3)=3$ and $(4, 3)$ is replaced by $\max(4, 3)=4$.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains $N$.The second line contains $a_1,a_2,\dots,a_N$.
OUTPUT FORMAT (print output to the terminal / stdout):
The sum of the answer to the subproblem over all subarrays.SAMPLE INPUT:
2 2 1
SAMPLE OUTPUT:
4
The answer for $[2]$ is $2$, the answer for $[1]$ is $1$, and the answer for $[2, 1]$ is $1$.
Thus, our output should be $2+1+1 = 4$.
SAMPLE INPUT:
3 3 1 3
SAMPLE OUTPUT:
12
SAMPLE INPUT:
4 2 4 1 3
SAMPLE OUTPUT:
22
Consider the subarray $[2, 4, 1, 3]$.
- Applying the first operation on (1, 3), our new array is $[2, 4, 1]$.
- Applying the second operation on (4, 1), our new array is $[2, 4]$.
- Applying the third operation on (2, 4), our final number is $2$.
It can be proven that $2$ is the maximum possible value of the final number.
SCORING:
- Inputs 4-5: $N\le 100$
- Inputs 6-7: $N\le 5000$
- Inputs 8-9: $\max(a)\le 10$
- Inputs 10-13: No additional constraints.
Problem credits: Benjamin Qi
结果
Kimi K3.1 ProKimi
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 40.2k平均输出 token(含思考) ↓
- 25.5输出速度 tokens/s ↑
- 1672 秒延迟 ↓
- 0.82×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
Kimi K3.1 Pro(high)Kimi high
1/3
解出的采样 ↑
- 100采样 1 · 解出
- 23.1采样 2 · 答案错误
- 23.1采样 3 · 答案错误
- 31.7k平均输出 token(含思考) ↓
- 23.6输出速度 tokens/s ↑
- 1330 秒延迟 ↓
- 0.96×CPU 时间 / 官方解 ↓
- 同阶 1时间复杂度(相对官方解)
DeepSeek Flash V4.1-1017DeepSeek
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 55.1k平均输出 token(含思考) ↓
- 184.5输出速度 tokens/s ↑
- 303 秒延迟 ↓
- 2.78×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
MiniMax M3.1 FlashMiniMax
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 75.4k平均输出 token(含思考) ↓
- 165.9输出速度 tokens/s ↑
- 449 秒延迟 ↓
- 0.69×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
#include <bits/stdc++.h> using namespace std; using int64 = long long; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); int maxValue = 0; for (int i = 1; i <= N; ++i) { cin >> a[i]; maxValue = max(maxValue, a[i]); } // Positions are bucketed by value. vector<int> head(maxValue + 1, -1), nextInBucket(N + 1, -1); for (int i = 1; i <= N; ++i) { nextInBucket[i] = head[a[i]]; head[a[i]] = i; } auto gapEven = [](int g) -> int64 { return 1LL * (g / 2) * ((g + 1) / 2); }; auto gapOdd = [&](int g) -> int64 { return 1LL * g * (g + 1) / 2 - gapEven(g); }; // Number of even-length subarrays containing p, with left endpoint in // [P+1,p] and right endpoint in [p,Q-1]. auto oneActiveEven = [](int p, int P, int Q) -> int64 { int64 leftEven = p / 2 - P / 2; int64 leftOdd = (p + 1) / 2 - (P + 1) / 2; int64 rightEven = (Q - 1) / 2 - (p - 1) / 2; int64 rightOdd = Q / 2 - p / 2; return leftEven * rightOdd + leftOdd * rightEven; }; const int64 totalSubarrays = 1LL * N * (N + 1) / 2; const int64 totalEven = gapEven(N); const int64 totalOdd = totalSubarrays - totalEven; // Initially every position is active. vector<int> left(N + 2), right(N + 2); for (int i = 1; i <= N; ++i) { left[i] = i - 1; right[i] = i + 1; } right[0] = 1; left[N + 1] = N; int64 zeroEven = 0, zeroOdd = 0, exactlyOneEven = 0; int64 sumMaximumOdd = 0, sumSecondMaximumEven = 0; int previousValue = 0; // Process thresholds increasingly, removing positions below the next threshold. for (int value = 1; value <= maxValue; ++value) { if (head[value] == -1) continue; int64 withActiveOdd = totalOdd - zeroOdd; int64 withTwoActiveEven = totalEven - zeroEven - exactlyOneEven; int64 delta = value - previousValue; sumMaximumOdd += delta * withActiveOdd; sumSecondMaximumEven += delta * withTwoActiveEven; previousValue = value; for (int p = head[value]; p != -1; p = nextInBucket[p]) { int P = left[p], Q = right[p]; exactlyOneEven -= oneActiveEven(p, P, Q); if (P != 0) { int PP = left[P]; exactlyOneEven -= oneActiveEven(P, PP, p); exactlyOneEven += oneActiveEven(P, PP, Q); } if (Q != N + 1) { int QQ = right[Q]; exactlyOneEven -= oneActiveEven(Q, p, QQ); exactlyOneEven += oneActiveEven(Q, P, QQ); } int oldGapLeft = p - P - 1; int oldGapRight = Q - p - 1; int mergedGap = Q - P - 1; zeroEven += gapEven(mergedGap) - gapEven(oldGapLeft) - gapEven(oldGapRight); zeroOdd += gapOdd(mergedGap) - gapOdd(oldGapLeft) - gapOdd(oldGapRight); right[P] = Q; left[Q] = P; } } /* For odd lengths at least 5, the answer is the subarray maximum. For even lengths at least 8, it is the second maximum. Lengths 1 and 2 already agree with these formulas. Only lengths 3, 4, and 6 need corrections. */ int64 correction = 0; for (int i = 1; i + 2 <= N; ++i) { int x = a[i], y = a[i + 1], z = a[i + 2]; int rangeMaximum = max(x, max(y, z)); int answer = max(max(min(x, y), z), max(x, min(y, z))); correction += answer - rangeMaximum; } for (int i = 1; i + 3 <= N; ++i) { int v[4] = {a[i], a[i + 1], a[i + 2], a[i + 3]}; sort(v, v + 4); int second = v[2], third = v[1]; if (second > third) { int positions[2], count = 0; for (int j = 0; j < 4; ++j) { if (a[i + j] >= second) positions[count++] = j + 1; } int p = positions[0], q = positions[1]; bool losing = (p == 1 && q == 3) || (p == 2 && q == 3) || (p == 2 && q == 4); if (losing) correction += (int64)third - second; } } for (int i = 1; i + 5 <= N; ++i) { int v[6] = {a[i], a[i + 1], a[i + 2], a[i + 3], a[i + 4], a[i + 5]}; sort(v, v + 6); int second = v[4], third = v[3]; if (second > third) { int positions[2], count = 0; for (int j = 0; j < 6; ++j) { if (a[i + j] >= second) positions[count++] = j + 1; } int p = positions[0], q = positions[1]; bool losing = (p == 2 && q == 4) || (p == 2 && q == 5) || (p == 3 && q == 5); if (losing) correction += (int64)third - second; } } cout << sumMaximumOdd + sumSecondMaximumEven + correction << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; static ll smallExcluded[7][7]; // Number of subarrays of an inactive gap having lengths // first, first+2, first+4, ... . static inline ll gapCount(ll d, int first) { if (d < first) return 0; ll k = (d - first) / 2 + 1; return k * (d - first + 1) - k * (k - 1); } // A specified active position is at distance A from the active position // on its left and B from the one on its right. Count even-length (>=8) // subarrays containing this position and no other active position. static inline ll oneActiveCount(ll A, ll B) { ll evenA = (A + 1) / 2, oddA = A / 2; ll evenB = (B + 1) / 2, oddB = B / 2; // If u+v is odd, the corresponding subarray has even length. ll result = evenA * oddB + oddA * evenB; int ia = A >= 6 ? 6 : (int)A; int ib = B >= 6 ? 6 : (int)B; // Exclude lengths 2, 4 and 6. result -= smallExcluded[ia][ib]; return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); int maxA = 0; for (int i = 1; i <= N; ++i) { cin >> a[i]; maxA = max(maxA, a[i]); } // Precompute exclusions for sums u+v = 1,3,5. Only A,B <= 6 matter. for (int A = 1; A <= 6; ++A) { for (int B = 1; B <= 6; ++B) { for (int s : {1, 3, 5}) { int lo = max(0, s - (B - 1)); int hi = min(s, A - 1); if (lo <= hi) smallExcluded[A][B] += hi - lo + 1; } } } ll answer = 0; // Length 1. for (int i = 1; i <= N; ++i) answer += a[i]; // Length 3: the answer is the maximum of the two endpoints. for (int i = 1; i + 2 <= N; ++i) { answer += max(a[i], a[i + 2]); } // Lengths 2, 4 and 6. For two distinguished elements p<q, let the // three gaps around/between them have sizes L,M,R. The pair works // exactly when the number of nonempty gaps is at most len/2-1. auto addEvenLength = [&](int len) { if (len > N) return; int rounds = len / 2 - 1; vector<pair<int, int>> pairs; for (int p = 0; p < len; ++p) { for (int q = p + 1; q < len; ++q) { int nonemptyGaps = (p > 0) + (q - p - 1 > 0) + (len - 1 - q > 0); if (nonemptyGaps <= rounds) { pairs.emplace_back(p, q); } } } for (int start = 1; start + len - 1 <= N; ++start) { int best = 0; for (auto [p, q] : pairs) { best = max(best, min(a[start + p], a[start + q])); } answer += best; } }; addEvenLength(2); addEvenLength(4); addEvenLength(6); /* Remaining subarrays: - odd length >= 5: answer is the subarray maximum; - even length >= 8: answer is the subarray second maximum. For a threshold x, call positions with value >= x active. We need: - odd long subarrays containing at least one active position; - even long subarrays containing at least two active positions. Summing these counts over x=1..max(a) gives the required sum. Active positions are maintained under deletions in a linked list. */ const ll totalOdd = gapCount(N, 5); const ll totalEven = gapCount(N, 8); ll zeroOdd = 0; // Qualifying odd subarrays with no active position. ll zeroEven = 0; // Qualifying even subarrays with no active position. ll exactlyOne = 0; // Qualifying even subarrays with exactly one active. vector<int> prv(N + 2), nxt(N + 2); for (int i = 0; i <= N + 1; ++i) { prv[i] = i - 1; nxt[i] = i + 1; } // Buckets of positions by value, using linked lists. vector<int> head(N + 1, -1), bucketNext(N + 1, -1); for (int i = 1; i <= N; ++i) { bucketNext[i] = head[a[i]]; head[a[i]] = i; } for (int x = 1; x <= maxA; ++x) { answer += totalOdd - zeroOdd; answer += totalEven - zeroEven - exactlyOne; if (x == maxA) break; // Delete positions whose value is x, preparing threshold x+1. for (int i = head[x]; i != -1; i = bucketNext[i]) { int p = prv[i]; int q = nxt[i]; ll A = i - p; ll B = q - i; // Merge the two inactive gaps, with position i joining them. zeroOdd += gapCount(A + B - 1, 5) - gapCount(A - 1, 5) - gapCount(B - 1, 5); zeroEven += gapCount(A + B - 1, 8) - gapCount(A - 1, 8) - gapCount(B - 1, 8); // Remove i's exactly-one-active contribution. exactlyOne -= oneActiveCount(A, B); // Only the nearest active neighbors change their contributions. if (p != 0) { ll leftDistance = p - prv[p]; exactlyOne -= oneActiveCount(leftDistance, A); exactlyOne += oneActiveCount(leftDistance, A + B); } if (q != N + 1) { ll rightDistance = nxt[q] - q; exactlyOne -= oneActiveCount(B, rightDistance); exactlyOne += oneActiveCount(A + B, rightDistance); } nxt[p] = q; prv[q] = p; } } cout << answer << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; static int lowPairs[7][7]; // Number of odd-length subarrays of length at least 5 in a segment of length g. static inline int64 oddFamily(int g) { if (g < 5) return 0; int64 h = (g + 1) / 2; int64 allOdd = h * (g + 1 - h); return allOdd - g - (g - 2); } // Number of even-length subarrays of length at least 8 in a segment of length g. static inline int64 evenFamily(int g) { if (g < 8) return 0; int64 h = g / 2; int64 allEven = h * (g - h); return allEven - (g - 1) - (g - 3) - (g - 5); } /* Count subarrays containing one distinguished active position, where: L left endpoints and R right endpoints are available. The subarray must have even length at least 8. If x and y are the numbers of positions used on the two sides, then x+y must be odd and at least 7. */ static inline int64 oneActiveEven(int L, int R) { if (L + R <= 8) return 0; int64 evenL = (L + 1LL) / 2; int64 oddL = L / 2; int64 evenR = (R + 1LL) / 2; int64 oddR = R / 2; int64 result = evenL * oddR + oddL * evenR; result -= lowPairs[min(L, 6)][min(R, 6)]; return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); // Pairs with odd sum less than 7, for small capped values of L and R. for (int L = 0; L <= 6; ++L) { for (int R = 0; R <= 6; ++R) { for (int x = 0; x <= 5; ++x) { for (int y = 0; y <= 5; ++y) { if (x < L && y < R && ((x + y) & 1) && x + y < 7) { ++lowPairs[L][R]; } } } } } int N; if (!(cin >> N)) return 0; vector<int> a(N + 1); vector<int> head(N + 1, -1), bucketNext(N + 1, -1); int maxA = 0; for (int i = 1; i <= N; ++i) { cin >> a[i]; maxA = max(maxA, a[i]); bucketNext[i] = head[a[i]]; head[a[i]] = i; } int64 answer = 0; // Length 1. for (int i = 1; i <= N; ++i) { answer += a[i]; } // Length 2. for (int i = 1; i + 1 <= N; ++i) { answer += min(a[i], a[i + 1]); } // Length 3. for (int i = 1; i + 2 <= N; ++i) { answer += max(a[i], a[i + 2]); } // Length 4. for (int i = 1; i + 3 <= N; ++i) { int cur = min(a[i], a[i + 1]); cur = max(cur, min(a[i], a[i + 3])); cur = max(cur, min(a[i + 2], a[i + 3])); answer += cur; } /* Length 6. A pair of positions can supply the final two numbers iff: - it contains the first position, or - it contains the last position, or - its two positions are adjacent. */ for (int i = 1; i + 5 <= N; ++i) { int x0 = a[i], x1 = a[i + 1], x2 = a[i + 2]; int x3 = a[i + 3], x4 = a[i + 4], x5 = a[i + 5]; int maxAfterFirst = max(max(x1, x2), max(x3, x4)); maxAfterFirst = max(maxAfterFirst, x5); int maxBeforeLast = max(max(x0, x1), max(x2, x3)); maxBeforeLast = max(maxBeforeLast, x4); int adjacent = min(x0, x1); adjacent = max(adjacent, min(x1, x2)); adjacent = max(adjacent, min(x2, x3)); adjacent = max(adjacent, min(x3, x4)); adjacent = max(adjacent, min(x4, x5)); int cur = max(min(x0, maxAfterFirst), min(maxBeforeLast, x5)); cur = max(cur, adjacent); answer += cur; } /* For odd lengths at least 5, the answer is the subarray maximum. For even lengths at least 8, it is the second maximum. Sweep the threshold v. Positions with value at least v are active. A maximum is at least v iff a subarray contains an active position; a second maximum is at least v iff it contains at least two. */ if (N >= 5) { const int64 totalOdd = oddFamily(N); const int64 totalEven = evenFamily(N); const bool needEven = (totalEven != 0); vector<int> prev(N + 2), next(N + 2); for (int i = 0; i <= N + 1; ++i) { prev[i] = i - 1; next[i] = i + 1; } int64 zeroOdd = 0; int64 zeroEven = 0; int64 exactlyOneEven = 0; for (int v = 1; v <= maxA; ++v) { answer += totalOdd - zeroOdd; if (needEven) { answer += totalEven - zeroEven - exactlyOneEven; } // No further threshold is needed, so avoid the final deletions. if (v == maxA) break; for (int i = head[v]; i != -1; i = bucketNext[i]) { int p = prev[i]; int q = next[i]; int gapLeft = i - p - 1; int gapRight = q - i - 1; int mergedGap = q - p - 1; zeroOdd += oddFamily(mergedGap) - oddFamily(gapLeft) - oddFamily(gapRight); if (needEven) { zeroEven += evenFamily(mergedGap) - evenFamily(gapLeft) - evenFamily(gapRight); // Remove the term belonging to position i. exactlyOneEven -= oneActiveEven(i - p, q - i); // p's next active position changes from i to q. if (p != 0) { int leftChoices = p - prev[p]; exactlyOneEven += oneActiveEven(leftChoices, q - p) - oneActiveEven(leftChoices, i - p); } // q's previous active position changes from i to p. if (q != N + 1) { int rightChoices = next[q] - q; exactlyOneEven += oneActiveEven(q - p, rightChoices) - oneActiveEven(q - i, rightChoices); } } next[p] = q; prev[q] = p; } } } cout << answer << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); int maxValue = 0; for (int i = 1; i <= N; ++i) { cin >> a[i]; maxValue = max(maxValue, a[i]); } // Positions are bucketed by value. vector<int> head(maxValue + 1, -1), nextInBucket(N + 1, -1); for (int i = 1; i <= N; ++i) { nextInBucket[i] = head[a[i]]; head[a[i]] = i; } auto gapEven = [](int g) -> int64 { return 1LL * (g / 2) * ((g + 1) / 2); }; auto gapOdd = [&](int g) -> int64 { return 1LL * g * (g + 1) / 2 - gapEven(g); }; // Number of even-length subarrays containing p, with left endpoint in // [P+1,p] and right endpoint in [p,Q-1]. auto oneActiveEven = [](int p, int P, int Q) -> int64 { int64 leftEven = p / 2 - P / 2; int64 leftOdd = (p + 1) / 2 - (P + 1) / 2; int64 rightEven = (Q - 1) / 2 - (p - 1) / 2; int64 rightOdd = Q / 2 - p / 2; return leftEven * rightOdd + leftOdd * rightEven; }; const int64 totalSubarrays = 1LL * N * (N + 1) / 2; const int64 totalEven = gapEven(N); const int64 totalOdd = totalSubarrays - totalEven; // Initially every position is active. vector<int> left(N + 2), right(N + 2); for (int i = 1; i <= N; ++i) { left[i] = i - 1; right[i] = i + 1; } right[0] = 1; left[N + 1] = N; int64 zeroEven = 0, zeroOdd = 0, exactlyOneEven = 0; int64 sumMaximumOdd = 0, sumSecondMaximumEven = 0; int previousValue = 0; // Process thresholds increasingly, removing positions below the next threshold. for (int value = 1; value <= maxValue; ++value) { if (head[value] == -1) continue; int64 withActiveOdd = totalOdd - zeroOdd; int64 withTwoActiveEven = totalEven - zeroEven - exactlyOneEven; int64 delta = value - previousValue; sumMaximumOdd += delta * withActiveOdd; sumSecondMaximumEven += delta * withTwoActiveEven; previousValue = value; for (int p = head[value]; p != -1; p = nextInBucket[p]) { int P = left[p], Q = right[p]; exactlyOneEven -= oneActiveEven(p, P, Q); if (P != 0) { int PP = left[P]; exactlyOneEven -= oneActiveEven(P, PP, p); exactlyOneEven += oneActiveEven(P, PP, Q); } if (Q != N + 1) { int QQ = right[Q]; exactlyOneEven -= oneActiveEven(Q, p, QQ); exactlyOneEven += oneActiveEven(Q, P, QQ); } int oldGapLeft = p - P - 1; int oldGapRight = Q - p - 1; int mergedGap = Q - P - 1; zeroEven += gapEven(mergedGap) - gapEven(oldGapLeft) - gapEven(oldGapRight); zeroOdd += gapOdd(mergedGap) - gapOdd(oldGapLeft) - gapOdd(oldGapRight); right[P] = Q; left[Q] = P; } } /* For odd lengths at least 5, the answer is the subarray maximum. For even lengths at least 8, it is the second maximum. Lengths 1 and 2 already agree with these formulas. Only lengths 3, 4, and 6 need corrections. */ int64 correction = 0; for (int i = 1; i + 2 <= N; ++i) { int x = a[i], y = a[i + 1], z = a[i + 2]; int rangeMaximum = max(x, max(y, z)); int answer = max(max(min(x, y), z), max(x, min(y, z))); correction += answer - rangeMaximum; } for (int i = 1; i + 3 <= N; ++i) { int v[4] = {a[i], a[i + 1], a[i + 2], a[i + 3]}; sort(v, v + 4); int second = v[2], third = v[1]; if (second > third) { int positions[2], count = 0; for (int j = 0; j < 4; ++j) { if (a[i + j] >= second) positions[count++] = j + 1; } int p = positions[0], q = positions[1]; bool losing = (p == 1 && q == 3) || (p == 2 && q == 3) || (p == 2 && q == 4); if (losing) correction += (int64)third - second; } } for (int i = 1; i + 5 <= N; ++i) { int v[6] = {a[i], a[i + 1], a[i + 2], a[i + 3], a[i + 4], a[i + 5]}; sort(v, v + 6); int second = v[4], third = v[3]; if (second > third) { int positions[2], count = 0; for (int j = 0; j < 6; ++j) { if (a[i + j] >= second) positions[count++] = j + 1; } int p = positions[0], q = positions[1]; bool losing = (p == 2 && q == 4) || (p == 2 && q == 5) || (p == 3 && q == 5); if (losing) correction += (int64)third - second; } } cout << sumMaximumOdd + sumSecondMaximumEven + correction << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; unsigned char winning[7][64]; bool gameWins(const vector<int>& b, bool minOperation) { if (b.size() == 1) return b[0]; int m = (int)b.size(); for (int i = 0; i + 1 < m; ++i) { vector<int> c = b; if (minOperation) c[i] = b[i] & b[i + 1]; else c[i] = b[i] | b[i + 1]; c.erase(c.begin() + i + 1); if (gameWins(c, !minOperation)) return true; } return false; } void precomputeWinningMasks() { for (int n = 1; n <= 6; ++n) { for (int mask = 0; mask < (1 << n); ++mask) { vector<int> b(n); for (int i = 0; i < n; ++i) b[i] = (mask >> i) & 1; winning[n][mask] = gameWins(b, true); } } } int smallAnswer(const int* v, int n) { int order[6]; for (int i = 0; i < n; ++i) order[i] = i; for (int i = 1; i < n; ++i) { int x = order[i], j = i; while (j > 0 && v[order[j - 1]] < v[x]) { order[j] = order[j - 1]; --j; } order[j] = x; } int mask = 0; for (int i = 0; i < n; ++i) { mask |= 1 << order[i]; if (winning[n][mask]) return v[order[i]]; } return 0; } long long parityCount(int l, int r, int p) { if (l > r) return 0; int len = r - l + 1; if ((l & 1) == p) return (len + 1) / 2; return len / 2; } // Counts pairs (l,r) in the two intervals having the requested parity, // then removes the short subarrays already handled directly. long long rectangleCount(int A, int B, int C, int D, bool sameParity, int maxShortDistance) { if (A > B || C > D) return 0; long long lo = parityCount(A, B, 1); long long le = parityCount(A, B, 0); long long ro = parityCount(C, D, 1); long long re = parityCount(C, D, 0); long long result; if (sameParity) result = lo * ro + le * re; else result = lo * re + le * ro; for (int d = sameParity ? 0 : 1; d <= maxShortDistance; d += 2) { int l = max(A, C - d); int r = min(B, D - d); if (l <= r) result -= r - l + 1; } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); precomputeWinningMasks(); int N; cin >> N; vector<int> a(N); for (int& x : a) cin >> x; long long answer = 0; // All subarrays of length at most 6. for (int i = 0; i < N; ++i) answer += a[i]; for (int i = 0; i + 1 < N; ++i) answer += min(a[i], a[i + 1]); for (int i = 0; i + 2 < N; ++i) answer += max(a[i], a[i + 2]); for (int i = 0; i + 3 < N; ++i) answer += smallAnswer(a.data() + i, 4); for (int i = 0; i + 4 < N; ++i) { int mx = a[i]; for (int j = 1; j < 5; ++j) mx = max(mx, a[i + j]); answer += mx; } for (int i = 0; i + 5 < N; ++i) answer += smallAnswer(a.data() + i, 6); // For odd lengths at least 7 the answer is the maximum. // For even lengths at least 8 it is the second maximum. // Use a total order on elements, breaking equal values by index. auto stronger = [&](int i, int j) { return a[i] > a[j] || (a[i] == a[j] && i < j); }; vector<int> prevStronger(N), nextStronger(N), st; st.reserve(N); for (int i = 0; i < N; ++i) { while (!st.empty() && stronger(i, st.back())) st.pop_back(); prevStronger[i] = st.empty() ? -1 : st.back(); st.push_back(i); } st.clear(); for (int i = N - 1; i >= 0; --i) { while (!st.empty() && stronger(i, st.back())) st.pop_back(); nextStronger[i] = st.empty() ? N : st.back(); st.push_back(i); } for (int i = 0; i < N; ++i) { int p = prevStronger[i]; int q = nextStronger[i]; // Subarrays for which a[i] is the maximum. Keep odd lengths >= 7. long long cnt = rectangleCount( p + 1, i, i, q - 1, true, 4 ); answer += cnt * a[i]; // a[i] is the second strongest element, and the strongest is on its left. if (p != -1) { int p2 = prevStronger[p]; cnt = rectangleCount( p2 + 1, p, i, q - 1, false, 5 ); answer += cnt * a[i]; } // The strongest element is on the right of a[i]. if (q != N) { int q2 = nextStronger[q]; cnt = rectangleCount( p + 1, i, q, q2 - 1, false, 5 ); answer += cnt * a[i]; } } cout << answer << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; struct FastSet { static constexpr int INF = INT_MAX; int n; vector<int> sz; vector<vector<uint64_t>> bits; explicit FastSet(int n_) : n(n_) { int cur = n; while (true) { sz.push_back(cur); bits.emplace_back((cur + 63) / 64, 0); if (cur == 1) break; cur = (cur + 63) / 64; } } void insert(int x) { for (int lev = 0; lev < (int)bits.size(); ++lev) { int w = x >> 6; uint64_t mask = 1ULL << (x & 63); uint64_t old = bits[lev][w]; bits[lev][w] = old | mask; if (old != 0 || lev + 1 == (int)bits.size()) break; x = w; } } int nextAt(int lev, int x) const { if (x >= sz[lev]) return INF; int w = x >> 6; int b = x & 63; uint64_t mask = bits[lev][w] & (~0ULL << b); if (mask) return (w << 6) + __builtin_ctzll(mask); if (lev + 1 == (int)bits.size()) return INF; int nw = nextAt(lev + 1, w + 1); if (nw == INF) return INF; return (nw << 6) + __builtin_ctzll(bits[lev][nw]); } int prevAt(int lev, int x) const { if (x < 0) return -1; int w = x >> 6; int b = x & 63; uint64_t mask = bits[lev][w] & (~0ULL >> (63 - b)); if (mask) return (w << 6) + 63 - __builtin_clzll(mask); if (lev + 1 == (int)bits.size()) return -1; int nw = prevAt(lev + 1, w - 1); if (nw == -1) return -1; return (nw << 6) + 63 - __builtin_clzll(bits[lev][nw]); } int next(int x) const { if (x < 0) x = 0; return nextAt(0, x); } int prev(int x) const { if (x >= n) x = n - 1; return prevAt(0, x); } }; struct SegTree { int n; vector<long long> sum; vector<int> setv, addv; explicit SegTree(int n_) : n(n_), sum(4 * n_), setv(4 * n_), addv(4 * n_) {} void applySet(int v, int l, int r, int x) { sum[v] = 1LL * (r - l + 1) * x; setv[v] = x; addv[v] = 0; } void applyAdd(int v, int l, int r, int x) { sum[v] += 1LL * (r - l + 1) * x; addv[v] += x; } void push(int v, int l, int r) { if (!setv[v] && !addv[v]) return; int m = (l + r) >> 1; if (setv[v]) { applySet(v << 1, l, m, setv[v]); applySet(v << 1 | 1, m + 1, r, setv[v]); setv[v] = 0; } if (addv[v]) { applyAdd(v << 1, l, m, addv[v]); applyAdd(v << 1 | 1, m + 1, r, addv[v]); addv[v] = 0; } } void rangeSet(int v, int l, int r, int ql, int qr, int x) { if (ql <= l && r <= qr) { applySet(v, l, r, x); return; } push(v, l, r); int m = (l + r) >> 1; if (ql <= m) rangeSet(v << 1, l, m, ql, qr, x); if (qr > m) rangeSet(v << 1 | 1, m + 1, r, ql, qr, x); sum[v] = sum[v << 1] + sum[v << 1 | 1]; } void rangeAdd(int v, int l, int r, int ql, int qr, int x) { if (ql <= l && r <= qr) { applyAdd(v, l, r, x); return; } push(v, l, r); int m = (l + r) >> 1; if (ql <= m) rangeAdd(v << 1, l, m, ql, qr, x); if (qr > m) rangeAdd(v << 1 | 1, m + 1, r, ql, qr, x); sum[v] = sum[v << 1] + sum[v << 1 | 1]; } void setRange(int l, int r, int x) { rangeSet(1, 0, n - 1, l, r, x); } void addRange(int l, int r, int x) { rangeAdd(1, 0, n - 1, l, r, x); } long long total() const { return sum[1]; } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> head(N + 1, -1), nxt(N + 1); for (int i = 1; i <= N; ++i) { int x; cin >> x; nxt[i] = head[x]; head[x] = i; } // Parity 0: even positions. Parity 1: odd positions. FastSet active[2] = {FastSet(N / 2), FastSet((N + 1) / 2)}; SegTree seg[2] = {SegTree(N / 2), SegTree((N + 1) / 2)}; auto actualPos = [](int parity, int idx) { return 2 * idx + (parity ? 1 : 2); }; auto countLE = [](int parity, int x) { if (x <= 0) return 0; return parity ? (x + 1) / 2 : x / 2; }; auto endpointCount = [&](int pos) { return (N - pos) / 2 + 1; }; auto activate = [&](int p) { int s = p & 1; int o = s ^ 1; int k = s ? (p - 1) / 2 : p / 2 - 1; int prevSame = active[s].prev(k - 1); int nextSame = active[s].next(k + 1); int tP = countLE(o, p); int nextOpp = active[o].next(tP); int value = endpointCount(p); if (nextOpp != FastSet::INF) { value += endpointCount(actualPos(o, nextOpp)); } // Activating p can give an earlier second required position to // a contiguous collection of starts of the opposite parity. int prevPos = prevSame >= 0 ? actualPos(s, prevSame) : 0; int tLeft = countLE(o, prevPos); int lastOpp = active[o].prev(tP - 1); if (lastOpp >= tLeft) { int before = active[o].prev(tLeft - 1); int oldValue = 0; if (nextSame != FastSet::INF) { oldValue = endpointCount(actualPos(s, nextSame)); } int delta = endpointCount(p) - oldValue; seg[o].addRange(before + 1, lastOpp, delta); } // Starts whose nearest activated position of their own parity // becomes p. seg[s].setRange(prevSame + 1, k, value); active[s].insert(k); }; long long answer = 0; for (int value = N; value >= 1; --value) { for (int p = head[value]; p != -1; p = nxt[p]) { activate(p); } answer += seg[0].total() + seg[1].total(); } cout << answer << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; static inline ll calcE(int g) { // Number of even-length subarrays of length >= 8 inside a gap of length g. if (g < 8) return 0; ll T = g / 2; // even lengths are 2*t, 4 <= t <= T if (T < 4) return 0; ll sumT = T * (T + 1) / 2 - 6; // sum t for t=4..T return (T - 3) * (g + 1LL) - 2 * sumT; } static inline ll calcF(int l, int r) { // Count pairs (x,y), 0<=x<=l, 0<=y<=r, // with x+y odd and x+y >= 7. ll evenL = l / 2 + 1; ll oddL = (l + 1) / 2; ll evenR = r / 2 + 1; ll oddR = (r + 1) / 2; ll total = evenL * oddR + oddL * evenR; ll small = 0; for (int s = 1; s <= 5; s += 2) { int lo = max(0, s - r); int hi = min(l, s); if (lo <= hi) small += hi - lo + 1; } return total - small; } static inline ll countOddMax(int L, int R) { // Count x in [0,L-1], y in [0,R-1] with x+y even and x+y >= 4. ll evenL = (L + 1LL) / 2; ll oddL = L / 2; ll evenR = (R + 1LL) / 2; ll oddR = R / 2; ll total = evenL * evenR + oddL * oddR; ll bad = 1; // (0,0) if (L >= 1 && R >= 3) ++bad; // (0,2) if (L >= 2 && R >= 2) ++bad; // (1,1) if (L >= 3 && R >= 1) ++bad; // (2,0) return total - bad; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N); int maxA = 0; vector<int> head(N + 1, -1), nxt(N); for (int i = 0; i < N; ++i) { cin >> a[i]; int v = a[i]; nxt[i] = head[v]; head[v] = i; if (v > maxA) maxA = v; } ll ans = 0; // Length 1 for (int i = 0; i < N; ++i) ans += a[i]; // Length 2 for (int i = 0; i + 1 < N; ++i) { ans += min(a[i], a[i + 1]); } // Length 3 for (int i = 0; i + 2 < N; ++i) { ans += max(a[i], a[i + 2]); } // Length 4 for (int i = 0; i + 3 < N; ++i) { int v1 = min(a[i], a[i + 1]); int v2 = min(a[i + 2], a[i + 3]); int v3 = min(a[i], a[i + 3]); ans += max({v1, v2, v3}); } // Length 6 if (N >= 6) { for (int s = 0; s + 5 < N; ++s) { int best = 0; for (int i = 0; i < 6; ++i) { for (int j = i + 1; j < 6; ++j) { // Forbidden 0-indexed pairs: (1,3), (1,4), (2,4) if ((i == 1 && j == 3) || (i == 1 && j == 4) || (i == 2 && j == 4)) { continue; } best = max(best, min(a[s + i], a[s + j])); } } ans += best; } } // Odd lengths >= 5: answer is the maximum element. vector<int> leftLen(N); vector<int> st; st.reserve(N); for (int i = 0; i < N; ++i) { while (!st.empty() && a[st.back()] <= a[i]) st.pop_back(); int p = st.empty() ? -1 : st.back(); leftLen[i] = i - p; st.push_back(i); } st.clear(); for (int i = N - 1; i >= 0; --i) { while (!st.empty() && a[st.back()] < a[i]) st.pop_back(); int q = st.empty() ? N : st.back(); int R = q - i; int L = leftLen[i]; ans += 1LL * a[i] * countOddMax(L, R); st.push_back(i); } // Even lengths >= 8: answer is the second largest element. // Sum over thresholds T: count subarrays with at least two elements >= T. vector<int> prevPos(N), nextPos(N); for (int i = 0; i < N; ++i) { prevPos[i] = i - 1; nextPos[i] = i + 1; } ll zeroActive = 0; ll oneActive = 0; ll totalEven8 = calcE(N); ll currentC = totalEven8; ll secondSum = 0; for (int T = 1; T <= maxA; ++T) { secondSum += currentC; for (int p = head[T]; p != -1; p = nxt[p]) { int L = prevPos[p]; int R = nextPos[p]; int l = p - L - 1; int r = R - p - 1; int g = R - L - 1; zeroActive -= calcE(l) + calcE(r); zeroActive += calcE(g); oneActive -= calcF(l, r); if (L >= 0) { int LL = prevPos[L]; int lgL = L - LL - 1; oneActive -= calcF(lgL, l); oneActive += calcF(lgL, g); } if (R < N) { int RR = nextPos[R]; int rgR = RR - R - 1; oneActive -= calcF(r, rgR); oneActive += calcF(g, rgR); } if (L >= 0) nextPos[L] = R; if (R < N) prevPos[R] = L; currentC = totalEven8 - zeroActive - oneActive; } } ans += secondSum; cout << ans << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; static inline ll Feven(int g) { // Number of subarrays inside a gap of length g // having even length >= 8. if (g < 8) return 0; ll K = (g - 8) / 2; return (K + 1) * ((ll)g - 7 - K); } static inline ll Fodd(int g) { // Number of subarrays inside a gap of length g // having odd length >= 7. if (g < 7) return 0; ll K = (g - 7) / 2; return (K + 1) * ((ll)g - 6 - K); } static inline ll cntEven(int n) { // Number of even integers in [0, n] if (n < 0) return 0; return n / 2 + 1; } static inline ll cntOdd(int n) { // Number of odd integers in [0, n] if (n < 0) return 0; return (n + 1) / 2; } static inline ll H(int A, int B) { // Count pairs (x,y), 0<=x<=A, 0<=y<=B, such that // x+y is odd and x+y >= 7. if (A < 0 || B < 0) return 0; ll ceA = cntEven(A), coA = cntOdd(A); ll ceB = cntEven(B), coB = cntOdd(B); ll total = ceA * coB + coA * ceB; // x+y odd ll sub = 0; // Remove x+y = 1, 3, 5 for (int s = 1; s <= 5; s += 2) { int lo = max(0, s - B); int hi = min(A, s); if (lo <= hi) sub += hi - lo + 1; } return total - sub; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int N; cin >> N; vector<int> a(N + 1); for (int i = 1; i <= N; ++i) cin >> a[i]; ll ans = 0; // Handle all small lengths directly. // L = 1 for (int i = 1; i <= N; ++i) ans += a[i]; // L = 2 if (N >= 2) { for (int i = 1; i + 1 <= N; ++i) { ans += min(a[i], a[i + 1]); } } // L = 3 if (N >= 3) { for (int i = 1; i + 2 <= N; ++i) { ans += max(a[i], a[i + 2]); } } // L = 4 if (N >= 4) { for (int i = 1; i + 3 <= N; ++i) { int v1 = min(a[i], a[i + 1]); int v2 = min(a[i + 2], a[i + 3]); int v3 = min(a[i], a[i + 3]); ans += max(v1, max(v2, v3)); } } // L = 5 if (N >= 5) { for (int i = 1; i + 4 <= N; ++i) { int mx = a[i]; for (int j = 1; j <= 4; ++j) mx = max(mx, a[i + j]); ans += mx; } } // L = 6 if (N >= 6) { for (int i = 1; i + 5 <= N; ++i) { int b[6]; for (int j = 0; j < 6; ++j) b[j] = a[i + j]; int c[6]; for (int j = 0; j < 6; ++j) c[j] = b[j]; sort(c, c + 6, greater<int>()); ll third = c[2]; ll bestPair = 0; for (int p = 0; p < 6; ++p) { for (int q = p + 1; q < 6; ++q) { bool bad = (p == 1 && q == 3) || // (2,4) in 1-based (p == 1 && q == 4) || // (2,5) (p == 2 && q == 4); // (3,5) if (!bad) { bestPair = max(bestPair, (ll)min(b[p], b[q])); } } } ans += max(third, bestPair); } } // For odd length >= 7: answer is the maximum. // For even length >= 8: answer is the second maximum. // // Compute their sums by threshold sweep over values. vector<int> head(N + 2, -1), nxt(N + 1, 0); for (int i = 1; i <= N; ++i) { int v = a[i]; nxt[i] = head[v]; head[v] = i; } ll totalOdd = Fodd(N); ll totalEven = Feven(N); ll zeroOdd = totalOdd; ll zeroEven = totalEven; ll oneEven = 0; vector<int> leftGap(N + 2, 0), rightGap(N + 2, 0); set<int> active; ll ansLargeOdd = 0; ll ansLargeEven = 0; for (int v = N; v >= 1; --v) { for (int p = head[v]; p != -1; p = nxt[p]) { auto it = active.lower_bound(p); int s = (it == active.end() ? N + 1 : *it); int q; if (it == active.begin()) q = 0; else q = *prev(it); int g = s - q - 1; int L = p - q - 1; int R = s - p - 1; zeroEven -= Feven(g); zeroEven += Feven(L) + Feven(R); zeroOdd -= Fodd(g); zeroOdd += Fodd(L) + Fodd(R); if (q > 0) { oneEven -= H(leftGap[q], rightGap[q]); rightGap[q] = p - q - 1; oneEven += H(leftGap[q], rightGap[q]); } if (s <= N) { oneEven -= H(leftGap[s], rightGap[s]); leftGap[s] = s - p - 1; oneEven += H(leftGap[s], rightGap[s]); } leftGap[p] = p - q - 1; rightGap[p] = s - p - 1; oneEven += H(leftGap[p], rightGap[p]); active.insert(p); } ansLargeOdd += totalOdd - zeroOdd; ansLargeEven += totalEven - zeroEven - oneEven; } ans += ansLargeOdd + ansLargeEven; cout << ans << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; class FastScanner { static constexpr int BUFSIZE = 1 << 20; int idx = 0, size = 0; char buf[BUFSIZE]; char getChar() { if (idx >= size) { size = (int)fread(buf, 1, BUFSIZE, stdin); idx = 0; if (size == 0) return 0; } return buf[idx++]; } public: int nextInt() { char c = getChar(); while (c && (c < '0' || c > '9')) c = getChar(); int x = 0; while (c >= '0' && c <= '9') { x = x * 10 + (c - '0'); c = getChar(); } return x; } }; static inline long long countParityRange(int l, int r, int p) { if (l > r) return 0; if (p == 0) { // even return r / 2 - (l - 1) / 2; } else { // odd return (r + 1LL) / 2 - l / 2; } } static inline long long countEvenLenGE8(int l1, int l2, int r1, int r2) { if (l1 > l2 || r1 > r2) return 0; long long oddL = countParityRange(l1, l2, 1); long long evenL = countParityRange(l1, l2, 0); long long oddR = countParityRange(r1, r2, 1); long long evenR = countParityRange(r1, r2, 0); // Need r - l odd, i.e. l and r have opposite parity. long long total = oddL * evenR + evenL * oddR; // Subtract r - l = 1, 3, 5, since we need r - l >= 7. long long bad = 0; for (int d : {1, 3, 5}) { int lo = max(l1, r1 - d); int hi = min(l2, r2 - d); if (lo <= hi) bad += (long long)(hi - lo + 1); } long long res = total - bad; return res > 0 ? res : 0; } int main() { FastScanner fs; int N = fs.nextInt(); vector<int> a(N + 1); for (int i = 1; i <= N; ++i) a[i] = fs.nextInt(); long long ans = 0; // Length 1 for (int i = 1; i <= N; ++i) ans += a[i]; // Length 2 for (int i = 1; i + 1 <= N; ++i) { ans += min(a[i], a[i + 1]); } // Length 3 for (int i = 1; i + 2 <= N; ++i) { ans += max(a[i], a[i + 2]); } // Length 4 for (int i = 1; i + 3 <= N; ++i) { int v1 = min(a[i], a[i + 1]); int v2 = min(a[i], a[i + 3]); int v3 = min(a[i + 2], a[i + 3]); ans += max({v1, v2, v3}); } // Length 6 static const int pairs6[12][2] = { {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 6}, {3, 4}, {3, 6}, {4, 5}, {4, 6}, {5, 6} }; for (int i = 1; i + 5 <= N; ++i) { int best = 0; for (int k = 0; k < 12; ++k) { int x = a[i + pairs6[k][0] - 1]; int y = a[i + pairs6[k][1] - 1]; best = max(best, min(x, y)); } ans += best; } // Odd lengths >= 5: answer is maximum of the subarray. vector<int> prv(N + 1), nxt(N + 1); vector<int> st; st.reserve(N); for (int i = 1; i <= N; ++i) { while (!st.empty() && a[st.back()] <= a[i]) st.pop_back(); prv[i] = st.empty() ? 0 : st.back(); st.push_back(i); } st.clear(); for (int i = N; i >= 1; --i) { while (!st.empty() && a[st.back()] < a[i]) st.pop_back(); nxt[i] = st.empty() ? N + 1 : st.back(); st.push_back(i); } long long oddMaxSum = 0; for (int i = 1; i <= N; ++i) { long long A = i - prv[i]; long long B = nxt[i] - i; long long oddA = (A + 1) / 2; long long evenA = A / 2; long long oddB = (B + 1) / 2; long long evenB = B / 2; long long total = oddA * oddB + evenA * evenB; long long bad = 0; if (A >= 1 && B >= 1) ++bad; // u + v = 2 if (A >= 1 && B >= 3) ++bad; // u + v = 4 if (A >= 2 && B >= 2) ++bad; // u + v = 4 if (A >= 3 && B >= 1) ++bad; // u + v = 4 long long cnt = total - bad; if (cnt < 0) cnt = 0; oddMaxSum += 1LL * a[i] * cnt; } ans += oddMaxSum; // Even lengths >= 8: answer is the second maximum of the subarray. vector<int> head(N + 1, -1), nextPos(N + 1); for (int i = 1; i <= N; ++i) { int v = a[i]; nextPos[i] = head[v]; head[v] = i; } set<int> active; active.insert(0); active.insert(N + 1); long long cur = 0; long long evenSecondMaxSum = 0; for (int x = N; x >= 1; --x) { for (int p = head[x]; p != -1; p = nextPos[p]) { auto itR = active.lower_bound(p); int R = *itR; auto itL = prev(itR); int L = *itL; int prevL = 0; int nextR = N + 1; if (L != 0) { auto itPrevL = prev(itL); prevL = *itPrevL; } if (R != N + 1) { auto itNextR = next(itR); nextR = *itNextR; } long long add = 0; // Subarrays newly getting at least two active positions: // include p and L, but not R. if (L > 0) { add += countEvenLenGE8(prevL + 1, L, p, R - 1); } // Include p and R, but not L. if (R <= N) { add += countEvenLenGE8(L + 1, p, R, nextR - 1); } cur += add; active.insert(p); } evenSecondMaxSum += cur; } ans += evenSecondMaxSum; printf("%lld\n", ans); return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct NextTwo { vector<int> first, second; }; // For every position, find the first and second positions to its right // whose values are >= its value (GreaterEqual = true), or > its value. template <bool GreaterEqual> NextTwo findNextTwo(const vector<int>& a) { int n = (int)a.size(); NextTwo result; result.first.assign(n, n); result.second.assign(n, n); vector<int> waitingFirst, waitingSecond, temporary; waitingFirst.reserve(n); waitingSecond.reserve(n); temporary.reserve(n); auto qualifies = [&](int current, int waiting) { if constexpr (GreaterEqual) { return a[current] >= a[waiting]; } else { return a[current] > a[waiting]; } }; for (int i = 0; i < n; ++i) { while (!waitingSecond.empty() && qualifies(i, waitingSecond.back())) { result.second[waitingSecond.back()] = i; waitingSecond.pop_back(); } temporary.clear(); while (!waitingFirst.empty() && qualifies(i, waitingFirst.back())) { result.first[waitingFirst.back()] = i; temporary.push_back(waitingFirst.back()); waitingFirst.pop_back(); } for (int j = (int)temporary.size() - 1; j >= 0; --j) { waitingSecond.push_back(temporary[j]); } waitingFirst.push_back(i); } return result; } struct ParityCounts { int64 even, odd; }; inline ParityCounts countParity(int left, int right) { if (left > right) return {0, 0}; int64 length = right - left + 1; int64 even = (length + ((left & 1) == 0 ? 1 : 0)) / 2; return {even, length - even}; } inline int secondLargest(const int* a, int length) { int largest = 0; int second = 0; for (int i = 0; i < length; ++i) { if (a[i] >= largest) { second = largest; largest = a[i]; } else if (a[i] > second) { second = a[i]; } } return second; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n); for (int& x : a) cin >> x; // Nearest and second-nearest positions to the right with value >= a[i]. NextTwo next = findNextTwo<true>(a); // Nearest and second-nearest positions to the left with value > a[i]. vector<int> previous1(n, -1), previous2(n, -1); { vector<int> reversed(a.rbegin(), a.rend()); NextTwo prev = findNextTwo<false>(reversed); for (int i = 0; i < n; ++i) { int reversedIndex = n - 1 - i; if (prev.first[reversedIndex] < n) { previous1[i] = n - 1 - prev.first[reversedIndex]; } if (prev.second[reversedIndex] < n) { previous2[i] = n - 1 - prev.second[reversedIndex]; } } } int64 answer = 0; // Sum maxima over all odd-length subarrays, and second maxima over // all even-length subarrays. for (int i = 0; i < n; ++i) { // i is the rightmost occurrence of the maximum. // An odd-length interval has endpoints of the same parity. { ParityCounts left = countParity(previous1[i] + 1, i); ParityCounts right = countParity(i, next.first[i] - 1); int64 count = left.even * right.even + left.odd * right.odd; answer += count * a[i]; } // i is the second-largest element, and the largest lies to its right. if (next.first[i] < n) { ParityCounts left = countParity(previous1[i] + 1, i); ParityCounts right = countParity(next.first[i], next.second[i] - 1); int64 count = left.even * right.odd + left.odd * right.even; answer += count * a[i]; } // i is the second-largest element, and the largest lies to its left. if (previous1[i] >= 0) { ParityCounts left = countParity(previous2[i] + 1, previous1[i]); ParityCounts right = countParity(i, next.first[i] - 1); int64 count = left.even * right.odd + left.odd * right.even; answer += count * a[i]; } } // Length 3: the answer is max(a[i], a[i+2]), rather than the // maximum of all three elements. for (int i = 0; i + 2 < n; ++i) { int ordinary = max(a[i], max(a[i + 1], a[i + 2])); int actual = max(a[i], a[i + 2]); answer += actual - ordinary; } // Length 4: allowed pairs are (1,2), (3,4), and (1,4). for (int i = 0; i + 3 < n; ++i) { int ordinary = secondLargest(a.data() + i, 4); int actual = max( min(a[i], a[i + 1]), max( min(a[i + 2], a[i + 3]), min(a[i], a[i + 3]) ) ); answer += actual - ordinary; } // Length 6: an allowed pair has an endpoint, or consists of // two consecutive positions. for (int i = 0; i + 5 < n; ++i) { int ordinary = secondLargest(a.data() + i, 6); int actual = 0; for (int p = 0; p < 6; ++p) { for (int q = p + 1; q < 6; ++q) { if (p == 0 || q == 5 || q == p + 1) { actual = max(actual, min(a[i + p], a[i + q])); } } } answer += actual - ordinary; } cout << answer << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; // Number of integers of parity p in [l, r], where p = 0 means even. static int64 parityCount(int l, int r, int p) { if (l > r) return 0; int64 len = r - l + 1; int64 even = r / 2 - (l - 1) / 2; return (p == 0 ? even : len - even); } // Count pairs (l, r) with l in [l1, l2], r in [r1, r2], // such that r-l+1 has the requested parity and is at least minLen. static int64 countPairs(int l1, int l2, int r1, int r2, int parity, int minLen) { if (l1 > l2 || r1 > r2) return 0; int64 lc[2] = { parityCount(l1, l2, 0), parityCount(l1, l2, 1) }; int64 rc[2] = { parityCount(r1, r2, 0), parityCount(r1, r2, 1) }; int64 result; if (parity == 1) { // Odd length: l and r have the same parity. result = lc[0] * rc[0] + lc[1] * rc[1]; } else { // Even length: l and r have different parities. result = lc[0] * rc[1] + lc[1] * rc[0]; } // Remove intervals shorter than minLen. for (int len = 1; len < minLen; ++len) { if ((len & 1) != parity) continue; int d = len - 1; int lo = max(l1, r1 - d); int hi = min(l2, r2 - d); if (lo <= hi) result -= hi - lo + 1; } return result; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; ++i) cin >> a[i]; int64 answer = 0; // Length 1. for (int i = 1; i <= n; ++i) { answer += a[i]; } // Length 2. for (int i = 1; i < n; ++i) { answer += min(a[i], a[i + 1]); } // Length 3. for (int i = 1; i + 2 <= n; ++i) { answer += max(a[i], a[i + 2]); } // Length 4. for (int i = 1; i + 3 <= n; ++i) { int best = max({ min(a[i], a[i + 1]), min(a[i], a[i + 3]), min(a[i + 2], a[i + 3]) }); answer += best; } // Length 6. for (int i = 1; i + 5 <= n; ++i) { int best = 0; for (int p = 1; p <= 6; ++p) { for (int q = p + 1; q <= 6; ++q) { // These are exactly the feasible pairs of positions. if (p == 1 || q == p + 1 || q == 6) { best = max(best, min(a[i + p - 1], a[i + q - 1])); } } } answer += best; } // Break ties by index: (a[i], i), so all order statistics are unique. auto greaterKey = [&](int x, int y) { return a[x] > a[y] || (a[x] == a[y] && x > y); }; vector<int> L1(n + 2, 0), L2(n + 2, 0); vector<int> R1(n + 2, n + 1), R2(n + 2, n + 1); vector<int> s1, s2, temp; s1.reserve(n); s2.reserve(n); temp.reserve(n); // First and second greater elements to the right. for (int i = 1; i <= n; ++i) { while (!s2.empty() && greaterKey(i, s2.back())) { R2[s2.back()] = i; s2.pop_back(); } temp.clear(); while (!s1.empty() && greaterKey(i, s1.back())) { R1[s1.back()] = i; temp.push_back(s1.back()); s1.pop_back(); } // Transfer in reverse order. while (!temp.empty()) { s2.push_back(temp.back()); temp.pop_back(); } s1.push_back(i); } s1.clear(); s2.clear(); temp.clear(); // First and second greater elements to the left. for (int i = n; i >= 1; --i) { while (!s2.empty() && greaterKey(i, s2.back())) { L2[s2.back()] = i; s2.pop_back(); } temp.clear(); while (!s1.empty() && greaterKey(i, s1.back())) { L1[s1.back()] = i; temp.push_back(s1.back()); s1.pop_back(); } while (!temp.empty()) { s2.push_back(temp.back()); temp.pop_back(); } s1.push_back(i); } for (int i = 1; i <= n; ++i) { // Odd lengths >= 5: the answer is the maximum. int64 cnt = countPairs( L1[i] + 1, i, i, R1[i] - 1, 1, 5 ); answer += 1LL * a[i] * cnt; // Even lengths >= 8: the answer is the second-largest value. cnt = 0; // The unique greater element is to the left. cnt += countPairs( L2[i] + 1, L1[i], i, R1[i] - 1, 0, 8 ); // The unique greater element is to the right. cnt += countPairs( L1[i] + 1, i, R1[i], R2[i] - 1, 0, 8 ); answer += 1LL * a[i] * cnt; } cout << answer << '\n'; return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct ParityCounts { int64 even, odd; }; static inline ParityCounts parityCounts(int l, int r) { if (l > r) return {0, 0}; int64 len = r - l + 1; int64 even = r / 2 - (l - 1) / 2; return {even, len - even}; } static int secondLargest(const vector<int>& a, int first, int len) { int largest = 0, second = 0; for (int j = 0; j < len; ++j) { int x = a[first + j]; if (x >= largest) { second = largest; largest = x; } else if (x > second) { second = x; } } return second; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vector<int> a(n + 1); for (int i = 1; i <= n; ++i) cin >> a[i]; // Break ties by index, so every subarray has a unique maximum // and a unique second maximum under this ordering. vector<int64> key(n + 1); for (int i = 1; i <= n; ++i) { key[i] = 1LL * a[i] * (n + 1) + i; } // L1/L2: first and second positions to the left with a larger key. // R1/R2: first and second positions to the right with a larger key. vector<int> L1(n + 2, 0), L2(n + 2, 0); vector<int> R1(n + 2, n + 1), R2(n + 2, n + 1); vector<int> st1, st2, moved; st1.reserve(n); st2.reserve(n); moved.reserve(n); // Second greater element to the right. for (int i = 1; i <= n; ++i) { while (!st2.empty() && key[st2.back()] < key[i]) { R2[st2.back()] = i; st2.pop_back(); } moved.clear(); while (!st1.empty() && key[st1.back()] < key[i]) { int j = st1.back(); st1.pop_back(); R1[j] = i; moved.push_back(j); } while (!moved.empty()) { st2.push_back(moved.back()); moved.pop_back(); } st1.push_back(i); } st1.clear(); st2.clear(); moved.clear(); // Second greater element to the left. for (int i = n; i >= 1; --i) { while (!st2.empty() && key[st2.back()] < key[i]) { L2[st2.back()] = i; st2.pop_back(); } moved.clear(); while (!st1.empty() && key[st1.back()] < key[i]) { int j = st1.back(); st1.pop_back(); L1[j] = i; moved.push_back(j); } while (!moved.empty()) { st2.push_back(moved.back()); moved.pop_back(); } st1.push_back(i); } int64 answer = 0; // Sum of maxima over all odd-length subarrays. for (int i = 1; i <= n; ++i) { ParityCounts left = parityCounts(L1[i] + 1, i); ParityCounts right = parityCounts(i, R1[i] - 1); // An odd-length interval has endpoints of the same parity. int64 count = left.even * right.even + left.odd * right.odd; answer += 1LL * a[i] * count; } // Sum of second maxima over all even-length subarrays. for (int i = 1; i <= n; ++i) { // The maximum is to the left of the second maximum. if (L1[i] != 0) { ParityCounts left = parityCounts(L2[i] + 1, L1[i]); ParityCounts right = parityCounts(i, R1[i] - 1); // An even-length interval has endpoints of opposite parity. int64 count = left.even * right.odd + left.odd * right.even; answer += 1LL * a[i] * count; } // The maximum is to the right of the second maximum. if (R1[i] != n + 1) { ParityCounts left = parityCounts(L1[i] + 1, i); ParityCounts right = parityCounts(R1[i], R2[i] - 1); int64 count = left.even * right.odd + left.odd * right.even; answer += 1LL * a[i] * count; } } // Correct length-3 subarrays: // actual answer = max(first, third), rather than max(first, second, third). for (int i = 1; i + 2 <= n; ++i) { int allThree = max({a[i], a[i + 1], a[i + 2]}); int endpoints = max(a[i], a[i + 2]); answer -= allThree - endpoints; } // Correct length-4 subarrays. for (int i = 1; i + 3 <= n; ++i) { int special = max({ min(a[i], a[i + 1]), min(a[i], a[i + 3]), min(a[i + 2], a[i + 3]) }); int baseline = secondLargest(a, i, 4); answer -= baseline - special; } // Correct length-6 subarrays. static constexpr int allowedPairs[12][2] = { {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {2, 3}, {2, 6}, {3, 4}, {3, 6}, {4, 5}, {4, 6}, {5, 6} }; for (int i = 1; i + 5 <= n; ++i) { int special = 0; for (const auto& p : allowedPairs) { special = max(special, min(a[i + p[0] - 1], a[i + p[1] - 1])); } int baseline = secondLargest(a, i, 6); answer -= baseline - special; } cout << answer << '\n'; return 0; }