#include #include #include #include #include #include #include using namespace std; long long bruteforce(const vector& a) { const int n = a.size(); long long ans = 0; for (int l = 0; l < n; l++) { for (int r = l; r < n; r++) { vector b(n+2, false); for (int i = l; i <= r; i++) b[a[i]] = true; for (int i = 1; i <= n+1; i++) if (!b[i]) { ans += i; break; } } } return ans; } long long solve(const vector& a) { const int n = a.size(); vector b[n+1]; for (int i = 0; i < n; i++) b[a[i]].push_back(i); long long ans = (long long)n * (n + 1) / 2; if (b[1].empty()) { return ans; } struct entry { int l, r; long long c; bool operator<(const entry& rhs) const { return l < rhs.l || (l == rhs.l && r < rhs.r); }; }; set v; long long s = 0; for (int i : b[1]) { const int l = v.empty() ? -1 : v.rbegin()->l; const long long c = (long long)(i - l) * (n - i); v.insert({i, i, c}); s += c; } ans += s; for (int x = 2; x <= n; x++) { // cerr << "x = " << x << endl; // for (auto [i, j, k] : v) // cerr << '(' << i << ' ' << j << ' ' << k << "); "; cerr << endl; // cerr << "ans = " << ans << endl; // cerr << "s = " << s << endl; if (b[x].empty()) break; // first { const int k = b[x][0]; const auto left = v.begin(); auto right = v.begin(); while (right != v.end() && right->r < k) right++; if (left != right) { entry e2 = *prev(right); for (auto it = v.begin(); it != right; ) { s -= it->c; it = v.erase(it); } long long c = (long long)(e2.l + 1) * (n - k); e2.r = k; e2.c = c; s += c; v.insert(e2); } } // middle for (int j = 1; j < b[x].size(); j++) { const int kl = b[x][j-1], kr = b[x][j]; const auto left = v.lower_bound({kl, kl, 0}); auto right = left; while (right != v.end() && right->r < kr) right++; if (left != right) { entry e1 = *left; entry e2 = *prev(right); const int l1 = left == v.begin() ? -1 : prev(left)->l; const int l2 = kl; // prev(right) == v.begin() ? kl : prev(right, 2)->l; // cerr << "l2 = " << l2 << endl; e1.l = kl; e1.c = (long long)(kl - l1) * (n - e1.r); e2.r = kr; e2.c = (long long)(e2.l - l2) * (n - kr); for (auto it = left; it != right; ) { s -= it->c; it = v.erase(it); } s += e1.c + e2.c; v.insert(e1); v.insert(e2); } } // last { const int kl = b[x].back(); const auto left = v.lower_bound({kl, kl, 0}); if (left != v.end()) { entry e1 = *left; const int l1 = left == v.begin() ? -1 : prev(left)->l; e1.l = kl; e1.c = (long long)(kl - l1) * (n - e1.r); for (auto it = left; it != v.end(); ) { s -= it->c; it = v.erase(it); } s += e1.c; v.insert(e1); } } ans += s; } return ans; } int main() { int n; cin >> n; vector a(n); for (int i = 0; i < n; i++) cin >> a[i]; long long ans = solve(a); // long long expect = bruteforce(a); // if (expect != ans) { // cerr << "wrong answer " << ans << ' ' << expect << endl; // cerr << n << endl; // for (int x : a) cerr << x << ' '; cerr << endl; // } cout << ans << endl; }