计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本:English。

High School Computer Science · 10–12 年级

18Greedy Algorithms

A shopkeeper owes 8787 in change and has coins of 11, 22, 55, 1010, 2020 and 5050. Without thinking she hands over the largest coin that fits, 5050, then again the largest that fits what is left, 2020, then 1010, 55, 22: five coins, and no way of giving fewer. Her rule never looks back and never looks ahead, and here it is the best possible.

Rules of this kind are called greedy. They are fast and easy to write, and they are often right, but not always: with other coins the same shopkeeper gives one coin too many. This chapter writes greedy rules for three problems, proves when they are right, and lets a program find where they go wrong.

You already know

sorted(t, key=f) sorts by the values of f (chapter 7). The cost of an algorithm counts its elementary operations (chapter 17); an invariant is kept by each turn of a loop (chapter 16).

18.1 Optimisation problems

Definition 18.1 (Optimisation problem, objective, optimal solution)

An optimisation problem asks, among the feasible solutions of a problem, for one that makes a number as small or as large as possible. That number is the objective. A feasible solution with the best possible objective is an optimal solution.

For change, a feasible solution is a set of coins that adds up to the amount, and the objective is the number of coins, to be made as small as possible. On a small amount, a program can try every combination and keep the best. That is slow, but surely right, and it serves as a reference.

"""The fewest coins by trying every combination: slow, but surely right."""
from change_greedy import greedy_change


