不知为何WA了一个点,感觉没有问题
#include <bits/stdc++.h>
#define pii pair<int,int>
#define mkp(x,y) make_pair(x,y)
using namespace std;
const int maxn=1e4+1;
int n,tot,ans,a[maxn],maxx[maxn],sum[maxn];
bool flag;
pii top[maxn];
int main(){
scanf("%d",&n);
for (int i=1;i<=n;i++){
scanf("%d",&a[i]);
sum[i]=sum[i-1]+a[i];
}
for (int i=1;i<=n;i++){
if ((a[i]>a[i-1]) ^ flag){
if (flag){
while (tot>=2 && maxx[tot-1]>top[tot].second && top[tot].second<a[i-1]) tot--;
top[++tot]=mkp(i-1,a[i-1]);
maxx[tot]=max(maxx[tot-1],a[i-1]);
}
flag^=1;
}
}
for (int i=2;i<=tot;i++) ans+=(top[i].first-top[i-1].first-1)*min(top[i].second,top[i-1].second)-(sum[top[i].first-1]-sum[top[i-1].first]);
printf("%d\n",ans);
return 0;
}