#K14341. Minimum Cost to Tie Ropes
Minimum Cost to Tie Ropes
Minimum Cost to Tie Ropes
You are given n ropes with different lengths. Your task is to tie all the ropes into one single rope. The cost to tie two ropes is equal to the sum of their lengths. Your goal is to compute the minimum cost required to tie all the ropes together.
At each step, choose the two smallest ropes to tie together. The process can be mathematically described as follows: if you choose two ropes with lengths a and b, the cost of this operation is $$a+b$$, and the new rope has length $$a+b$$. Repeat this process until only one rope remains. This greedy strategy ensures the minimum total cost.
inputFormat
The first line contains an integer n (0 ≤ n ≤ 105), the number of ropes. The second line contains n space-separated integers representing the lengths of the ropes. If n is 0, the second line may be omitted.
outputFormat
Output a single integer, the minimum total cost to tie all the ropes into one rope. If there is only one rope or no rope at all, print 0
.
4
8 4 6 12
58