//Let's join Kaede Takagaki Fan Club !! #include #include #include using namespace std; typedef long long ll; typedef pair P; typedef pair P1; typedef pair P2; #define pu push #define pb push_back #define mp make_pair #define eps 1e-7 #define INF 1000000000 #define fi first #define sc second #define rep(i,x) for(int i=0;i void dmp(T a){ rep(i,a.size()) cout << a[i] << " "; cout << endl; } template bool chmax(T&a, T b){ if(a < b){ a = b; return 1; } return 0; } template bool chmin(T&a, T b){ if(a > b){ a = b; return 1; } return 0; } template void g(T &a){ cin >> a; } template void o(const T &a,bool space=false){ cout << a << (space?' ':'\n'); } //ios::sync_with_stdio(false); const int mod = 1000000007; template void add(T&a,T b){ a+=b; if(a >= mod) a-=mod; } struct RMQ{ #define s (1<<18) int seg[s]; void init(){ memset(seg, 0, sizeof(seg)); } void update(int k,int a){ k+=s/2-1; seg[k]=a; while(k>0){ k=(k-1)/2; seg[k]=(seg[k*2+1]+seg[k*2+2]); } } int query(int a,int b,int k,int l,int r){ if(rvec[100005]; void solve(vectorvi){ int n = vi.size(); vectormx(n), mn(n); stack

st; rep(i, n){ while(st.size() && st.top().fi < vi[i]){ mx[st.top().sc] = i-1; st.pop(); } st.push(mp(vi[i],i)); } while(st.size()) { mx[st.top().sc] = n-1; st.pop(); } for(int i=n-1;i>=0;i--){ while(st.size() && st.top().fi > vi[i]){ mn[st.top().sc] = i+1; st.pop(); } st.push(mp(vi[i],i)); } while(st.size()) { mn[st.top().sc] = 0; st.pop(); } rep(i, n){ vec[i].clear(); } rep(i, n) vec[mn[i]].pb(i); rmq.init(); for(int i=n-1;i>=0;i--){ for(auto at:vec[i+1]) rmq.update(at, 0); int L = i, R = mx[i]; ans += rmq.query(L, R, 0, 0, s/2-1); rmq.update(i, 1); } } int main(){ int n; scanf("%d",&n); vectorvi(n); rep(i, n) scanf("%d", &vi[i]); solve(vi); reverse(all(vi)); solve(vi); o(ans); }