#include using namespace std; #ifdef LOCAL #include "debug.h" #else #define DEBUG(...) #endif template struct disjoint_sparse_table { vector> t; disjoint_sparse_table(const vector& v) : t(1, v) { for (int k = 1, n = v.size(); 1 << k < n; ++k) { t.push_back(v); for (int m = 1 << k; m < n; m += 1 << (k + 1)) { partial_sum(rend(v) - m, rend(v) - (m - (1 << k)), rend(t[k]) - m, [](T a, T b) { return b * a; }); partial_sum(begin(v) + m, begin(v) + min(m + (1 << k), n), begin(t[k]) + m, multiplies<>()); } } } T fold(int l, int r) const { assert(l < r); if (l == --r) return t[0][l]; int k = __lg(l ^ r); return t[k][l] * t[k][r]; } }; struct node { int mn, mx; node operator*(node b) const { return {min(mn, b.mn), max(mx, b.mx)}; } }; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; vector p(n); for (auto&& e : p) { cin >> e; --e; } long long res = 0; for (int _ = 2; _--; ) { vector _v(n); for (int i = 0; i < n; ++i) { _v[i] = {p[i], p[i]}; } disjoint_sparse_table st(_v); auto nxt = [&](int i, bool gt = true) { int ok = i + 1, ng = n + 1; while (ng - ok > 1) { int mid = (ok + ng) / 2; if (gt) { (st.fold(i, mid).mx <= p[i] ? ok : ng) = mid; } else { (st.fold(i, mid).mn >= p[i] ? ok : ng) = mid; } } return ok; }; vector dp(17, vector(n + 1, n)); for (int i = 0; i < n; ++i) { dp[0][i] = nxt(i); } for (int k = 0; k < 16; ++k) { for (int i = 0; i < n; ++i) { dp[k + 1][i] = dp[k][dp[k][i]]; } } for (int i = 0; i < n; ++i) { int j = nxt(i, false); int pos = i; for (int k = 17; k--; ) { if (dp[k][pos] < j) { res += 1 << k; pos = dp[k][pos]; } } } reverse(begin(p), end(p)); } cout << res << '\n'; }