problems / 102

Snowball Merging

easy heap greedy 1000 ms · 256 MB

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 a and b.
  • Rolling them together costs a + b units 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.

Example 1

Input

4
1 2 3 4

Output

19

Example 2

Input

1
1000000000

Output

0

Hints · reveal one at a time if you're stuck

Hint 1

Each roll costs the sum of its two masses, so a snowball's mass is paid for once for every roll it takes part in, directly or inside a bigger ball. Which snowballs should be rolled early, and which should be left to the end?

Hint 2

Always roll the two lightest current snowballs, the same greedy merge used for Huffman coding. Keep the current masses in a min-heap, and use a 64-bit total since the answer can be large.

report an issue Prefer your own editor? sooks prep 102 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.