Từ Trường Đại học Hoa Lư, Ninh Bình, Trường THPT chuyên Lương Văn Tụy, Ninh Bình
Thông tin
include <bits/stdc++.h>
define int long long
using namespace std; const int maxn = 1e6+10; int n,a[maxn],l[maxn],r[maxn]; signed main() { #define name "haruurara" if (fopen(name ".inp", "r")) { freopen(name ".inp", "r", stdin); freopen(name ".out", "w", stdout); } #define name "haruurara" ios::syncwithstdio(false); cin.tie(nullptr); cin>>n; for(int i=1;i<=n;i++) cin>>a[i]; stack<int> st; for(int i=1;i<=n;i++) { while(!st.empty()&&a[st.top()]<a[i]) st.pop(); if(st.empty()) l[i]=0; else l[i]=st.top(); st.push(i); } while(!st.empty()) st.pop(); for(int i=n;i>=1;i--) { while(!st.empty()&&a[st.top()]<a[i]) st.pop(); if(st.empty()) r[i]=n+1; else r[i]=st.top(); st.push(i); } int res=0; for(int i=1;i<=n;i++){ res += max(0LL, r[i]-i-1); res += max(0LL, i-l[i]-1); } cout<<res; }