计算机科学 · 第 3 册 · 本科一年级

University Computer Science — Year 1

本书暂未推出简体中文版。现有版本: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 O(log⁡n)O(\log n). 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 ii choices the greedy solution is at least as far as any other solution after ii 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 [s,f)[s, f) 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)
Listing 22.1. Four greedy rules for one room code/bachelor-1/22-greedy-proofs/listings/intervals.py
$ 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
Output 22.1. The conference, and the four rules against the optimum on random sets of talks.

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 gg be the talk that finishes first, which the greedy keeps, and OO an optimal set, sorted by finishing time, with first talk oo. Then f(g)≤f(o)f(g) \leq f(o), and every other talk of OO starts after oo finishes, hence after gg finishes: O′=O−{o}+{g}O' = O - \{o\} + \{g\} is compatible, of the same size, and optimal. The other talks of O′O' all start at or after f(g)f(g): they form a compatible set of the talks starting at or after f(g)f(g), and no larger one exists, or adding gg to it would beat OO. After keeping gg, the greedy discards exactly the talks that start before f(g)f(g) and runs on the others, where by induction it finds an optimal set. With gg, it has ∣O∣|O| talks. ∎

Seven talks, the greedy choice by earliest finish, an optimal set, and the exchange step: the optimum’s first talk A is replaced by B, which finishes earlier, so the rest of the optimum still fits after it.
Seven talks, the greedy choice by earliest finish, an optimal set, and the exchange step: the optimum’s first talk A is replaced by B, which finishes earlier, so the rest of the optimum still fits after it.

With several rooms, every talk must be placed. At a moment when dd talks are going on, dd 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
Listing 22.2. The maximum overlap, and rooms assigned by increasing start code/bachelor-1/22-greedy-proofs/listings/partition_rooms.py
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)]
Output 22.2. The forty talks in nine rooms; the first two rooms shown. Some lines are left out.

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 r+1r + 1 for a talk starting at ss. Then each of the rr rooms has a last talk that started at or before ss (talks come by increasing start) and is not over at ss: with the new talk, r+1r + 1 talks are going on at time ss, so r+1r + 1 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, nn tasks each take one slot of time on one machine, in slots 1,2,…,n1, 2, \dots, n; task ii has a deadline did_i and a penalty pi>0p_i > 0, paid if it ends after slot did_i. 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 tt, at most tt of its tasks have a deadline at most tt.

Proof. If more than tt tasks have a deadline at most tt, they cannot all fit in the first tt slots. Conversely, run the tasks by increasing deadline: the task in slot ii has the ii-th smallest deadline, and at least ii tasks have a deadline at most that one, so it is at least ii. ∎

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
Listing 22.3. The feasibility test and the greedy choice code/bachelor-1/22-greedy-proofs/listings/penalties.py
$ 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
Output 22.3. Seven tasks, scheduled; and the greedy against all subsets.

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 XX and YY are feasible and ∣X∣<∣Y∣|X| < |Y|, some task yy of YY not in XX keeps X+{y}X + \{y\} feasible. Write Nt(S)N_t(S) for the number of tasks of SS with deadline at most tt, and let kk be the largest tt with Nt(Y)≤Nt(X)N_t(Y) \leq N_t(X) (k=0k = 0 qualifies). For large tt, Nt(Y)=∣Y∣>∣X∣N_t(Y) = |Y| > |X|, so Nt(Y)>Nt(X)N_t(Y) > N_t(X) for every t>kt > k, and YY has more tasks than XX with a deadline after kk: some y∈Y−Xy \in Y - X has dy>kd_y > k. Adding it to XX changes NtN_t only for t≥dy>kt \geq d_y > k, where Nt(X)+1≤Nt(Y)≤tN_t(X) + 1 \leq N_t(Y) \leq t: still feasible by the lemma.

Let g1,g2,…g_1, g_2, \dots be the greedy’s tasks and a1,a2,…a_1, a_2, \dots 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 ∣A∣≤∣G∣|A| \leq |G|. Suppose p(ai)>p(gi)p(a_i) > p(g_i) for some ii, the first one. With X={g1,…,gi−1}X = \{g_1, \dots, g_{i-1}\} and Y={a1,…,ai}Y = \{a_1, \dots, a_i\}, some aj∉Xa_j \notin X, j≤ij \leq i, keeps X+{aj}X + \{a_j\} feasible, and p(aj)≥p(ai)>p(gi)p(a_j) \geq p(a_i) > p(g_i). The greedy looked at aja_j before gig_i, when its set was part of XX, so it would have kept it: then aja_j would be one of g1,…,gi−1g_1, \dots, g_{i-1}, which it is not. So p(gi)≥p(ai)p(g_i) \geq p(a_i) for all i≤∣A∣i \leq |A|, 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 fsf_s, the cost of the code is ∑sfsℓs\sum_s f_s \ell_s, where ℓs\ell_s, the length of the codeword of ss, is the depth of its leaf: the number of bits of the encoded text.

