Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

The rope connection cost

Suppose you have ropes of lengths 1, 2 and 4, and joining two ropes costs their combined length. If you connect 2 and 4 first (cost 6), then join 1 (cost 7), the total cost is 13. But if you connect 1 and 2 first (cost 3), then the 4 (cost 7), the total is only 10.

Long ropes that get joined early are paid for again and again, so join the short ones first.

Greedy strategy: always pick the two shortest ropes currently available.
Reinserting: the newly made rope must compete with the remaining ropes.
ropes = [4, 3, 2, 6] in a min-heap (smallest first)
2
0
3
1
4
2
6
3
smallestnext
cost
5

Pop the two shortest: 2 and 3. Joining them costs 5.

Move 1 of 4

Why a min-heap fits perfectly

Every turn, you must find and remove the two smallest numbers, and insert one new combined number. Sorting after every combine would be slow, and with many ropes that adds up quickly.

With a min-heap, each turn takes only about log n steps, so the whole job is fast: the heap keeps the shortest ropes at the top for you.

Pop twice: take out the two smallest.
Push the sum: add the cost to the total and put the new rope back.
In code
import heapq

if len(ropes) <= 1:
    return 0
heapq.heapify(ropes)
total = 0
while len(ropes) > 1:
    a = heapq.heappop(ropes)
    b = heapq.heappop(ropes)
    total += a + b
    heapq.heappush(ropes, a + b)
return total