Question: C. appleman and toastmantime limit per Test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output
Appleman and toastman play a game. Initially appleman gives one groupNNumbers 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 integerN(1? ≤?N? ≤? 3 · 105). The second line containsNIntegersA1,A2 ,...,AN(1? ≤?AI? ≤? (106)-the initial group that is given to toastman.
Output
Print a single integer-the largest possible score.
Sample test (s) Input
33 1 5
Output
26
Input
110
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 shocould be given to toastman. when toastman ES group [1], he adds 1 to score and gives the group to appleman (he will throw it out ). when toastman groups ES 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 es [5], he adds 5 to the score and gives the group to appleman (he will throws it out ). when toastman es [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.
Question analysis: the meaning of the question is quite clear. Sort the original array and perform a recursive simulation.
Code:
#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>#include <string>#include <iostream>using namespace std;long long a[300005];int main(){ int n; long long ans; while(scanf("%d",&n)!=EOF) { ans=0; for(int i=1;i<=n;i++) { cin>>a[i]; } sort(a+1,a+n+1); for(int i=1;i<=n;i++) { a[i]+=a[i-1]; } ans=a[n]; for(int i=0;i<=n-2;i++) { ans+=(a[n]-a[i]); } cout<<ans<<endl; }}
Codeforces round #263 (Div. 2) proc