#include #define rep(i, n) for (int i = 0; i < (n); ++i) using namespace std; using ll = long long; map mp; auto split(int x) { auto it = mp.upper_bound(x); --it; if (it->first == x) return it; return mp.insert({x, it->second}).first; } int get(int x) { return prev(mp.upper_bound(x))->second; } int main() { int n; cin >> n; vector a(n); rep(i, n) cin >> a[i]; vector m(n); vector vis(n+2); int mex = 1; rep(i, n) { vis[a[i]] = true; while (vis[mex]) ++mex; m[i] = mex; } vector nxt(n); vector last(n+2, n); for (int i = n-1; i >= 0; --i) { nxt[i] = last[a[i]]; last[a[i]] = i; } ll now = 0; rep(i, n) { now += m[i]; if (i == 0 or m[i] != m[i-1]) { mp[i] = m[i]; } } mp[n] = 0; ll ans = 0; rep(l, n) { ans += now; int x = a[l]; int r = nxt[l]-1; int ac = r+1, wa = l-1; while (ac-wa > 1) { int wj = (ac+wa)/2; if (get(wj) > x) ac = wj; else wa = wj; } int k = ac; if (k <= r) { auto itr = split(r+1); auto itl = split(k); for (auto it = itl; it != itr; ++it) { int nl = it->first; int nr = next(it)->first-1; int nx = it->second; now -= ll(nr-nl+1)*nx; } mp.erase(itl, itr); mp[k] = x; now += ll(r-k+1)*x; } now -= get(l); } cout << ans << '\n'; return 0; }