#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define endl codeforces #define ALL(v) std::begin(v), std::end(v) #define ALLR(v) std::rbegin(v), std::rend(v) using ll = std::int64_t; using ull = std::uint64_t; using pii = std::pair; using tii = std::tuple; using pll = std::pair; using tll = std::tuple; template using vec = std::vector; template using vvec = vec>; template const T& var_min(const T &t) { return t; } template const T& var_max(const T &t) { return t; } template const T& var_min(const T &t, const Tail&... tail) { return std::min(t, var_min(tail...)); } template const T& var_max(const T &t, const Tail&... tail) { return std::max(t, var_max(tail...)); } template void chmin(T &t, const Tail&... tail) { t = var_min(t, tail...); } template void chmax(T &t, const Tail&... tail) { t = var_max(t, tail...); } template const T& clamp(const T &t, const T &low, const T &high) { return std::max(low, std::min(high, t)); } template void chclamp(T &t, const T &low, const T &high) { return t = clamp(t, low, high); } template T make_v(T init) { return init; } template auto make_v(T init, std::size_t s, Tail... tail) { auto v = std::move(make_v(init, tail...)); return vec(s, v); } template struct multi_dem_array { using type = std::array::type, Head>; }; template struct multi_dem_array { using type = std::array; }; template using mdarray = typename multi_dem_array::type; namespace init__ { struct InitIO { InitIO() { std::cin.tie(nullptr); std::ios_base::sync_with_stdio(false); std::cout << std::fixed << std::setprecision(30); } } init_io; } const ll inf = 5e15; vec cnt_l(vec p) { ll n = p.size(); p.push_back(n); vec rp(n + 1); for (ll i = 0; i < n; i++) rp[p[i]] = i; auto adjust = [&] { std::set unused; vec ret(n + 1, n); for (ll i = 0; i <= n; i++) unused.insert(i); for (ll e = n - 1; 0 <= e; e--) { ll pos = rp[e]; unused.erase(pos); auto ite = unused.lower_bound(pos); ret[e] = *ite; } return ret; }(); auto dub = make_v(0, 20, n + 1); for (ll i = 0; i <= n; i++) dub[0][i] = adjust[i]; for (ll i = 0; i + 1 < 20; i++) for (ll j = 0; j <= n; j++) { ll pos = dub[i][j]; ll val = p[pos]; dub[i + 1][j] = dub[i][val]; } auto get_cnt = [&](ll pos, ll r) { ll ret = 0; for (ll i = 19; 0 <= i; i--) { ll mask = 1ll << i; ll nxt = dub[i][p[pos]]; if (r <= nxt) continue; ret += mask; pos = nxt; } return ret; }; vec ret(n); std::set used; used.insert(n); for (ll e = n - 1; 0 <= e; e--) { ll pos = rp[e]; ll r = *used.lower_bound(pos); ret[e] = get_cnt(pos, r); used.insert(pos); } return ret; } int main() { ll n; std::cin >> n; vec p(n); for (ll &e : p) { std::cin >> e; e--; } auto lv = cnt_l(p); std::reverse(ALL(p)); auto rv = cnt_l(p); ll ans = 0; for (ll i = 0; i < n; i++) ans += lv[i] + rv[i]; std::cout << ans << '\n'; return 0; }