#include #include #include #include #include using namespace std; int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) cin >> a[i]; 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()) { cout << ans << endl; return 0; } set > v; long long s = 0; for (int i : b[1]) { const int l = v.empty() ? -1 : get<0>(*v.rbegin()); 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 << "; "; cerr << endl; // cerr << ans << endl; if (b[x].empty()) break; auto left = v.begin(); for (int k : b[x]) { // cerr << "k = " << k << endl; // for (auto [i, j, k] : v) cerr << i << ' ' << j << "; "; cerr << endl; auto it = v.lower_bound({k, k, 0}); // if (it == v.end()) cerr << "end\n"; if (it != left) { while (next(left) != v.end() && get<1>(*next(left)) < k) { s -= get<2>(*left); left = v.erase(left); } const int l1 = left == v.begin() ? -1 : get<0>(*prev(left)); const long long c = (long long)(get<0>(*left) - l1) * (n - k); s += c; v.insert({get<0>(*left), k, c}); s -= get<2>(*left); v.erase(left); } if (it != v.end()) { const int r = get<1>(*it); const int l1 = it == v.begin() ? -1 : get<0>(*prev(it)); const long long c = (long long)(k - l1) * (n - r); s += c; v.insert({k, r, c}); // cerr << k << ' ' << r << endl; } left = it; } ans += s; } cout << ans << endl; }