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

  

上一篇:StampedLock主要API实现浅析


下一篇:Delphi国内优秀网站及开源项目