\(Solution\)
He observed that if a number of sides than he was, he could be deleted to ensure optimal, this should be obvious. This stack maintenance stuff monotonous look, what is left is a monotonically increasing or monotonically decreasing sequence, a sequence from small to large to take front \ (n-2 \) a, \ (n-\) number column length
\(Code\)
#include<bits/stdc++.h>
#define int long long
#define rg register
#define file(x) freopen(x".in","r",stdin);freopen(x".out","w",stdout);
using namespace std;
int read(){
int x=0,f=1;char c=getchar();
while(c<'0'||c>'9') f=(c=='-')?-1:1,c=getchar();
while(c>='0'&&c<='9') x=x*10+c-48,c=getchar();
return f*x;
}
const int N=5e5+10;
stack<int> s;
int a[N];
main(){
int n=read(),ans=0,x,y,tot=0;
for(int i=1;i<=n;i++){
a[i]=read();
while(s.size()>=2){
x=s.top(),s.pop(),y=s.top();
if(y>=x&&x<=a[i]) ans+=min(a[i],y);
else {s.push(x);break;}
}
s.push(a[i]);
}
while(!s.empty())
a[++tot]=s.top(),s.pop();
sort(a+1,a+1+tot);
for(int i=1;i<tot-1;i++)
ans+=a[i];
printf("%lld",ans);
return 0;
}