Snowball Merging
A group of children has built n snowballs of various masses. They want to end the afternoon with
a single giant snowball, so they keep combining balls two at a time until only one is left.
Rolling two snowballs together works like this:
- Pick any two of the currently remaining snowballs, with masses
aandb. - Rolling them together costs
a + bunits of effort. - They disappear and are replaced by a single new snowball of mass
a + b, which can be rolled together with any other snowball later on, including one produced by an earlier roll.
The children repeat this until exactly one snowball remains (if there is only one snowball to begin with, they are already done and no rolling happens). Help them choose which snowballs to combine, and in what order, to make the total effort spent over all rolls as small as possible.
Input
The first line contains one integer n (1 ≤ n ≤ 2·10^5), the number of snowballs.
The second line contains n integers m_1, m_2, ..., m_n (1 ≤ m_i ≤ 10^9), the masses of the
snowballs.
Output
Print a single integer: the minimum total effort needed to merge all snowballs into one. The answer can exceed the range of a 32-bit integer, so use a 64-bit integer type.
Notes
In the first example, rolling the two lightest balls together first (masses 1 and 2) costs 3 and produces a ball of mass 3. Rolling the two remaining balls of mass 3 together costs 6 and produces a ball of mass 6. Finally rolling masses 6 and 4 together costs 10. The total effort is 3 + 6 + 10 = 19, which is optimal — always combining the two currently lightest balls never wastes effort.
In the second example there is only one snowball, so nothing needs to be rolled and the answer is 0.