codeforces 442C C. Artem and Array(贪心)

题目链接:

C. Artem and Array

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have an adjacent number to the left or right, Artem doesn't get any points.

After the element is removed, the two parts of the array glue together resulting in the new array that Artem continues playing with. Borya wondered what maximum total number of points Artem can get as he plays this game.

Input

The first line contains a single integer n (1 ≤ n ≤ 5·105) — the number of elements in the array. The next line contains n integers ai(1 ≤ ai ≤ 106) — the values of the array elements.

Output

In a single line print a single integer — the maximum number of points Artem can get.

Examples
input
5
3 1 5 2 6
output
11
input
5
1 2 3 4 5
output
6
input
5
1 100 101 100 1
output
102

题意:

给出n个数,每次删去一个数,得到的分数是min(a,b),a和b是这个左右相邻的数,边界上的数不能删去,现在要求怎么样才能得到最大的得分;

思路:

贪心的想,每次如果一个数不小于它相邻的两个数,那么这个数就可以删去,得到的分数就是min(a,b),最后剩下的就是一个倒v形状的或者一半,最高的那两个选不了,再把剩下的相加就好了;

AC代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=5e5+10;
int n,a[maxn],q[maxn];

int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&a[i]);
    LL ans=0;
    q[1]=a[1];int p=1;
    for(int i=2;i<=n;i++)
    {
        while(q[p]<=a[i]&&q[p]<=q[p-1]&&p>1)
        {
            ans=ans+min(q[p-1],a[i]);
            p--;
        }
        q[++p]=a[i];
    }
    sort(q,q+p+1);
    for(int i=1;i<p-1;i++)ans=ans+q[i];
    cout<<ans<<endl;

    return 0;
}

  

转载于:https://www.cnblogs.com/zhangchengc919/p/5942367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值