CodeForces 442C Artem and Array(贪心)

E - Artem and Array
Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u
Appoint description:  

Description

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 integersai(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.

Sample Input

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

题目大意:给出一个数组,每次操作可以删除一个数,得到这个数左右两个数的最小值的权值(如果左右两侧不全,权值为0),问最大得到多少?
首先,如果是左右两个数均不比中间的数小(有一侧大于,一侧相等也可以),那么可以直接取中间的数,权值加上左右两侧的最小值,这样操作完成后,得到的数组,递增,递减,先增后减,最大的两个数是紧挨着的,一定取不到,能取到的是除去最大的两个数的其他所有的和

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
#define LL __int64
LL p[600000] , top ;
int main()
{
    LL i , x , n , ans ;
    top = -1 ; ans = 0 ;
    scanf("%I64d", &n);
    while(n--)
    {
        scanf("%I64d", &x);
        while( top >= 1 && p[top] <= p[top-1] && p[top] <= x )
        {
            ans += min( p[top-1],x );
            top-- ;
        }
        p[++top] = x ;
    }
    sort(p,p+(top+1));
    for(i = 0 ; i < top-1 ; i++)
        ans += p[i] ;
    printf("%I64d\n", ans);
    return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值