```cpp
#include<bits/stdc++.h>
using namespace std;
struct abc{
int id,z;
};
int main(){
int n;
scanf("%d",&n);
if(n==0) return 0;
abc a[n+2];
for(int i=1;i<=n;i++){
scanf("%d",&a[i].z);
a[i].id=i;
}
int l=1,r=n;
while(a[l].z<=a[l+1].z) l++;
while(a[r].z<=a[r-1].z) r--;
stack<abc> s;
long long int ans=0;
for(int i=l;i<=r;i++){
if(s.empty()){
s.push(a[i]);
continue;
}
long long int x=0,y=s.top().z,tmp=a[i].id,y2=s.top().z;
while(!s.empty()&&s.top().z<a[i].z){
y2=s.top().z;
s.pop();
x=0;
if(!s.empty())
x=tmp-s.top().id-1;
if(!s.empty())
y=min(s.top().z,a[i].z)-y2;
ans+=x*y;
}
s.push(a[i]);
}
printf("%lld\n",ans);
}
```
先送个单调栈AC
by bayerfans @ 2023-04-14 22:19:43