Minimum Cost to Connect Sticks (via extremes, priority-queue idea)

MEDIUM-HARD · C · 3000ms

In the equipment room, Zayan must repeatedly combine bamboo practice sticks (cost = sum of the two combined lengths) until only one remains, and wants to MINIMIZE total combining cost. Given N stick lengths, repeatedly combine any two sticks into one (cost = sum of their lengths, and the new stick replaces both) until one stick remains. Minimize total cost. (Think: is picking the two SHORTEST sticks each time optimal? Prove it or find a counterexample before coding.)

Input

Line1: N. Line2: N integers.

Output

Minimum total cost.

Constraints

1 ≤ N ≤ 10^5

Sample Input

4
2 4 3 1

Sample Output

19
main.c
Loading editor…

Write C, then Run (custom I/O) or Submit (sample tests). ⌘/Ctrl+Enter submits.

Minimum Cost to Connect Sticks (via extremes, priority-queue idea) · DIU ContestHub