Gym - 101257H card

After Hasan ruined the Worm puzzle, Rula brought a new game to the office, the Card game.

The game has a group of cards, each card has an integer value Vi written on it.

Initially, N cards are placed side by side in a straight line (refer to the picture above). In each turn you will pick two adjacent card sets (a single card is also considered a card set) and merge the cards of the two sets together to form one new set.

After each turn, you will add the maximum card value in each card set to your score. The game is over when no more merges could be performed.

What is the maximum score you can get at the end of the game, given that your initial score is 0?

Input

The first line of input contains a single integer N(2 ≤ N ≤ 105), the number of cards in the game.

The second line contains N space-separated integers, each integer isVi(1 ≤ Vi ≤ 5000), which represents the number written on theith card.

Output

On a single line, print the maximum score you can get.

Example
Input
5
1 2 3 2 1
Output
23
Input
6
7 9 7 5 4 3
Output
108
Note

One of the possible solutions for the first sample is as follows:

  • Initially, each set will contain a single card: {1} {2} {3} {2} {1}.
  • Merge {1} with {2}, the resulting sets are: {1 2} {3} {2} {1}, which will add(2 + 3 + 2 + 1 = 8) to your score.
  • Merge {2} with {1}, the resulting sets are: {1 2} {3} {2 1}, which will add (2 + 3 + 2 = 7) to your score.
  • Merge {1 2} with {3}, the resulting sets a4re: {1 2 3} {2 1}, which will add (3 + 2 = 5) to your score.
  • Merge {1 2 3} with {2 1}, the resulting sets are: {1 2 3 2 1}, which will add3 to your score.

Final score is 8 + 7 + 5 + 3 = 23.


题意:就是一个纸牌游戏,规则根据示例很容易就能看懂

思路:其实就是一个策略问题,只要每次都把所剩的数中的最小的合并掉就可以了,把所有的数排序,从小到大,每次减去一个,然后把剩余的相加到总的结果就是最后的代码了

ac代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    long long x,sum,a[100005];
    while(cin>>x)
    {
        sum=0;
        for(int i=0;i<x;i++)
        {scanf("%lld",&a[i]);
        sum+=a[i];
        }
        sort(a,a+x);
        long long ans=0;
        for(int i=0;i<x;i++)
        {
            ans+=(sum-a[i]);
            sum=sum-a[i];
        }
        cout<<ans<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值