#include using namespace std; using P = pair; const int M = 1000000007; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector> vv(100010); for (int i = 0; i < n; ++i) { int a; cin >> a; vv[a].push_back(i + 1); } long long ans = 0; for (const auto& v : vv) { if (v.size() == 0) continue; stack

st; st.push({0, 0}); unordered_map mp; mp[0] = 0; int pd = 0, pj = 0; int mind = 0; for (int j : v) { int d = pd - (j - pj - 1) + 1; mind = min(mind, d); if (pj != j - 1) { ans -= mp[pd]; if (mp.count(d - 1)) ans += mp[d - 1]; } while (!st.empty() && st.top().first < d) { st.pop(); } if (!st.empty()) { int k = st.top().second + st.top().first - d; mp[d] += j - k - 1; ans += mp[d] * 2; } else { mp[d] = j; ans += j * 2; } st.push({d, j}); pd = d; pj = j; } ans -= mp[pd]; for (int i = mind; i < pd - n + pj; ++i) { ans -= mp[i]; } } cout << ans << '\n'; return 0; }