首先操作区间一定不交
其次要考虑转化为单点贡献,反着求,考虑一个点在怎样的子段中可以不被排序
发现:左侧的数都小于等于它,右侧都大于等于它
单调栈维护即可
#include<bits/stdc++.h>
using namespace std;
typedef long long LL ;
const int N = 3e6 + 10 ;
int read()
{
int x = 0 ; char c = getchar() ;
while( !isdigit(c) ) c = getchar() ;
while( isdigit(c) ) x = (x<<1)+(x<<3)+(c^48) , c = getchar() ;
return x ;
}
int n , a[N] ;
// 神奇性质题
// 考虑单点贡献,某个数在怎样的子段里不用重新排序
// 很容易得出错误的结论,但正确的是:左边都小于等于它,右边都大于等于它
// 就很好单调栈处理了
int stk[N] , top , L[N] ;
LL ans , res ;
int main()
{
n = read() ;
for(int i = 1 ; i <= n ; i ++ ) {
a[i] = read() ;
while( top && a[i] >= a[stk[top]] ) top -- ;
L[i] = stk[top] ;
stk[++top] = i ;
res = res + 1LL*(n-i+2)*(n-i+1)/2 ;
}
top = 0 ; stk[0] = n+1 ;
for(int i = n ; i >= 1 ; i -- ) {
while( top && a[i] <= a[stk[top]] ) top -- ;
ans = ans + 1LL*(i-L[i])*(stk[top]-i) ;
stk[++top] = i ;
}
printf("%lld\n" , res-ans ) ;
return 0 ;
}