单调栈
维护一个单调递减的单调栈,每次把栈顶元素和栈顶的后一个元素合并,直到栈顶的后一个元素大于当前值,然后把栈顶合并到当前值即可。
注意最后要把栈里面的元素做一遍。
代码:
#include<cctype>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 1000005
#define F inline
using namespace std;
typedef long long LL;
int n,tp,a[N],stk[N]; LL ans;
F char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
return l==r?EOF:*l++;
}
F int _read(){
int x=0; char ch=readc();
while (!isdigit(ch)) ch=readc();
while (isdigit(ch)) x=(x<<3)+(x<<1)+(ch^48),ch=readc();
return x;
}
int main(){
n=_read();
for (int i=1;i<=n;i++) a[i]=_read();
stk[++tp]=a[1];
for (int i=2;i<=n;i++){
while (tp>1&&stk[tp-1]<=a[i]) ans+=stk[tp-1],tp--;
if (stk[tp]<=a[i]) ans+=a[i],tp--; stk[++tp]=a[i];
}
while (tp) ans+=stk[tp-1],tp--;
return printf("%lld\n",ans),0;
}