提交时间:2025-09-25 13:26:44
运行 ID: 38262
#include<bits/stdc++.h> using namespace std; int n,a[2000006],ci,ji[2000006],nxt[2000006],pre[2000006]; #define getchar getchar_unlocked inline int read() { int x = 0; bool fl = 0; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') fl = 1; c = getchar(); } while (c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + (c ^ 48); c = getchar(); } return fl ? -x : x; } struct sss{ int l,r,as; bool operator<(const sss x)const{ return x.as<as; } }; priority_queue<sss>q; int main(){ //freopen("legion.in","r",stdin); //freopen("legion.out","w",stdout); scanf("%d",&n); for(int i=1;i<=n;i++){ a[i]=read(); if(i!=1){ pre[i]=i-1; } if(i!=n){ nxt[i]=i+1; } } for(int i=1;i<n;i++){ q.push((sss){i,i+1,max(a[i],a[i+1])}); } long long ans=0,top=n; while(ci<n-1){ sss now=q.top(); if(ji[now.l]!=0 || ji[now.r]!=0 || now.l==0 || now.r==0){ q.pop(); continue; } ans+=now.as; ji[now.l]=1; ji[now.r]=1; top++; a[top]=now.as; nxt[top]=nxt[now.r]; pre[top]=pre[now.l]; nxt[pre[now.l]]=top; pre[nxt[now.r]]=top; ci++; q.pop(); q.push((sss){top,nxt[top],max(a[top],a[nxt[top]])}); q.push((sss){pre[top],top,max(a[top],a[pre[top]])}); } printf("%lld",ans); }