「CF442C」 Artem and Array

题目链接

戳我

\(Solution\)

观察发现如果一个数两边都比他大,删掉他可以保证最优,这个应该是显然的。这个东西用单调栈维护一下,最后剩下的就是个单调递减或单调递增的数列,从小到大排个序取前面\(n-2\)个,\(n\)为数列长度

\(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;
}

转载于:https://www.cnblogs.com/hbxblog/p/11410296.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值