#include #define fi first #define se second #define FOR(i, a, b) for(int i=(a); i<=(b); ++i) #define REP(i, a, b) for(int i=(a); i>=(b); --i) #define umax(x, y) x = max(x, (y)) #define umin(x, y) x = min(x, (y)) #define BIT(x, i) (((x) >> (i)) & 1) #define MASK(i) (1LL << (i)) #define sz(v) (int)(v).size() #define ALL(v) (v).begin(),(v).end() using namespace std; typedef long long ll; typedef pair pii; typedef pair pll; const int N = 1e6 + 5; const int mod = 1e9 + 7; const int base = 311; const ll INF = 1e18; // Author: rexdino int n, a[N]; int pos[N]; void solve(){ cin >> n; FOR(i, 1, n) cin >> a[i], pos[a[i]] = i; int l = mod, r = 0; ll ans = 0; FOR(x, 0, n - 1){ umin(l, pos[x]); umax(r, pos[x]); if (l <= pos[x + 1] && pos[x + 1] <= r) continue; if (pos[x + 1] < l){ ans += 1ll * (x + 1) * (l - (pos[x + 1] + 1) + 1) * (n - r + 1); // cerr << x + 1 << ": " << 1ll * (l - (pos[x + 1] + 1) + 1) * (n - r + 1) << " ? \n"; } else { ans += 1ll * (x + 1) * l * (pos[x + 1] - r); // cerr << x + 1 << ": " << 1ll * l * (pos[x + 1] - r + 1) << ", " << l << " " << pos[x + 1] << " - \n"; } } cout << ans; } signed main(){ #define NAME "main" if (fopen(NAME".inp", "r")){ freopen(NAME".inp", "r", stdin); freopen(NAME".out", "w", stdout); } ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int t = 1; // cin >> t; while(t--) solve(); // cerr << "Time elapsed: " << (1.0 * clock() / CLOCKS_PER_SEC) << "s\n"; return 0; }