#include int ri() { int n; scanf("%d", &n); return n; } struct BIT { int n; std::vector data; std::vector written; BIT (int n) : n(n), data(n + 1, 0) {} void add(int i, int64_t val) { for (i++; i <= n; i += i & -i) data[i] += val, written.push_back(i); } int64_t sum(int r) { int64_t res = 0; for (; r; r &= r - 1) res += data[r]; return res; } void clear() { for (auto i : written) data[i] = 0; written.clear(); } }; struct BIT2 { int n; BIT tree0, tree1, tree2; BIT2(int n) : n(n), tree0(2 * n + 1), tree1(2 * n + 1), tree2(2 * n + 1) {} void add(int l, int r, int64_t val) { l += n; r += n; tree0.add(l, val); tree1.add(l, -val * l); tree2.add(l, val * ((int64_t) l * (l - 1) / 2)); tree0.add(r, -val); tree1.add(r, val * r); tree2.add(r, -val * ((int64_t) l * (l - 1) / 2 + (int64_t) r * (r - l) - (int64_t) (r - l) * (r - l + 1) / 2)); } private : int64_t sum1(int r) { return ((int64_t) r * (r + 1) / 2 * tree0.sum(r) + (int64_t) r * tree1.sum(r) + tree2.sum(r)); } public : int64_t sum2(int l, int r) { l += n; r += n; return sum1(r) - sum1(l); } void clear() { tree0.clear(); tree1.clear(); tree2.clear(); } }; int main() { int n = ri(); int a[n]; std::vector > indexes(n); for (int i = 0; i < n; i++) a[i] = ri(), indexes[a[i]].push_back(i); BIT2 tree(n); int64_t res = 0; for (auto &i : indexes) { tree.add(0, 1, 1); int last = 0; int cur = 0; auto process_empty = [&] (int len) { if (!len) return; res += tree.sum2(cur - len - 1, cur - 1); tree.add(cur - len, cur, 1); cur -= len; }; for (auto j : i) { process_empty(j - last); res += tree.sum2(cur, cur + 1); cur++; tree.add(cur, cur + 1, 1); last = j + 1; } process_empty(n - last); tree.clear(); } std::cout << res << std::endl; return 0; }