本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 1 · 本科一年级
22Greedy Algorithms and Their Proofs
A conference has forty talks to fit in one room, and each talk has fixed hours. Taking the shortest talks first sounds reasonable; so does taking the earliest. One rule always gives the most talks, and it is neither of these. Greedy algorithms build a solution one irrevocable choice at a time; they are fast and short, and they are often wrong. This chapter is about telling the two cases apart, with two kinds of proof, and about one greedy algorithm that many compressed files rely on, from ZIP and gzip archives to PNG and JPEG images.
You already know
A priority queue (Definition 18.1) gives its smallest element in . In a binary tree (Definition 11.3), the depth of a node is the number of edges from the root to it.
22.1 The greedy method
Definition 22.1 (Greedy algorithm)
A greedy algorithm builds a solution by a sequence of choices, each made by a fixed rule that looks only at the current partial solution, and never undone.
The second book met greedy methods on examples; here they need proofs. Backtracking (Chapter 20) tries every choice and undoes the bad ones; a greedy algorithm makes one choice per step and keeps it, which is why it is fast, and why a proof is needed: nothing in the method guarantees that a choice good now is not fatal later.
Method 22.2 (Proving a greedy algorithm optimal)
Two templates.
- Exchange argument: take any optimal solution; show that it can be changed, step by step, into the greedy one without getting worse. The step usually replaces the optimal solution’s first choice by the greedy choice and checks that the result is still valid and no worse.
- Greedy stays ahead: measure the progress of a partial solution, and show by induction that after choices the greedy solution is at least as far as any other solution after choices.
Either proof must use the rule: a proof that would work for any rule proves nothing, since most rules fail.
22.2 Interval scheduling
Definition 22.3 (Interval scheduling, interval partitioning, maximum overlap)
Talks are intervals of time; two talks are compatible if their intervals do not overlap. The interval scheduling problem asks for a largest set of pairwise compatible talks. The interval partitioning problem asks to place all the talks in as few rooms as possible, compatible talks only in one room. The maximum overlap of a set of talks is the largest number of them going on at one moment.
Four rules come to mind: earliest start, shortest, fewest conflicts with the others, and earliest finish. The program applies each, keeping every talk compatible with those already kept, and compares with the optimum found by trying all subsets.
RULES = {
"earliest finish": lambda t, talks: t[1],
"earliest start": lambda t, talks: t[0],
"shortest": lambda t, talks: t[1] - t[0],
"fewest conflicts": lambda t, talks: sum(overlap(t, u) for u in talks),
}
def overlap(t, u):
"""Do the talks [start, end) t and u overlap?"""
return t[0] < u[1] and u[0] < t[1]
def greedy(talks, rule):
"""Take the talks in the rule's order, keeping each one compatible with the kept."""
kept = []
for t in sorted(talks, key=lambda t: RULES[rule](t, talks)):
if all(not overlap(t, u) for u in kept):
kept.append(t)
return sorted(kept)
$ python intervals.py
40 talks, one room: 9 fit, ending at [95, 166, 228, 285, 324, 353, 440, 474, 577]
optimal on 500 random sets of 10 talks:
earliest finish 500
earliest start 398
shortest 446
fewest conflicts 499
A rule that fails once is wrong, however often it succeeds: fewest conflicts fails on one set in five hundred here. Earliest start fails on one long talk that starts first; shortest fails on a short talk overlapping two long compatible ones.
Theorem 22.4 (Earliest finish is optimal)
Taking the talks by increasing finishing time, and keeping each one compatible with those kept, gives a largest set of compatible talks.
Proof. By the exchange argument, by induction on the number of talks. Let be the talk that finishes first, which the greedy keeps, and an optimal set, sorted by finishing time, with first talk . Then , and every other talk of starts after finishes, hence after finishes: is compatible, of the same size, and optimal. The other talks of all start at or after : they form a compatible set of the talks starting at or after , and no larger one exists, or adding to it would beat . After keeping , the greedy discards exactly the talks that start before and runs on the others, where by induction it finds an optimal set. With , it has talks. ∎
With several rooms, every talk must be placed. At a moment when talks are going on, rooms are needed, so the maximum overlap is a lower bound; a greedy assignment reaches it.
def max_overlap(talks):
"""The largest number of talks going on at one moment."""
events = sorted([(s, 1) for s, _ in talks] + [(e, -1) for _, e in talks])
now = best = 0
for _, change in events: # at equal times, ends (-1) come before starts (+1)
now += change
best = max(best, now)
return best
def rooms(talks):
"""Rooms by increasing start: reuse a room whose last talk is over, if any."""
free_at = [] # heap of (end of the room's last talk, room number)
assignment, opened = {}, 0
for talk in sorted(talks):
if free_at and free_at[0][0] <= talk[0]:
_, room = heapq.heappop(free_at) # the room that frees up first
else:
room, opened = opened, opened + 1 # every room is busy: open a new one
assignment[talk] = room
heapq.heappush(free_at, (talk[1], room))
return assignment
40 talks: maximum overlap 9, rooms used 9
room 0: [(25, 95), (123, 166), (206, 325), (364, 440), (442, 474), (539, 597)]
room 1: [(31, 123), (171, 269), (286, 324), (333, 447), (457, 480), (543, 577)]
Proposition 22.5 (Rooms by increasing start)
Assigning the talks by increasing start, each to a room whose last talk is over if there is one, uses exactly as many rooms as the maximum overlap.
Proof. At least that many are needed. Conversely, suppose the algorithm opens room number for a talk starting at . Then each of the rooms has a last talk that started at or before (talks come by increasing start) and is not over at : with the new talk, talks are going on at time , so is at most the maximum overlap. ∎
22.3 Unit tasks with deadlines and penalties
Definition 22.6 (Unit-task scheduling problem)
In the unit-task scheduling problem, tasks each take one slot of time on one machine, in slots ; task has a deadline and a penalty , paid if it ends after slot . The problem asks for an order with the smallest total penalty.
Only the set of tasks done on time matters: they can be run by increasing deadline, the late ones after them in any order. A set is feasible if its tasks can all be on time; minimising the penalty paid means maximising the penalty of a feasible set.
Lemma 22.7 (Feasibility)
A set of tasks is feasible if and only if, for every , at most of its tasks have a deadline at most .
Proof. If more than tasks have a deadline at most , they cannot all fit in the first slots. Conversely, run the tasks by increasing deadline: the task in slot has the -th smallest deadline, and at least tasks have a deadline at most that one, so it is at least . ∎
The greedy rule takes the tasks by decreasing penalty and keeps each one that leaves the set feasible.
def feasible(tasks):
"""Can all these tasks be on time? Iff at most t of them have a deadline <= t."""
deadlines = sorted(d for d, _ in tasks)
return all(d >= i + 1 for i, d in enumerate(deadlines))
def greedy(tasks):
"""On-time tasks: by decreasing penalty, keep a task if the set stays feasible."""
on_time = []
for task in sorted(tasks, key=lambda t: -t[1]):
if feasible(on_time + [task]):
on_time.append(task)
return on_time
$ python penalties.py
slot 1: deadline 2, penalty 45 on time
slot 2: deadline 3, penalty 50 on time
slot 3: deadline 3, penalty 60 on time
slot 4: deadline 4, penalty 15 on time
slot 5: deadline 1, penalty 25 late
slot 6: deadline 2, penalty 35 late
slot 7: deadline 4, penalty 10 late
total penalty 70 - smallest possible 70
greedy optimal on 300 of 300 random sets
Theorem 22.8 (Greedy penalties)
The greedy rule by decreasing penalty gives a feasible set of largest total penalty, so a schedule with the smallest penalty paid.
Proof. First an exchange property: if and are feasible and , some task of not in keeps feasible. Write for the number of tasks of with deadline at most , and let be the largest with ( qualifies). For large , , so for every , and has more tasks than with a deadline after : some has . Adding it to changes only for , where : still feasible by the lemma.
Let be the greedy’s tasks and those of an optimal set, both by decreasing penalty. A subset of a feasible set is feasible, so whenever the greedy rejected a task, adding it to all the tasks it ends with would not be feasible either. If the optimal set had more tasks, the exchange property would give a task that can be added to the greedy’s set, which the greedy would have kept: so . Suppose for some , the first one. With and , some , , keeps feasible, and . The greedy looked at before , when its set was part of , so it would have kept it: then would be one of , which it is not. So for all , and the greedy’s total is at least the optimum. ∎
22.4 Huffman codes
Text stored with a fixed number of bits per character wastes space on the frequent ones. The second book compressed texts by giving short codes to frequent symbols; the question here is the best such code.
Definition 22.9 (Prefix code, code tree, cost)
A prefix code assigns to each symbol a word of bits, its codeword, so that no codeword is the beginning of another. Its code tree is the binary tree whose leaves are the symbols, the codeword of a symbol spelling the path from the root, 0 for left and 1 for right. For frequencies , the cost of the code is , where , the length of the codeword of , is the depth of its leaf: the number of bits of the encoded text.
Without the prefix property, the bits would need separators: with , and , the bits read either t or eh. With it, the decoder walks down the tree and outputs a symbol at each leaf.
Method 22.10 (Huffman’s algorithm)
Start with one tree per symbol, of weight its frequency. While there are two trees or more, remove the two lightest and join them under a new root, of weight the sum of theirs. The last tree is the code tree of a Huffman code.
def huffman_tree(freq):
"""Merge the two lightest trees until one is left. A leaf is a symbol, an inner
node a pair (left, right). Ties go to the tree made first (symbols in order)."""
heap = [(f, i, s) for i, (s, f) in enumerate(sorted(freq.items()))]
heapq.heapify(heap)
made = len(heap)
while len(heap) > 1:
f1, _, t1 = heapq.heappop(heap)
f2, _, t2 = heapq.heappop(heap)
heapq.heappush(heap, (f1 + f2, made, (t1, t2))) # the lighter one on the left
made += 1
return heap[0][2]
def codewords(tree, prefix=""):
"""The codeword of each symbol: 0 for a left branch, 1 for a right one."""
if isinstance(tree, str):
return {tree: prefix or "0"}
left, right = tree
return codewords(left, prefix + "0") | codewords(right, prefix + "1")
The priority queue holds : the number breaks ties by age, so that two runs on the same frequencies build the same tree, which matters to the decoder (Exercise 22.6). With symbols there are merges, each .
On the library’s catalogue, the 80 titles in lower case, one per line:
$ python huffman.py
1437 characters, 24 symbols; fixed-length code: 5 bits each, 7185 bits
'e' 195 101 ' ' 182 100 't' 121 1111
'h' 104 1101 'o' 89 0110 'r' 85 0101
'\n' 79 0100 'a' 72 0010 'n' 71 0001
'd' 55 11101 'l' 53 11100 's' 50 11000
'i' 48 01111 'c' 40 00111 'y' 33 00000
'b' 28 110011 'm' 21 011101 'p' 20 011100
'k' 18 001101 'g' 17 000011 'u' 17 001100
'v' 16 000010 'f' 12 1100101 'w' 11 1100100
Huffman code: 5993 bits, 4.170 bits per character
’\n’ is the end of a line).def decode(bits, tree):
"""Walk down the tree, one bit per step; at a leaf, output its symbol, restart."""
out, node = [], tree
for b in bits:
node = node[int(b)] # 0: left, 1: right
if isinstance(node, str):
out.append(node)
node = tree
assert node is tree, "the bits end inside a codeword"
return "".join(out)
$ python encode_decode.py
'the silent code': 15 characters, 60 bits
111111011011001100001111111001010001111110000111011011101101
'the silent code'
whole catalogue: decoded back exactly
Lemma 22.11 (The two rarest are siblings)
For any frequencies, some optimal code tree has the two least frequent symbols and as sibling leaves at the largest depth.
Proof. In an optimal tree every inner node has two children: an inner node with one child could be replaced by that child, shortening codewords. So a deepest leaf has a sibling, also a leaf; call them and . Exchange with : goes down by and goes up as much, and the cost changes by , since . Exchange with in the same way. The tree is still optimal, and , are sibling leaves at the largest depth. ∎
Lemma 22.12 (Merging keeps optimality)
Replace and by a new symbol of frequency . If is an optimal code tree for the new symbols, the tree obtained by hanging and under the leaf of is optimal for the old ones.
Proof. The leaves , of are one deeper than in , so . Let be an optimal tree for the old symbols with , siblings (Lemma 22.11); replacing them and their parent by a leaf gives a tree for the new symbols with . So is optimal. ∎
Theorem 22.13 (Huffman)
Huffman’s algorithm builds a prefix code of smallest cost.
Proof. By induction on the number of symbols; one symbol needs a tree of one leaf. The first merge joins and , the two lightest, and the rest of the algorithm is Huffman’s algorithm on the symbols with , replaced by : by induction it builds an optimal tree for them, and Lemma 22.12 makes the final tree optimal. ∎
The proof never used the tie rule: any Huffman tree is optimal, though different tie rules give different codewords. The construction was published by Huffman in 1952.
22.5 When greedy is only an approximation
Change for an amount with the fewest coins: the greedy rule gives the largest coin that fits, repeatedly. With euro coins it is optimal; with coins of 1, 3 and 4 it is not.
def greedy_change(amount, coins):
used = []
for c in sorted(coins, reverse=True):
while amount >= c:
amount -= c
used.append(c)
return used
$ python coins.py
coins [1, 2, 5, 10, 20, 50, 100, 200]: greedy worse for 0 amounts up to 300
coins [1, 3, 4]: greedy worse for 74 amounts up to 300
first: 6 = 4 + 1 + 1 by greedy, 2 coins at best
coins [1, 5, 10, 12]: greedy worse for 163 amounts up to 300
first: 15 = 12 + 1 + 1 + 1 by greedy, 2 coins at best
The knapsack of Section 20.5 can be filled greedily by value per unit of weight. That was the optimum of the relaxed problem, where fractions are allowed; for whole items it is an approximation, good on average and bad on some instances.
def greedy(items, capacity):
"""Take items by decreasing value/weight while they fit."""
total = 0
for w, v in sorted(items, key=lambda t: t[1] / t[0], reverse=True):
if w <= capacity:
capacity -= w
total += v
return total
$ python knapsack_greedy.py
1000 random instances of 12 items: greedy optimal in 548, mean ratio 0.9877, worst 0.888
items [(1, 2), (100, 100)], capacity 100: greedy 2, optimum 100
On the last instance, the greedy takes the small item of ratio 2 and has no room left for the item worth 100: its result can be as far from the optimum as one likes. How far a greedy method can be from the optimum, in the worst case, is a subject of the fifth book.
22.6 Exercises
Exercise 22.1 ★
Which talks does the earliest-finish rule keep among , , , , , , , ? Can four talks fit?
Solution
Solution of Exercise 22.1.
By finishing time: kept; overlaps it; kept; and overlap it; kept; and overlap. Three talks. No four fit, since the rule is optimal (Theorem 22.4).
Exercise 22.2 ★
Give the codeword lengths of a Huffman code for six symbols of frequencies 1, 1, 2, 3, 5, 8, and its cost.
Solution
Solution of Exercise 22.2.
Merges: , , , , . Lengths 5, 5, 4, 3, 2, 1 for the frequencies 1, 1, 2, 3, 5, 8; cost .
Exercise 22.3 ★
Decode 111111001101110 with the code tree of the six-symbol figure.
Solution
Solution of Exercise 22.3.
: notes.
Exercise 22.4 ★
Which coins does the greedy rule give for 289 cents with euro coins? For 10 with coins of 1, 3 and 4, and what is the optimum?
Solution
Solution of Exercise 22.4.
: seven coins. For 10 with coins of 1, 3 and 4, the greedy gives , four coins, against .
Exercise 22.5 ★★
This version sorts the talks by start. Explain its result, and say where the exchange argument breaks for it.
def scan(talks, key):
kept = []
for t in sorted(talks, key=key):
if not kept or kept[-1][1] <= t[0]: # starts after the last talk kept ends
kept.append(t)
return kept
by start: [(0, 100)]
by finish: [(10, 30), (35, 55), (60, 80), (85, 99)]
Solution
Solution of Exercise 22.5.
The long talk starts first, is kept, and overlaps all the others: one talk instead of four. The exchange step replaces the optimum’s first talk by the greedy’s; it needs the greedy’s talk to finish no later, and a talk that starts first may finish last, so the rest of the optimum no longer fits after it.
Exercise 22.6 ★★
Sender and receiver build the Huffman tree from the same frequencies, but break ties differently. Explain the output, and give two ways to make decoding safe.
sender's code: {'a': '00', 'b': '01', 'c': '10', 'd': '11'}
receiver's code: {'d': '00', 'c': '01', 'b': '10', 'a': '11'}
'bad' sent as 010011, received as 'cda'
Solution
Solution of Exercise 22.6.
All weights are equal, and the two tie rules merge the symbols in opposite orders: the receiver’s tree is the mirror of the sender’s. The bits of bad read c, d, a with the receiver’s code. Safe ways: fix the tie rule as part of the file format, so that both build the same tree; or send the code itself rather than the frequencies, for instance the codeword lengths of a canonical code (Exercise 22.8).
Exercise 22.7 ★★
A station’s timetable gives each train an arrival and a departure time; a train occupies a platform from its arrival to its departure, both included. Compute the fewest platforms needed, in .
Solution
Solution of Exercise 22.7.
def platforms(trains):
arrivals = sorted(a for a, _ in trains)
departures = sorted(d for _, d in trains)
busy = most = j = 0
for a in arrivals:
while j < len(departures) and departures[j] < a: # left strictly before a
busy -= 1
j += 1
busy += 1
most = max(most, busy)
return most
This is the maximum overlap of closed intervals: walk the arrivals in order, first freeing the platforms of the trains that left strictly before (a train leaving at the very minute another arrives still holds its platform). Sorting costs and the walk . The test compares with the largest number of trains present at each minute.
Exercise 22.8 ★★
Given only the codeword lengths of a prefix code, build the canonical code: symbols sorted by length then by name, each codeword the previous one plus one, followed by zeros when the length grows. Why is it enough for a sender to transmit the lengths?
Solution
Solution of Exercise 22.8.
def canonical(lengths):
"""The codewords, from lengths: symbol -> length (with sum 2^-l <= 1)."""
code, value, previous = {}, 0, 0
for s in sorted(lengths, key=lambda s: (lengths[s], s)):
value <<= lengths[s] - previous # append zeros up to the new length
code[s] = format(value, f"0{lengths[s]}b")
value += 1
previous = lengths[s]
return code
Read as binary numbers, the codewords of one length are consecutive, and the first codeword of a longer length extends, with zeros, the number just after the last shorter codeword: no shorter codeword can be its beginning. The lengths alone determine the code, so the sender transmits small numbers, and both sides build the same codewords; the test checks the lengths and the prefix property on codes built from Huffman lengths.
Exercise 22.9 ★★
Show that the codeword lengths of a prefix code satisfy , with equality when every inner node of the code tree has two children.
Solution
Solution of Exercise 22.9.
Let be the largest length. A codeword of length is the beginning of words of length ; for two codewords these sets are disjoint, otherwise one codeword would begin the other. So . If every inner node has two children, replace two sibling leaves at depth by their parent: , the sum does not change; repeating down to the root alone gives 1.
Exercise 22.10 ★★★
Show that for the coins , with , greedy change uses the fewest coins.
Solution
Solution of Exercise 22.10.
In a way of paying with fewest coins, each coin with appears at most times, since of them could be replaced by one . With for , the sum is less than , so is the quotient of the amount by , and the below are the digits in base of the remainder: there is a single such way of paying. The greedy rule takes as many as fit, then as many as fit in the rest, and so on, which computes exactly this quotient and these digits. The test checks up to 600.
Exercise 22.11 ★★★
Tasks of lengths and deadlines must all be run, one after the other, on one machine; the lateness of a task is its finishing time minus its deadline, if positive. Show that the order by earliest deadline minimises the largest lateness, and test it against all orders.
Solution
Solution of Exercise 22.11.
If a task runs just before a task with , exchange them. The tasks before and after are not moved; finishes earlier; finishes when finished, at time , and its lateness is less than , the lateness of before the exchange. So the largest lateness does not increase. Starting from an optimal order and exchanging such neighbours until none is left reaches the order by deadline (equal deadlines can be put in any order, which does not change the largest lateness) without increasing the largest lateness. exercises/lateness.py checks it against all orders of up to six tasks.
Exercise 22.12 ★★★
Prove Theorem 22.4 again, with the other template: if are the greedy’s talks and those of an optimal set, both by finishing time, then for every .
Solution
Solution of Exercise 22.12.
For , finishes first of all talks. If , then starts at or after , so it is compatible with , which all finish by ; the greedy keeps the first compatible talk in finishing order, so . If the optimum had a talk beyond the greedy’s last , it would start after , be compatible with all the greedy’s talks, and the greedy would have kept a talk after . So both have the same number of talks.
22.7 Problem: Compressing the library catalogue
Problem 22.1
Weekend problem — Compressing the library catalogue
The catalogue is the text of Output 22.4: the 80 titles in lower case, one per line. The problem builds its Huffman code and proves that no prefix code does better.
Part I — A fixed-length code.
- How many characters and how many distinct symbols has the catalogue? Why is the end of line a symbol?
- What is the shortest fixed length of codewords for its symbols?
- How many bits does the fixed-length code take?
- Which symbols are the most and the least frequent?
- Is a fixed-length code a prefix code?
- Show with an example why a code without the prefix property may not be decodable.
Part II — Building the tree.
- Which two symbols does the first merge join, and what is the new weight?
- The second merge has a choice between
gandu, both of frequency 17. Which does the program take, and why? - How many merges are made in all?
- How many trees does the queue hold after merges?
- What is the cost of the algorithm for symbols?
- Why does the tie rule change the codewords but not the cost?
Part III — Lengths, bits, decoding.
- Group the symbols by codeword length.
- Check that .
- Compute the cost and compare with the program.
- How many bits are saved against the fixed-length code, in percent?
- Decode the first eleven bits of Output 22.5 with the table.
- Why does the decoder never need to read ahead?
Part IV — Nothing does better.
- Which two symbols are siblings at the largest depth in the program’s tree? Is this what Lemma 22.11 says?
- Why does an optimal code tree have no inner node with one child?
- In Lemma 22.12, why is ?
- Write the induction that proves Theorem 22.13.
- Coding pairs of characters can take fewer bits than 5993. Why does this not contradict the theorem?
- State the named result, Huffman’s theorem on the catalogue.
Solution
Solution of Problem 22.1.
1. 1437 characters and 24 symbols. The ends of lines separate the titles; without coding them, the catalogue could not be rebuilt.
2. 5 bits: .
3. bits.
4. e (195) and the space (182); w (11) and f (12).
5. Yes: two different words of the same length never begin one another.
6. With , , , the bits are t or eh.
7. w (11) and f (12), into a tree of weight 23.
8. g: the leaves are numbered in the order of the symbols, and g comes before u; the queue compares the numbers when the weights are equal. The second merge joins v (16) and g (17).
9. 23: each merge removes one tree, from 24 down to 1.
10. .
11. merges of three queue operations, each: .
12. The proof of Theorem 22.13 holds for any choice between equal weights: every such choice gives an optimal tree, so all have the same cost, though the trees and their codewords may differ.
13. Length 3: e, space. 4: t, h, o, r, end of line, a, n. 5: d, l, s, i, c, y. 6: b, m, p, k, g, u, v. 7: f, w.
14. .
15. , as printed.
16. bits, 16.6 %.
17. : t, h, e.
18. When the bits read so far form a codeword, no other codeword begins with them: the symbol is decided without looking at the next bit.
19. f and w, codewords and , at depth 7, the largest: the two least frequent symbols, as the lemma allows.
20. The only child could take the place of its parent, which shortens every codeword below by one bit and lowers the cost.
21. and sit one level below where was, and : , the other leaves being unchanged.
22. For 1 symbol, the single leaf is optimal. For symbols, Huffman’s algorithm merges the two lightest , and continues as Huffman’s algorithm on symbols; by induction it builds an optimal tree for them, and Lemma 22.12 makes the final tree optimal.
23. The theorem compares codes that give a codeword to each character. A code for pairs of characters is a code for another alphabet, of pairs, where the theorem applies again.
24. Huffman’s theorem on the catalogue: no prefix code for its 24 symbols encodes the catalogue in fewer than 5993 bits, the cost of the program’s Huffman code, against 7185 bits for the fixed-length code.