Without the prefix property, the bits would need separators: with e=0\mathtt{e} = 0, t=01\mathtt{t} = 01 and h=1\mathtt{h} = 1, the bits 0101 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")
Listing 22.4. Huffman’s algorithm with a priority queue, and the codewords code/bachelor-1/22-greedy-proofs/listings/huffman.py

The priority queue holds (weight,number,tree)(\mathit{weight}, \mathit{number}, \mathit{tree}): 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 nn symbols there are n−1n - 1 merges, each O(log⁡n)O(\log n).

Huffman’s algorithm on six symbols of frequencies 12, 9, 8, 7, 4, 3: the merges, then the code tree, each inner node marked with its weight, each leaf with its symbol, frequency and codeword. The tie between o and the tree of weight 7 goes to o, made first. Cost: 107 bits, against 3 × 43 = 129 with three bits per symbol.
Huffman’s algorithm on six symbols of frequencies 12, 9, 8, 7, 4, 3: the merges, then the code tree, each inner node marked with its weight, each leaf with its symbol, frequency and codeword. The tie between o and the tree of weight 7 goes to o, made first. Cost: 107107 bits, against 3×43=1293 \times 43 = 129 with three bits per symbol.

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
Output 22.4. Frequencies and codewords of the catalogue’s 24 symbols (’\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)
Listing 22.5. Decoding by walking down the tree code/bachelor-1/22-greedy-proofs/listings/encode_decode.py
$ python encode_decode.py
'the silent code': 15 characters, 60 bits
111111011011001100001111111001010001111110000111011011101101
'the silent code'
whole catalogue: decoded back exactly
Output 22.5. The first title, encoded and decoded; and the whole catalogue.

Lemma 22.11 (The two rarest are siblings)

For any frequencies, some optimal code tree has the two least frequent symbols xx and yy 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 aa and bb. Exchange xx with aa: xx goes down by ℓa−ℓx≥0\ell_a - \ell_x \geq 0 and aa goes up as much, and the cost changes by (fx−fa)(ℓa−ℓx)≤0(f_x - f_a)(\ell_a - \ell_x) \leq 0, since fx≤faf_x \leq f_a. Exchange yy with bb in the same way. The tree is still optimal, and xx, yy are sibling leaves at the largest depth. ∎

Lemma 22.12 (Merging keeps optimality)

Replace xx and yy by a new symbol zz of frequency fx+fyf_x + f_y. If T′T' is an optimal code tree for the new symbols, the tree TT obtained by hanging xx and yy under the leaf zz of T′T' is optimal for the old ones.

