All problems

Problem 252

Minimum Cost to Connect Ropes

Medium · 20 pts · Array, Greedy, Heap

Problem

You have N ropes with given lengths. Connecting two ropes of lengths a and b costs a + b and produces a single rope of length a + b. Keep connecting until only one rope remains, and find the minimum total cost. Ropes joined early are paid for again in every later join, so the shortest ropes should be joined first. Use a min-heap: repeatedly take the two shortest ropes, join them, add the cost, and put the new rope back. This is the same idea as Huffman coding.

Input

First line: N. Second line: N rope lengths.

Output

Print the minimum total cost.

Constraints

1 <= N <= 100000; 1 <= length <= 10000 (the answer fits in a 64-bit integer)

Example input

4
4 3 2 6

Example output

29

Explanation

With ropes 4 3 2 6: join 2 and 3 for 5 (cost 5), then 4 and 5 for 9 (cost 9), then 6 and 9 for 15 (cost 15). The total cost is 5 + 9 + 15 = 29.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Job Sequencing with Deadlines Next: Two City Scheduling