单调栈维护
自己体会一下应该问题不大
#include<cstdio>
#include<cstdlib>
#include<algorithm>
using namespace std;
typedef long long ll;
inline char nc()
{
static char buf[100000],*p1=buf,*p2=buf;
if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
return *p1++;
}
inline void read(int &x)
{
char c=nc(),b=1;
for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}
int Stack[250005];
int pnt;
int n,a;
ll ans;
int main()
{
freopen("t.in","r",stdin);
freopen("t.out","w",stdout);
read(n);
for (int i=1;i<=n;i++)
{
read(a);
while (pnt && a>=Stack[pnt])
{
if(pnt-1 && a>=Stack[pnt-1])
ans+=Stack[pnt-1];
else
ans+=a;
pnt--;
}
Stack[++pnt]=a;
}
for (int i=1;i<pnt;i++)
ans+=Stack[i];
printf("%lld\n",ans);
return 0;
}