#define _USE_MATH_DEFINES #include "bits/stdc++.h" using namespace std; #define FOR(i,j,k) for(int (i)=(j);(i)<(int)(k);++(i)) #define rep(i,j) FOR(i,0,j) #define each(x,y) for(auto &(x):(y)) #define mp make_pair #define MT make_tuple #define all(x) (x).begin(),(x).end() #define debug(x) cout<<#x<<": "<<(x)<; using vi = vector; using vll = vector; template struct BinaryIndexedTree { int n; vector t; BinaryIndexedTree() {} BinaryIndexedTree(int _n) :n(_n + 1), t(_n + 1) {} void add(int k, Val val) { k++; while (k < n) { t[k] += val; k += (k&-k); } } void set(int k, Val val) { add(k, -sum(k, k + 1)); add(k, val); } Val sum(int k) { Val r = 0; while (k > 0) { r += t[k]; k -= (k&-k); } return r; } Val sum(int l, int r) { return sum(r) - sum(l); } }; const int MA = 100001, SQ = 320; vi indices[MA]; void solve() { int N; cin >> N; rep(i, N) { int A; cin >> A; indices[A].push_back(i); } vi flag(N, -1); ll ans = 0; BinaryIndexedTree bit(2 * N + 2); for (int A = 1; A <= MA; ++A) { auto &ids = indices[A]; const int M = sz(ids); each(id, ids) { flag[id] = 1; } if (M < SQ) { // 最も左の要素を固定 rep(i, M) { int p = ids[i]; // 左にいくつ0があるか int leftZeroes = (i ? ids[i] - ids[i - 1] - 1 : p); int cnt = 0; FOR(q, p, min(N, p + 2 * SQ)) { cnt += flag[q]; // cnt, cnt-1, cnt-2, ,,, cnt-leftZeroes // 1以上を数える if (cnt > 0) { ans += min(cnt, leftZeroes + 1); } } } } else { int sum = 0; fill(all(bit.t), 0); bit.add(N, 1); for (int i = 0; i < N; ++i) { sum += flag[i]; ans += bit.sum(N + sum); bit.add(N + sum, 1); } } each(id, ids) { flag[id] = -1; } } cout << ans << endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout << fixed << setprecision(15); solve(); return 0; }