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?
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.
Print a single integer — the largest possible score.
3 3 1 5
26
1 10
10
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.
————————————————————集训27.2的分割线————————————————————
前言:一开始以为每次都扔掉最小的数不是正解,后来证明了每次扔最小的数就是正解。
思路:如果倒过来看。假设三个数字。把最后一次扔掉当做第一次添加,假设扔掉之前不会单独添加该数。
S = A1
S = A1 + A2
S = A1 + A2 + A3
由此可见,A从大到小排序是最优的。
最后把单独的数字加回来。
代码如下:
/*
ID: j.sure.1
PROG:
LANG: C++
*/
/****************************************/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <string>
#include <climits>
#include <iostream>
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
/****************************************/
const int N = 3e5+5;
int a[N];
bool cmp(int a, int b)
{
return a > b;
}
int main()
{
#ifdef J_Sure
// freopen("000.in", "r", stdin);
// freopen(".out", "w", stdout);
#endif
int n;
scanf("%d", &n);
LL ans = 0;
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
ans += a[i];
}
sort(a, a+n, cmp);
LL tmp = a[0];
for(int i = 1; i < n; i++) {
tmp += a[i];
ans += tmp;
}
printf("%I64d\n", ans);
return 0;
}