Learn / Greedy

Huffman-style merges

When joining items costs the sum of the two joined, always join the two smallest, using a min heap. The small values then take part in the most joins and the big ones in the fewest. The same idea builds Huffman codes. Cutting problems work the other way round: make the most expensive cuts first, while they cross the fewest pieces.

How to recognise it

  • Items are combined two at a time and each join has a cost.
  • Frequencies decide how long a code should be.
  • Cuts whose cost grows with the number of pieces they cross.

Join the two smallest

heap = all values
while size > 1:
    a = pop; b = pop
    cost += a + b
    push a + b

Think of the joins as a tree: each original value is added once for every join above it, which is its depth. To make the total small, the smallest values should be deepest. Joining the two smallest first puts them deepest. Huffman coding is the same tree, where a symbol's code length is its depth and the total is the number of bits.

Cut the dearest first

A board cut along a line costs its price times the number of pieces it runs across. Each cut in one direction adds a piece for the other direction. So sort both lists from most to least expensive and always make the dearest cut next.

Common mistakes

  • Sorting once and adding from the left, which ignores that a joined pile can be smaller than the next value.
  • Using 32-bit sums for long lists.

Problems

0 of 3 solved

Check yourself

Ropes 4, 3, 2, 6. Least total cost to join them?

Why join the two smallest each time?

In the board-cutting problem, why make expensive cuts first?