def fewest(amount, coins):
    """Return (fewest coins, combinations tried). coins sorted, coins[0] == 1."""
    if len(coins) == 1:
        return amount, 1                  # only coins of 1 left
    *smaller, c = coins
    best, tried = None, 0
    for k in range(amount // c + 1):      # k coins of the largest value, then the rest
        n, t = fewest(amount - k * c, smaller)
        tried += t
        if best is None or k + n < best:
            best = k + n
    return best, tried


if __name__ == "__main__":
    print("20 with 1, 2, 5:", fewest(20, [1, 2, 5]))
    coins = [1, 2, 5, 10, 20, 50]
    limit = coins[-1] + coins[-2]         # 70: the theorem says this is far enough
    bad = [a for a in range(1, limit)
           if len(greedy_change(a, coins)) != fewest(a, coins)[0]]
    print(f"amounts below {limit} where greedy is not optimal: {bad}")
Listing 18.1. The fewest coins, by trying every combination. code/grade-11/07-greedy-algorithms/listings/change_exhaustive.py
$ python change_exhaustive.py
20 with 1, 2, 5: (4, 29)
amounts below 70 where greedy is not optimal: []
Output 18.1. 2020 needs 44 coins of 11, 22 and 55, found among 2929 combinations; with six coins, greedy matches the fewest on every amount checked.

18.2 The greedy choice

Definition 18.2 (Greedy algorithm)

A greedy algorithm builds a solution one piece at a time, each time taking the piece that looks best at that moment, by a fixed rule, and never going back on a choice.

Method 18.3 (Designing a greedy algorithm)

  1. Choose the rule: the order in which candidates are looked at, often a sort by a well-chosen key.
  2. Take each candidate that keeps the solution feasible.
  3. Prove that the result is optimal, often by exchange: take any optimal solution, and change it, step by step, into the greedy one without making it worse.
  4. If there is no proof, look for a counter-example with a program that compares greedy with an exhaustive search on small inputs.
def greedy_change(amount, coins):
    """Take the largest coin that fits, again and again. coins must contain 1."""
    given = []
    for c in sorted(coins, reverse=True):
        while c <= amount:
            given.append(c)
            amount -= c
    return given


if __name__ == "__main__":
    COINS = [1, 2, 5, 10, 20, 50]
    for amount in [87, 43, 9]:
        change = greedy_change(amount, COINS)
        print(f"{amount}: {change} -> {len(change)} coins")
Listing 18.2. Greedy change: the largest coin that fits, again and again. code/grade-11/07-greedy-algorithms/listings/change_greedy.py
$ python change_greedy.py
87: [50, 20, 10, 5, 2] -> 5 coins
43: [20, 20, 2, 1] -> 4 coins
9: [5, 2, 2] -> 3 coins
Output 18.2. Three amounts with the coins 11, 22, 55, 1010, 2020, 5050.

With the coins 11, 22, 55 an exchange argument proves greedy right. Take a way of paying with the fewest coins. It uses at most one coin of 11, since two could become one 22; at most two coins of 22, since three could become a 55 and a 11; and never two 22 with a 11, which could become a 55. So the coins of 11 and 22 add up to at most 44, and every 55 that fits is used, exactly as greedy does; what remains, 00 to 44, has only one way with these rules: 00, 11, 22, 2+12 + 1, 2+22 + 2, again greedy’s way. Greedy and an optimal solution are the same.

For six coins a full case argument is long. A theorem does the work instead.

Theorem 18.4 (Kozen and Zaks)

Let a system of coins have the values 1=c1<c2<⋯<cm1 = c_1 < c_2 < \dots < c_m, with m≥3m \ge 3. If greedy change gives more coins than necessary for some amount, then it does so already for some amount xx with c3+1<x<cm+cm−1c_3 + 1 < x < c_m + c_{m-1}.

Proof. Admitted at this level. ∎

For 11, 22, 55, 1010, 2020, 5050, it is enough to check every amount below 50+20=7050 + 20 = 70, which the output above did: no failure there, so none anywhere. A system for which greedy change is always optimal has a name.

Definition 18.5 (Canonical coin system)

A coin system is canonical if, for every amount, greedy change uses the fewest coins possible.

18.3 Choosing activities

One room, twelve requests, each a start and an end hour; two bookings that overlap cannot both be kept. The goal is to keep as many as possible. Several greedy rules come to mind: shortest first, earliest start first, earliest end first. Only the last is always right.

"""One room, many requests: keep as many bookings as possible, earliest end first."""
import random

rng = random.Random(11)
requests = []
for name in "ABCDEFGHIJKL":
    start = rng.randint(8, 18)
    requests.append((name, start, start + rng.randint(1, 3)))   # hours, end excluded


def earliest_end_first(requests):
    chosen, free_from = [], 0
    for name, start, end in sorted(requests, key=lambda r: r[2]):
        if start >= free_from:            # does not overlap the last one kept
            chosen.append((name, start, end))
            free_from = end
    return chosen


for name, start, end in sorted(requests, key=lambda r: r[2]):
    print(f"{name}: {start:2}h-{end:2}h")
print("kept:", " ".join(name for name, _, _ in earliest_end_first(requests)))
Listing 18.3. Earliest end first: keep a request when it starts after the last one kept ends. code/grade-11/07-greedy-algorithms/listings/activities.py
$ python activities.py
G: 10h-11h
I: 10h-11h
D: 11h-12h
B: 15h-17h
H: 15h-17h
A: 15h-18h
E: 16h-18h
C: 16h-19h
J: 16h-19h
K: 18h-19h
L: 17h-19h
F: 18h-21h
kept: G D B K
Output 18.3. The requests sorted by end hour, and the four kept.
The twelve requests, from the run, in order of end hour. In blue, the four that earliest end first keeps: each starts after the previous blue one ends.
The twelve requests, from the run, in order of end hour. In blue, the four that earliest end first keeps: each starts after the previous blue one ends.

Why is it optimal? Let g1,g2,…g_1, g_2, \dots be the bookings greedy keeps, in order, and o1,o2,…o_1, o_2, \dots those of an optimal choice, in order. Greedy “stays ahead”: g1g_1 ends no later than o1o_1, since greedy took the request that ends first. If gkg_k ends no later than oko_k, then ok+1o_{k+1}, which starts after oko_k ends, starts after gkg_k ends too; so it was still available to greedy, which took a request ending no later, and gk+1g_{k+1} ends no later than ok+1o_{k+1}. Greedy can therefore never run out before the optimal choice does: it keeps at least as many bookings.

Greedy stays ahead. Each g_k ends no later than o_k, so o_k+1 was still free for greedy, and replacing o_k by g_k in the optimal choice keeps it feasible.
Greedy stays ahead. Each gkg_k ends no later than oko_k, so ok+1o_{k+1} was still free for greedy, and replacing oko_k by gkg_k in the optimal choice keeps it feasible.

18.4 Filling a knapsack

A trader’s sack holds 1515 kg. Goods can be cut: half a sack of rice is worth half its price. The greedy rule takes the goods in order of value per kilogram, as much as fits.

"""A sack of 15 kg, goods that can be cut: take the best value per kilogram first."""
GOODS = [("tea", 4, 60), ("rice", 10, 40), ("spices", 2, 50),
         ("coffee", 6, 72), ("flour", 8, 16)]          # name, kg, value


def fill(goods, capacity):
    load, value = [], 0
    for name, kg, worth in sorted(goods, key=lambda g: g[2] / g[1], reverse=True):
        take = min(kg, capacity)          # all of it, or what still fits
        if take == 0:
            break
        load.append((name, take))
        value += worth * take / kg
        capacity -= take
    return load, value


load, value = fill(GOODS, 15)
for name, kg in load:
    print(f"{name:7} {kg} kg")
print("value:", value)
Listing 18.4. The fractional knapsack: the best value per kilogram first. code/grade-11/07-greedy-algorithms/listings/knapsack_fractional.py
$ python knapsack_fractional.py
spices  2 kg
tea     4 kg
coffee  6 kg
rice    3 kg
value: 194.0
Output 18.4. Three goods whole, then 33 kg of rice fill the sack.
The goods as bars, widths in kilograms, heights in value per kilogram, best first. The sack takes everything left of the line; the value is the blue area, 194.
The goods as bars, widths in kilograms, heights in value per kilogram, best first. The sack takes everything left of the line; the value is the blue area, 194194.

Here greedy is optimal: any kilogram in the sack that is not among the best ones could be swapped for a better one left out, which raises the value. Now suppose the objects cannot be cut: a lamp is taken whole or not at all.

"""Whole objects only: the best value per kilogram first is no longer optimal."""
from itertools import combinations

OBJECTS = [("A", 6, 30), ("B", 5, 20), ("C", 5, 20)]   # name, kg, value
CAPACITY = 10

load, kg_used = [], 0
for name, kg, _ in sorted(OBJECTS, key=lambda o: o[2] / o[1], reverse=True):
    if kg_used + kg <= CAPACITY:
        load.append(name)
        kg_used += kg
print("greedy keeps", load, "value", sum(o[2] for o in OBJECTS if o[0] in load))

best = max((sum(o[2] for o in subset), [o[0] for o in subset])
           for r in range(len(OBJECTS) + 1)
           for subset in combinations(OBJECTS, r)
           if sum(o[1] for o in subset) <= CAPACITY)
print("every subset tried: best", best[1], "value", best[0])
Listing 18.5. Whole objects: the same rule, and every subset as a reference. code/grade-11/07-greedy-algorithms/listings/knapsack_01_greedy_fails.py
$ python knapsack_01_greedy_fails.py
greedy keeps ['A'] value 30
every subset tried: best ['B', 'C'] value 40
Output 18.5. The densest object takes 66 kg of the 1010 and leaves room for nothing else.

No greedy rule is known to solve the knapsack with whole objects; the grade-12 chapter on dynamic programming solves it exactly by a different method.

18.5 When greedy fails

With coins of 11, 33 and 44, greedy pays 66 as 4+1+14 + 1 + 1, three coins, while 3+33 + 3 needs two. The program below looks, among all systems of three coins up to 88, for those that are not canonical, and for the first amount each gets wrong; the theorem says to look only below the sum of the two largest coins.

"""Systems of three coins 1 < a < b <= 8 where greedy change can go wrong."""
from change_exhaustive import fewest
from change_greedy import greedy_change

for b in range(3, 9):
    for a in range(2, b):
        coins = [1, a, b]
        bad = [m for m in range(1, a + b)          # below the two largest added
               if len(greedy_change(m, coins)) > fewest(m, coins)[0]]
        if bad:
            m = bad[0]
            print(f"coins {coins}: first failure at {m}:",
                  f"greedy {greedy_change(m, coins)}, fewest {fewest(m, coins)[0]}")
Listing 18.6. Every system of three coins up to 88 where greedy fails. code/grade-11/07-greedy-algorithms/listings/smallest_counterexample.py
$ python smallest_counterexample.py
coins [1, 3, 4]: first failure at 6: greedy [4, 1, 1], fewest 2
coins [1, 4, 5]: first failure at 8: greedy [5, 1, 1, 1], fewest 2
coins [1, 4, 6]: first failure at 8: greedy [6, 1, 1], fewest 2
coins [1, 5, 6]: first failure at 10: greedy [6, 1, 1, 1, 1], fewest 2
coins [1, 5, 7]: first failure at 10: greedy [7, 1, 1, 1], fewest 2
coins [1, 6, 7]: first failure at 12: greedy [7, 1, 1, 1, 1, 1], fewest 2
coins [1, 5, 8]: first failure at 10: greedy [8, 1, 1], fewest 2
coins [1, 6, 8]: first failure at 12: greedy [8, 1, 1, 1, 1], fewest 2
coins [1, 7, 8]: first failure at 14: greedy [8, 1, 1, 1, 1, 1, 1], fewest 2
Output 18.6. The smallest system that fails is 11, 33, 44, first at 66.
The amount 6 with coins 1, 3, 4. Taking 4 first leaves 2, which only coins of 1 can pay.
The amount 66 with coins 11, 33, 44. Taking 44 first leaves 22, which only coins of 11 can pay.

18.6 Exercises

Exercise 18.1 ★

Give greedy change for 8787 with coins 11, 22, 55, 1010, 2020, 5050, without the program.

Solution

Solution of Exercise 18.1.

5050 leaves 3737; 2020 leaves 1717; 1010 leaves 77; 55 leaves 22; 22 leaves 00: five coins, 50+20+10+5+250 + 20 + 10 + 5 + 2.

Exercise 18.2 ★

With coins 11, 33, 44, how many coins does greedy give for 66? How many are needed?

Solution

Solution of Exercise 18.2.

Greedy gives 4+1+14 + 1 + 1, three coins; 3+33 + 3 needs two.

Exercise 18.3 ★

Four requests: P from 88h to 1212h, S from 1111h to 1313h, Q from 1212h to 1616h, R from 1313h to 1414h. Which does earliest end first keep?

Solution

Solution of Exercise 18.3.

By end hour: P (1212h), S (1313h), R (1414h), Q (1616h). P is kept; S starts at 1111h, before 1212h: no; R starts at 1313h: kept; Q starts at 1212h, before 1414h: no. P and R, two bookings, as many as possible.

Exercise 18.4 ★

With the goods of the chapter and a sack of 88 kg, what does the fractional greedy take, and for what value?

Solution

Solution of Exercise 18.4.

Spices (22 kg, 5050), tea (44 kg, 6060), then 22 of the 66 kg of coffee, worth 72×2/6=2472 \times 2/6 = 24: in all 134134.

Exercise 18.5 ★

Write greedy_change(amount, coins) with divmod, one division per coin value.

Solution

Solution of Exercise 18.5.

def greedy_change(amount, coins):

given = []

for c in sorted(coins, reverse=True):

k, amount = divmod(amount, c)

given += [c] * k

return given

divmod(a, c) gives the number of coins c that fit and what is left, in one step.

Exercise 18.6 ★★

A student sorts the requests by start time instead of end time. Find four requests on which this keeps one booking when three are possible.

Solution

Solution of Exercise 18.6.

L from 88h to 2020h, x from 99h to 1010h, y from 1010h to 1111h, z from 1111h to 1212h. By start, L comes first and is kept; it overlaps all the others. Earliest end first keeps x, y and z.

Exercise 18.7 ★★

Write max_activities(requests), each request being a triple (name, start, end), that returns the names kept by earliest end first.

Solution

Solution of Exercise 18.7.

def max_activities(requests):

chosen, free_from = [], 0

for name, start, end in sorted(requests, key=lambda r: r[2]):

if start >= free_from:

chosen.append(name)

free_from = end

return chosen

The tests compare its count with the best found by trying every subset, on 200200 random sets of requests. (The 0 start assumes hours are not negative.)

Exercise 18.8 ★★

How many combinations does fewest(20, [1, 2, 5]) try? Count them by hand, by the number of coins of 55, then of 22.

Solution

Solution of Exercise 18.8.

With kk coins of 55, from 00 to 44, the rest 20−5k20 - 5k is paid with 11 and 22, trying every number of coins of 22: 1111, 88, 66, 33 and 11 ways for k=0k = 0 to 44. In all 2929, as printed.

Exercise 18.9 ★★

With a sack of 1010 kg, compare the fractional greedy by value per kilogram with a greedy that takes the most valuable goods first. Which is better here, and why?

Solution

Solution of Exercise 18.9.

By value per kilogram: spices, tea, and 44 kg of coffee, 50+60+48=15850 + 60 + 48 = 158. By value: coffee (7272, 66 kg) and tea (6060, 44 kg), 132132. Per kilogram is better: the sack’s limit is in kilograms, and the spices, worth less in all, give the most for each kilogram they use.

Exercise 18.10 ★★

Objects that cannot be cut: X of 55 kg worth 4040, Y and Z of 44 kg worth 2828 each; the sack holds 88 kg. What does greedy by value per kilogram keep, and what is optimal?

Solution

Solution of Exercise 18.10.

Values per kilogram: X 88, Y and Z 77. Greedy keeps X (55 kg), and then neither Y nor Z fits: value 4040. Y and Z together weigh 88 kg and are worth 5656, which is optimal.

Exercise 18.11 ★★

Write is_canonical_upto(coins, m) that compares greedy with fewest on every amount from 11 to mm. With the theorem, which mm makes it a full test?

Solution

Solution of Exercise 18.11.

def is_canonical_upto(coins, m):

return all(len(greedy_change(a, coins)) == fewest(a, sorted(coins))[0]

for a in range(1, m + 1))

By the theorem, m=cm+cm−1−1m = c_m + c_{m-1} - 1, the largest coin plus the next one, minus one, is enough: if no amount up to it fails, none fails at all.

Exercise 18.12 ★★★

Write out in full the proof that earliest end first keeps as many bookings as possible, with the “stays ahead” statement as an invariant of its loop.

Solution

Solution of Exercise 18.12.

Let the requests be sorted by end hour, and let o1,o2,…,opo_1, o_2, \dots, o_p be an optimal choice, in order of time. Invariant of the loop: after greedy has kept g1,…,gkg_1, \dots, g_k, with k≤pk \le p, each gig_i ends no later than oio_i. It holds for k=0k = 0. When greedy has g1,…,gkg_1, \dots, g_k and k<pk < p, the request ok+1o_{k+1} starts after oko_k ends, hence after gkg_k ends: it is compatible with what greedy kept, and greedy, scanning by end hour, keeps a request no later than ok+1o_{k+1} in that order, so its gk+1g_{k+1} ends no later than ok+1o_{k+1}. The invariant is kept as long as k<pk < p, so greedy keeps at least pp requests, and therefore exactly pp, the most possible. The loop is a for over the sorted list and stops.

Exercise 18.13 ★★★

Prove that greedy change is optimal for the coins 11, 22, 55 by treating the amounts left after the coins of 55: 00, 11, 22, 33 and 44.

Solution

Solution of Exercise 18.13.

Take a way of paying an amount with the fewest coins: ff coins of 55, tt of 22, uu of 11. Then u≤1u \le 1, since 1+11 + 1 could become 22; t≤2t \le 2, since 2+2+22 + 2 + 2 could become 5+15 + 1; and not t=2t = 2 with u=1u = 1, since 2+2+12 + 2 + 1 could become 55. So 2t+u2t + u is one of 00, 11, 22, 2+1=32 + 1 = 3, 2+2=42 + 2 = 4: it is less than 55, ff is the number of fives that fit, and 2t+u2t + u is the remainder. Each remainder from 00 to 44 has exactly one such way, and it is greedy’s: greedy also takes every five that fits, then a 22 while it fits, then a 11.

Exercise 18.14 ★★★

All the requests must now be kept, in as few rooms as possible. Taking the requests by start time, give each the first room free at its start, opening a new room if none is. Write rooms_needed(requests) and check that it equals the largest number of requests going on at the same hour.

Solution

Solution of Exercise 18.14.

def rooms_needed(requests):

rooms = []

for _, start, end in sorted(requests, key=lambda r: r[1]):

for i, free in enumerate(rooms):

if free <= start:

rooms[i] = end

break

else:

rooms.append(end)

return len(rooms)

rooms[i] is the hour at which room i becomes free; the else of a for runs when the loop ended without break. A new room is opened only when every room is busy at that start: at that hour, as many requests as rooms, plus the new one, are going on, so no plan can use fewer rooms. The tests check the equality on 200200 random sets.

Exercise 18.15 ★★★

Find three requests on which “shortest first” keeps fewer bookings than possible.

Solution

Solution of Exercise 18.15.

P from 88h to 1212h, S from 1111h to 1313h, Q from 1212h to 1616h. Shortest first keeps S (22 h), which overlaps P and Q: one booking. P and Q together make two.

18.7 Problem: The Coins of Brenmoor

Problem 18.1

Weekend problem — the amounts greedy gets wrong

The town of Brenmoor, invented for this problem, mints coins of 11, 22, 55, 1212, 2525 and 4040. Its shopkeepers give change greedily. The program compares greedy with the exhaustive search on every amount up to 100100, then tries every way of changing one coin.

"""The weekend problem: is greedy change right with the coins of Brenmoor?"""
from change_exhaustive import fewest
from change_greedy import greedy_change

BRENMOOR = [1, 2, 5, 12, 25, 40]


def failures(coins, upto):
    return [a for a in range(1, upto + 1)
            if len(greedy_change(a, coins)) > fewest(a, coins)[0]]


bad = failures(BRENMOOR, 100)
a = bad[0]
print("smallest failure:", a, "greedy", greedy_change(a, BRENMOOR),
      "fewest", fewest(a, BRENMOOR)[0])
print(len(bad), "failures up to 100:", bad)
print("fewest coins tried for 100:", fewest(100, BRENMOOR)[1], "combinations")
# Part IV: change one coin (not the 1) and check below the two largest added
for i in range(1, len(BRENMOOR)):
    for new in range(2, 50):
        coins = sorted(set(BRENMOOR[:i] + [new] + BRENMOOR[i + 1:]))
        if len(coins) == len(BRENMOOR) and not failures(coins, coins[-1] + coins[-2]):
            print(f"replace {BRENMOOR[i]} by {new}: {coins} never fails")
Listing 18.7. Greedy against the fewest coins in Brenmoor, and the systems one coin away. code/grade-11/07-greedy-algorithms/listings/brenmoor.py
$ python brenmoor.py
smallest failure: 36 greedy [25, 5, 5, 1] fewest 3
17 failures up to 100: [36, 49, 50, 51, 55, 60, 61, 62, 63, 74, 75, 76, 89, 90, 91, 95, 100]
fewest coins tried for 100: 3687 combinations
replace 12 by 10: [1, 2, 5, 10, 25, 40] never fails
replace 25 by 3: [1, 2, 3, 5, 12, 40] never fails
replace 25 by 19: [1, 2, 5, 12, 19, 40] never fails
replace 25 by 26: [1, 2, 5, 12, 26, 40] never fails
Output 18.7. The failures, and four ways to remove them all by changing one coin.

Part I — The coins.

  1. Give greedy change for 2424, 3030 and 3737.
  2. Why must a coin system contain a coin of 11 for greedy to pay every amount?
  3. By the theorem, below which amount must a failure appear, if there is one?
  4. Why does the program still check up to 100100?

Part II — Greedy against the fewest.

  1. Give greedy change for 3636, and a way with fewer coins.
  2. By the theorem’s lower bound, which amounts cannot be the first failure? Which amounts did the program have to examine before finding 3636?
  3. For 4949 and 5050, give greedy’s change and a better one.
  4. The exhaustive search tries 36873687 combinations for 100100. Why does greedy need only a few steps?
  5. Is the system canonical?

Part III — The failures.

  1. What do 3636, 6161 and 7676 have in common in their best change?
  2. For 6060, 6161, 6262 and 6363, give greedy’s change and a way with fewer coins.
  3. How many coins too many does greedy give for 100100? Find a way with only four.
  4. How many of the amounts 11 to 100100 fail?

Part IV — Changing one coin.

  1. Replacing 1212 by 1010 gives a canonical system. Up to which amount did the program have to check, and why is that enough?
  2. Check by hand that 3636 no longer fails with 11, 22, 55, 1010, 2525, 4040.
  3. Replacing 2525 by 2626 also works. Check 3636 and 5050 in that system.
  4. Why does the program skip replacements that give a coin already in the system?
  5. Brenmoor prefers to keep its 1212 and its 4040. Which replacements allow it?
  6. Name an advantage for the town of a canonical system.
  7. State the result: the smallest amount greedy gets wrong in Brenmoor, and how many amounts up to 100100 it gets wrong.
Solution

Solution of Problem 18.1.

1. 24=12+1224 = 12 + 12; 30=25+530 = 25 + 5; 37=25+1237 = 25 + 12: two coins each.

2. Without a coin of 11, some amounts cannot be paid at all, and greedy may leave a remainder smaller than every coin, as 33 with coins of 22 and 55 after taking nothing, or 11 after taking a 22.

3. Below cm+cm−1=40+25=65c_m + c_{m-1} = 40 + 25 = 65.

4. The theorem places the first failure; the question asks for all of them up to 100100.

5. Greedy: 25+5+5+125 + 5 + 5 + 1, four coins. Better: 12+12+1212 + 12 + 12, three.

6. The first failure is above c3+1=6c_3 + 1 = 6: amounts 11 to 66 cannot be it. The program examined 77 to 3636 (and, without knowing the theorem, 11 to 66 too) before finding 3636.

7. 4949: greedy 40+5+2+240 + 5 + 2 + 2, four coins; 25+12+1225 + 12 + 12, three. 5050: greedy 40+5+540 + 5 + 5, three; 25+2525 + 25, two.

8. One division per coin value, six in all, whatever the amount; the search tries combinations of all the coins.

9. No: 3636 fails.

10. Their best change uses three coins of 1212: 36=3×1236 = 3 \times 12, 61=25+3×1261 = 25 + 3 \times 12, 76=40+3×1276 = 40 + 3 \times 12. Greedy takes a larger coin first and can no longer use three 1212.

11. 6060: greedy 40+12+5+2+140 + 12 + 5 + 2 + 1, five; 25+25+5+525 + 25 + 5 + 5, four. 6161: greedy 40+12+5+2+240 + 12 + 5 + 2 + 2, five; 25+12+12+1225 + 12 + 12 + 12, four. 6262: greedy 40+12+5+540 + 12 + 5 + 5, four; 25+25+1225 + 25 + 12, three. 6363: greedy 40+12+5+5+140 + 12 + 5 + 5 + 1, five; 25+25+12+125 + 25 + 12 + 1, four.

12. Greedy gives 40+40+12+5+2+140 + 40 + 12 + 5 + 2 + 1, six coins; 25+25+25+2525 + 25 + 25 + 25 needs four: two too many. 100100 is the only amount up to 100100 where greedy loses two coins.

13. 1717.

14. Up to 40+25=6540 + 25 = 65; by the theorem, a system that does not fail below that never fails.

15. Greedy gives 25+10+125 + 10 + 1, three coins; two coins cannot make 3636 (4040 is too large, and no two of 2525, 1010, 55, 22, 11 add to 3636).

16. 3636: greedy 26+5+526 + 5 + 5, three, as many as 12×312 \times 3. 5050: greedy 40+5+540 + 5 + 5, three; with 2525 gone, no two coins make 5050.

17. A coin already present would leave five different coins: the system is not one coin changed, but one coin removed.

18. Replacing 2525 by 33, by 1919 or by 2626.

19. Shopkeepers can follow the quickest rule and still give the fewest coins, so fewer coins change hands and fewer need to be minted.

20. In Brenmoor greedy change first goes wrong at 3636, giving four coins where three of 1212 suffice, and it goes wrong on 1717 amounts up to 100100.

本章定义的术语

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