Proof. The leaves xx, yy of TT are one deeper than zz in T′T', so cost(T)=cost(T′)+fx+fy\mathrm{cost}(T) = \mathrm{cost}(T') + f_x + f_y. Let UU be an optimal tree for the old symbols with xx, yy siblings (Lemma 22.11); replacing them and their parent by a leaf zz gives a tree U′U' for the new symbols with cost(U)=cost(U′)+fx+fy≥cost(T′)+fx+fy=cost(T)\mathrm{cost}(U) = \mathrm{cost}(U') + f_x + f_y \geq \mathrm{cost}(T') + f_x + f_y = \mathrm{cost}(T). So TT 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 xx and yy, the two lightest, and the rest of the algorithm is Huffman’s algorithm on the symbols with xx, yy replaced by zz: by induction it builds an optimal tree T′T' 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
Listing 22.6. Change, largest coin first code/bachelor-1/22-greedy-proofs/listings/coins.py
$ 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
Output 22.6. Greedy change against the fewest coins, for three coin systems (amounts in cents).

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
Listing 22.7. The knapsack by value per unit of weight code/bachelor-1/22-greedy-proofs/listings/knapsack_greedy.py
$ 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
Output 22.7. The greedy knapsack against the optimum, computed by the method of Chapter 23.

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 [2,5)[2, 5), [1,3)[1, 3), [4,7)[4, 7), [6,8)[6, 8), [3,9)[3, 9), [8,10)[8, 10), [7,11)[7, 11), [9,12)[9, 12)? Can four talks fit?

Solution

Solution of Exercise 22.1.

By finishing time: [1,3)[1, 3) kept; [2,5)[2, 5) overlaps it; [4,7)[4, 7) kept; [6,8)[6, 8) and [3,9)[3, 9) overlap it; [8,10)[8, 10) kept; [7,11)[7, 11) and [9,12)[9, 12) 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: 1+1=21 + 1 = 2, 2+2=42 + 2 = 4, 3+4=73 + 4 = 7, 5+7=125 + 7 = 12, 8+12=208 + 12 = 20. Lengths 5, 5, 4, 3, 2, 1 for the frequencies 1, 1, 2, 3, 5, 8; cost 5+5+8+9+10+8=455 + 5 + 8 + 9 + 10 + 8 = 45.

Exercise 22.3 ★

Decode 111111001101110 with the code tree of the six-symbol figure.

Solution

Solution of Exercise 22.3.

1111∣110∣01∣10∣11101111 \mid 110 \mid 01 \mid 10 \mid 1110: 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.

289=200+50+20+10+5+2+2289 = 200 + 50 + 20 + 10 + 5 + 2 + 2: seven coins. For 10 with coins of 1, 3 and 4, the greedy gives 4+4+1+14 + 4 + 1 + 1, four coins, against 4+3+34 + 3 + 3.

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
Listing 22.8. Talks by start time code/bachelor-1/22-greedy-proofs/listings/exo_by_start.py
by start:  [(0, 100)]
by finish: [(10, 30), (35, 55), (60, 80), (85, 99)]
Output 22.8. Five talks, two orders. Some lines are left out.
Solution

Solution of Exercise 22.5.

The long talk [0,100)[0, 100) 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'
Output 22.9. Four symbols of equal frequency. Some lines are left out.
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 01 00 1101\,00\,11 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 O(nlog⁡n)O(n \log n).

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
Platforms for a timetable code/bachelor-1/22-greedy-proofs/exercises/platforms.py

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 O(nlog⁡n)O(n \log n) and the walk O(n)O(n). 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
The canonical code code/bachelor-1/22-greedy-proofs/exercises/canonical.py

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 nn 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 ℓ1,…,ℓn\ell_1, \dots, \ell_n of a prefix code satisfy ∑i2−ℓi≤1\sum_i 2^{-\ell_i} \leq 1, with equality when every inner node of the code tree has two children.

Solution

Solution of Exercise 22.9.

Let LL be the largest length. A codeword of length ℓ\ell is the beginning of 2L−ℓ2^{L - \ell} words of length LL; for two codewords these sets are disjoint, otherwise one codeword would begin the other. So ∑i2L−ℓi≤2L\sum_i 2^{L - \ell_i} \leq 2^L. If every inner node has two children, replace two sibling leaves at depth dd by their parent: 2⋅2−d=2−(d−1)2 \cdot 2^{-d} = 2^{-(d - 1)}, the sum does not change; repeating down to the root alone gives 1.

Exercise 22.10 ★★★

Show that for the coins 1,c,c2,…,ck1, c, c^2, \dots, c^k, with c≥2c \geq 2, greedy change uses the fewest coins.

Solution

Solution of Exercise 22.10.

In a way of paying with fewest coins, each coin cic^i with i<ki < k appears at most c−1c - 1 times, since cc of them could be replaced by one ci+1c^{i+1}. With ni<cn_i < c for i<ki < k, the sum n0+n1c+⋯+nk−1ck−1n_0 + n_1 c + \dots + n_{k-1} c^{k-1} is less than ckc^k, so nkn_k is the quotient of the amount by ckc^k, and the nin_i below are the digits in base cc of the remainder: there is a single such way of paying. The greedy rule takes as many ckc^k as fit, then as many ck−1c^{k-1} as fit in the rest, and so on, which computes exactly this quotient and these digits. The test checks c=2,3,5,10c = 2, 3, 5, 10 up to 600.

Exercise 22.11 ★★★

Tasks of lengths tit_i and deadlines did_i 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 ii runs just before a task jj with dj<did_j < d_i, exchange them. The tasks before and after are not moved; jj finishes earlier; ii finishes when jj finished, at time TT, and its lateness T−diT - d_i is less than T−djT - d_j, the lateness of jj 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 g1,g2,…g_1, g_2, \dots are the greedy’s talks and o1,o2,…o_1, o_2, \dots those of an optimal set, both by finishing time, then f(gi)≤f(oi)f(g_i) \leq f(o_i) for every ii.

Solution

Solution of Exercise 22.12.

For i=1i = 1, g1g_1 finishes first of all talks. If f(gi−1)≤f(oi−1)f(g_{i-1}) \leq f(o_{i-1}), then oio_i starts at or after f(oi−1)≥f(gi−1)f(o_{i-1}) \geq f(g_{i-1}), so it is compatible with g1,…,gi−1g_1, \dots, g_{i-1}, which all finish by f(gi−1)f(g_{i-1}); the greedy keeps the first compatible talk in finishing order, so f(gi)≤f(oi)f(g_i) \leq f(o_i). If the optimum had a talk ok+1o_{k+1} beyond the greedy’s last gkg_k, it would start after f(ok)≥f(gk)f(o_k) \geq f(g_k), be compatible with all the greedy’s talks, and the greedy would have kept a talk after gkg_k. 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.

  1. How many characters and how many distinct symbols has the catalogue? Why is the end of line a symbol?
  2. What is the shortest fixed length of codewords for its symbols?
  3. How many bits does the fixed-length code take?
  4. Which symbols are the most and the least frequent?
  5. Is a fixed-length code a prefix code?
  6. Show with an example why a code without the prefix property may not be decodable.

Part II — Building the tree.

  1. Which two symbols does the first merge join, and what is the new weight?
  2. The second merge has a choice between g and u, both of frequency 17. Which does the program take, and why?
  3. How many merges are made in all?
  4. How many trees does the queue hold after kk merges?
  5. What is the cost of the algorithm for nn symbols?
  6. Why does the tie rule change the codewords but not the cost?

Part III — Lengths, bits, decoding.

  1. Group the symbols by codeword length.
  2. Check that ∑s2−ℓs=1\sum_s 2^{-\ell_s} = 1.
  3. Compute the cost ∑sfsℓs\sum_s f_s \ell_s and compare with the program.
  4. How many bits are saved against the fixed-length code, in percent?
  5. Decode the first eleven bits of Output 22.5 with the table.
  6. Why does the decoder never need to read ahead?

Part IV — Nothing does better.

  1. Which two symbols are siblings at the largest depth in the program’s tree? Is this what Lemma 22.11 says?
  2. Why does an optimal code tree have no inner node with one child?
  3. In Lemma 22.12, why is cost(T)=cost(T′)+fx+fy\mathrm{cost}(T) = \mathrm{cost}(T') + f_x + f_y?
  4. Write the induction that proves Theorem 22.13.
  5. Coding pairs of characters can take fewer bits than 5993. Why does this not contradict the theorem?
  6. 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: 24=16<24≤32=252^4 = 16 < 24 \leq 32 = 2^5.

3. 5×1437=71855 \times 1437 = 7185 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 e=0\mathtt{e} = 0, t=01\mathtt{t} = 01, h=1\mathtt{h} = 1, the bits 0101 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. 24−k24 - k.

11. n−1n - 1 merges of three queue operations, O(log⁡n)O(\log n) each: O(nlog⁡n)O(n \log n).

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. 28+716+632+764+2128=32+56+24+14+2128=1\frac{2}{8} + \frac{7}{16} + \frac{6}{32} + \frac{7}{64} + \frac{2}{128} = \frac{32 + 56 + 24 + 14 + 2}{128} = 1.

15. 3⋅377+4⋅621+5⋅279+6⋅137+7⋅23=1131+2484+1395+822+161=59933 \cdot 377 + 4 \cdot 621 + 5 \cdot 279 + 6 \cdot 137 + 7 \cdot 23 = 1131 + 2484 + 1395 + 822 + 161 = 5993, as printed.

16. 7185−5993=11927185 - 5993 = 1192 bits, 16.6 %.

17. 1111∣1101∣1011111 \mid 1101 \mid 101: 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 11001011100101 and 11001001100100, 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. xx and yy sit one level below where zz was, and fz=fx+fyf_z = f_x + f_y: fx(ℓz+1)+fy(ℓz+1)=fzℓz+fx+fyf_x(\ell_z + 1) + f_y(\ell_z + 1) = f_z \ell_z + f_x + f_y, the other leaves being unchanged.

22. For 1 symbol, the single leaf is optimal. For n+1n + 1 symbols, Huffman’s algorithm merges the two lightest xx, yy and continues as Huffman’s algorithm on nn symbols; by induction it builds an optimal tree T′T' 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.

本章定义的术语

在术语表中查看全部 1050 个术语