K - Appleman and Toastman
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks:
Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman.
Each time Appleman gets a group consisting of a single number, he throws this group out. Each time Appleman gets a group consisting of more than one number, he splits the group into two non-empty groups (he can do it in any way) and gives each of them to Toastman.
After guys complete all the tasks they look at the score value. What is the maximum possible value of score they can get?
Input
The first line contains a single integer n (1 ≤ n ≤ 3·105). The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 106) — the initial group that is given to Toastman.
Output
Print a single integer — the largest possible score.
Examples
Input
3
3 1 5
Output
26
Input
1
10
Output
10
Note
Consider the following situation in the first example. Initially Toastman gets group [3, 1, 5] and adds 9 to the score, then he give the group to Appleman. Appleman splits group [3, 1, 5] into two groups: [3, 5] and [1]. Both of them should be given to Toastman. When Toastman receives group [1], he adds 1 to score and gives the group to Appleman (he will throw it out). When Toastman receives group [3, 5], he adds 8 to the score and gives the group to Appleman. Appleman splits [3, 5] in the only possible way: [5] and [3]. Then he gives both groups to Toastman. When Toastman receives [5], he adds 5 to the score and gives the group to Appleman (he will throws it out). When Toastman receives [3], he adds 3 to the score and gives the group to Appleman (he will throws it out). Finally Toastman have added 9 + 1 + 8 + 5 + 3 = 26 to the score. This is the optimal sequence of actions.
这个题属于贪心问题,我先大致说一下题意,就是一个人给出一些数,然后对这些数字进行相加,之后再把这些数字给人物二号,然后人物二号在对这些数字进行分组,但是这些数字的数量必须要大于1,如果这些数字的数量等于1,人物二号把这组数字扔掉,直到这些数字没有了就行了。
我的思想:我刚开始想的时候是对半分组,这些刚开始的时候就没有数消失,但是这种是不对的,因为就算刚开始的时候消失的少但是最后的时候就会一下少很多数字,就是相加的次数很少,不如这样,我们每次分组的时候然最小的数字分成一组,其他的数字是一组,这样就可以很多组。
#include <iostream>
#include <algorithm>
using namespace std;
long long a[4000000];
int main()
{
long long n,sum=0,ans=0;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
sum+=a[i];
}
sort(a+1,a+n+1);
int t=0;
for(int i=1;i<=n;i++,t++) //每次减去最小的数字
{
ans=ans+sum;
sum-=a[t];
}
cout<<ans<<endl;
}