#include #include using namespace std; #include using ull = unsigned long long; struct S { ull sum; unsigned max, size; S() = default; }; S op(S l, S r) noexcept { return {l.sum + r.sum, l.max > r.max ? l.max : r.max, l.size + r.size}; } S e() noexcept { return {0, 0, 0}; } S mapping(unsigned f, S x) noexcept { return f ? S{(unsigned long long)x.size * f, x.size ? f : 0, x.size} : x; } unsigned composition(unsigned f, unsigned g) noexcept { return f ? f : g; } unsigned id() noexcept { return 0; } int main() { ios::sync_with_stdio(false), cin.tie(nullptr); unsigned N; cin >> N; vector> v2is(N); for (unsigned i = 0; i < N; i++) { unsigned a; cin >> a; v2is[a - 1].push_back(i); } long long ret = 0; vector init(N); for (int i = 0; i < N; i++) init[i] = {(unsigned)i, (unsigned)i, 1}; atcoder::lazy_segtree tree(init); for (int h = 0; h < N; h++) { int l = 0; for (auto i : v2is[h]) { int r = tree.max_right(l, [&](S x) { return x.max <= i; }); if (l < r) tree.apply(l, r, i); l = i + 1; } tree.apply(l, N, N); auto tmp = (long long)N * N - tree.all_prod().sum; ret += tmp; if (!tmp) break; } cout << ret + (long long)N * (N + 1) / 2 << '\n'; }