题目描述
题解
维护栈低到栈顶单调递减的单调栈,每次进栈的时候都要考虑如何合并。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define LL long long
const int INF=2e9;
int n,x,temp,strack[1000005];
LL ans;
int main(){
scanf("%d",&n);
strack[0]=INF;
for (int i=1;i<=n;++i){
scanf("%d",&x);
while (temp&&x>=strack[temp]){
if (x>=strack[temp-1]) ans+=(LL)strack[temp-1],temp--;
else ans+=(LL)x,temp--;
}
strack[++temp]=x;
}
while (temp>1) ans+=(LL)strack[--temp];
printf("%lld\n",ans);
}