TExcelTAD

Exercises

Fourteen problems covering the whole course: dynamic programming, greedy algorithms and amortized analysis. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.

Tip: For a DP, write down the subproblem in words before the recurrence ("c[i,j]c[i, j] is the best value for ..."); most wrong recurrences come from a subproblem that was never stated precisely. For a greedy algorithm, look for a counterexample on three or four elements before trying to prove it.

# Exercise Practises
1 Rod cutting by hand bottom-up DP, reconstruction
2 Strings without two adjacent ones setting up a counting DP
3 A chain of four matrices interval DP
4 LCS and edit distance by hand prefix-pair DPs
5 Houses on a street choosing the state
6 A tiny knapsack, and a huge capacity 0/1 knapsack, pseudo-polynomial time
7 Three keys in a search tree optimal BSTs
8 Stabbing intervals with points greedy choice, exchange argument
9 Huffman code by hand Huffman's algorithm
10 Two per category partition matroids, greedy
11 Five jobs with deadlines unit-task scheduling
12 A ternary counter aggregate method
13 A table that triples potential method
14 Why the quarter? table contraction

Exercise 1: Rod cutting by hand

Prices for lengths 1 to 5 are 3,7,11,12,163, 7, 11, 12, 16. Find r1,…,r5r_1, \ldots, r_5 and an optimal cutting of a rod of length 5.

Answer

r=(3,7,11,14,18)r = (3, 7, 11, 14, 18). Length 5 is best cut into 2+32 + 3, for 7+11=187 + 11 = 18.

Solution

Bottom-up, with r0=0r_0 = 0: r1=3r_1 = 3; r2=max⁡(3+3,7)=7r_2 = \max(3 + 3, 7) = 7; r3=max⁡(3+7,7+3,11)=11r_3 = \max(3 + 7, 7 + 3, 11) = 11; r4=max⁡(3+11,7+7,11+3,12)=14r_4 = \max(3 + 11, 7 + 7, 11 + 3, 12) = 14; r5=max⁡(3+14,7+11,11+7,12+3,16)=18r_5 = \max(3 + 14, 7 + 11, 11 + 7, 12 + 3, 16) = 18. The smallest winning first piece for length 5 is 2, and the rest, length 3, is best uncut. See Reconstructing an Optimal Solution.

python · try it yourself
p = [3, 7, 11, 12, 16]
r, s = [0] * 6, [0] * 6
for j in range(1, 6):
    best = -1
    for i in range(1, j + 1):
        if p[i - 1] + r[j - i] > best:
            best, s[j] = p[i - 1] + r[j - i], i
    r[j] = best
pieces, n = [], 5
while n:
    pieces.append(s[n]); n -= s[n]
print("r =", r[1:], " cutting of 5:", pieces)
r = [3, 7, 11, 14, 18]  cutting of 5: [2, 3]

Exercise 2: Strings without two adjacent ones

How many binary strings of length nn contain no two consecutive 1s? Give a recurrence, the value for n=10n = 10, and the running time of the bottom-up computation.

Answer

an=an−1+an−2a_n = a_{n-1} + a_{n-2} with a1=2a_1 = 2, a2=3a_2 = 3; a10=144a_{10} = 144 (the Fibonacci number F12F_{12}). Θ(n)\Theta(n) additions.

Solution

Split by the last character. A valid string ending in 0 is any valid string of length n−1n - 1 followed by 0. A valid string ending in 1 must end in 0101, so it is a valid string of length n−2n - 2 followed by 0101. These cases are disjoint and cover everything, so an=an−1+an−2a_n = a_{n-1} + a_{n-2}. With a1=2a_1 = 2 (0, 1) and a2=3a_2 = 3 (00, 01, 10), the sequence is 2,3,5,8,…2, 3, 5, 8, \ldots, so an=Fn+2a_n = F_{n+2}. The subproblems are the lengths 1..n1..n, each with two ingredients. A brute-force check:

python · try it yourself
from itertools import product
a = {1: 2, 2: 3}
for n in range(3, 11):
    a[n] = a[n - 1] + a[n - 2]
brute = sum(1 for bits in product("01", repeat=10) if "11" not in "".join(bits))
print("a_10 =", a[10], " brute force:", brute)
a_10 = 144  brute force: 144

Exercise 3: A chain of four matrices

Find the cheapest order for multiplying matrices with dimensions p=(5,10,3,12,5)p = (5, 10, 3, 12, 5), and its cost.

Answer

((A1A2)(A3A4))((A_1 A_2)(A_3 A_4)) with 405 scalar multiplications.

Solution

Length 2: m[1,2]=5⋅10⋅3=150m[1,2] = 5 \cdot 10 \cdot 3 = 150, m[2,3]=10⋅3⋅12=360m[2,3] = 10 \cdot 3 \cdot 12 = 360, m[3,4]=3⋅12⋅5=180m[3,4] = 3 \cdot 12 \cdot 5 = 180. Length 3: m[1,3]=min⁡(0+360+5⋅10⋅12, 150+0+5⋅3⋅12)=min⁡(960,330)=330m[1,3] = \min(0 + 360 + 5 \cdot 10 \cdot 12,\ 150 + 0 + 5 \cdot 3 \cdot 12) = \min(960, 330) = 330; m[2,4]=min⁡(0+180+10⋅3⋅5, 360+0+10⋅12⋅5)=min⁡(330,960)=330m[2,4] = \min(0 + 180 + 10 \cdot 3 \cdot 5,\ 360 + 0 + 10 \cdot 12 \cdot 5) = \min(330, 960) = 330. Length 4: m[1,4]=min⁡(0+330+250, 150+180+75, 330+0+300)=min⁡(580,405,630)=405m[1,4] = \min(0 + 330 + 250,\ 150 + 180 + 75,\ 330 + 0 + 300) = \min(580, 405, 630) = 405, at the split k=2k = 2. Both halves are single products. See Matrix-Chain Multiplication: The Table.

Exercise 4: LCS and edit distance by hand

(a) Find the length of an LCS of BANANA and ATANA. (b) Find the edit distance from PARK to SPARE.

Answer

(a) 4, for example AANA. (b) 2: insert S at the front and substitute K by E.

Solution

(a) ATANA minus its T is AANA, which is a subsequence of BANANA (positions 2, 4, 5, 6). Length 5 is impossible: it would be all of ATANA, but BANANA has no T. (b) Lengths differ by 1, so at least one insertion is needed, and PARK and SPARE differ in more than the inserted letter (the last letters differ), so 1 is impossible; the two edits given reach SPARE. The tables confirm both:

python · try it yourself
def lcs(x, y):
    c = [[0] * (len(y) + 1) for _ in range(len(x) + 1)]
    for i in range(1, len(x) + 1):
        for j in range(1, len(y) + 1):
            c[i][j] = c[i - 1][j - 1] + 1 if x[i - 1] == y[j - 1] else max(c[i - 1][j], c[i][j - 1])
    return c[-1][-1]

def edit(x, y):
    prev = list(range(len(y) + 1))
    for i, ch in enumerate(x, 1):
        cur = [i]
        for j, d in enumerate(y, 1):
            cur.append(min(prev[j - 1] + (ch != d), prev[j] + 1, cur[-1] + 1))
        prev = cur
    return prev[-1]

print("LCS(BANANA, ATANA) =", lcs("BANANA", "ATANA"))
print("d(PARK, SPARE) =", edit("PARK", "SPARE"))
LCS(BANANA, ATANA) = 4
d(PARK, SPARE) = 2

Exercise 5: Houses on a street

Houses along a street hold amounts a1,…,an≥0a_1, \ldots, a_n \ge 0. A collector may visit any set of houses but never two neighbours. Give an O(n)O(n) algorithm for the largest total, and apply it to 6,1,2,7,5,36, 1, 2, 7, 5, 3.

Answer

Bi=max⁡(Bi−1, Bi−2+ai)B_i = \max(B_{i-1},\ B_{i-2} + a_i) with B0=0B_0 = 0, B1=a1B_1 = a_1. For the example B6=16B_6 = 16: houses 1, 4 and 6 (6+7+36 + 7 + 3).

Solution

State: BiB_i, the best total using only houses 1..i1..i. Either house ii is skipped (Bi−1B_{i-1}), or it is visited, and then house i−1i - 1 is not, leaving houses 1..i−21..i-2 (Bi−2+aiB_{i-2} + a_i). One pass computes B1,…,BnB_1, \ldots, B_n; two variables suffice for the values. For the example, B=(6,6,8,13,13,16)B = (6, 6, 8, 13, 13, 16). A greedy rule such as "take the largest remaining house, discard its neighbours" fails on 2,3,22, 3, 2: it takes the 3, while 2+2=42 + 2 = 4 is better.

Exercise 6: A tiny knapsack, and a huge capacity

(a) Items (weight, value): (1,1)(1, 1), (3,4)(3, 4), (4,5)(4, 5), (5,7)(5, 7); capacity 7. Find the best 0/1 packing. (b) A program solves 0/1 knapsack in Θ(nW)\Theta(nW) time. Is it practical for n=50n = 50 items with weights around 101210^{12} and W=4⋅1012W = 4 \cdot 10^{12}?

Answer

(a) Value 9, items 2 and 3. (b) No: nW=2⋅1014nW = 2 \cdot 10^{14} steps (and as many table cells), although the input has only a few thousand bits.

Solution

(a) The candidates that fit: items 2 and 3 (weight 7, value 9), items 1 and 4 (weight 6, value 8), items 1 and 2 (value 5), items 1 and 3 (value 6), and singles. Note that item 4 has the best density but is not in the optimum. (b) The running time is polynomial in the value of WW but exponential in its length (about 42 bits): pseudo-polynomial (0/1 Knapsack and Pseudo-Polynomial Time). With 50 items, meet-in-the-middle (2252^{25} subsets per half) or branch and bound with the fractional bound would be the realistic choices.

Exercise 7: Three keys in a search tree

Keys k1<k2<k3k_1 < k_2 < k_3 are searched 22, 55 and 33 times. Find an optimal BST and its cost (comparisons = depth + 1).

Answer

Root k2k_2 with children k1k_1 and k3k_3: cost 5⋅1+2⋅2+3⋅2=155 \cdot 1 + 2 \cdot 2 + 3 \cdot 2 = 15.

Solution

There are five BSTs on three keys. Root k2k_2: 15. Root k1k_1 with k2k_2 below and k3k_3 below that: 2+10+9=212 + 10 + 9 = 21; root k1k_1, then k3k_3, then k2k_2: 2+6+15=232 + 6 + 15 = 23. Root k3k_3 with k2k_2 then k1k_1: 3+10+6=193 + 10 + 6 = 19; root k3k_3, then k1k_1, then k2k_2: 3+4+15=223 + 4 + 15 = 22. With the recurrence: w(1,3)=10w(1, 3) = 10, and e[1,3]=10+min⁡(e[2,3], e[1,1]+e[3,3], e[1,2])=10+min⁡(11,5,9)=15e[1, 3] = 10 + \min(e[2,3],\ e[1,1] + e[3,3],\ e[1,2]) = 10 + \min(11, 5, 9) = 15, where e[2,3]=8+3=11e[2, 3] = 8 + 3 = 11 (root k2k_2) and e[1,2]=7+2=9e[1, 2] = 7 + 2 = 9 (root k2k_2). See Optimal Binary Search Trees.

Exercise 8: Stabbing intervals with points

Given closed intervals [ai,bi][a_i, b_i] on the line, place as few points as possible so that every interval contains at least one point. Give a greedy algorithm and prove it optimal. Apply it to [1,4],[2,6],[3,5],[5,8],[7,9][1, 4], [2, 6], [3, 5], [5, 8], [7, 9].

Answer

Repeatedly take the interval with the smallest right endpoint bb among those not yet stabbed, place a point at bb, and remove every interval containing it. For the example: points 4 and 8.

Solution

Greedy choice. Let I=[a,b]I = [a, b] have the smallest right endpoint. Any solution has a point x∈Ix \in I, so x≤bx \le b. Moving xx to bb keeps every interval it stabbed stabbed: an interval [a′,b′][a', b'] containing xx has a′≤x≤ba' \le x \le b and b′≥bb' \ge b (since bb is the smallest right endpoint), so it contains bb. So some optimal solution uses the point bb. Optimal substructure: the intervals not containing bb form a smaller instance, and an optimal solution for it plus bb is optimal overall. On the example, point 4 stabs [1,4],[2,6],[3,5][1, 4], [2, 6], [3, 5]; the first remaining right endpoint is 8, which stabs [5,8],[7,9][5, 8], [7, 9]. Two points are needed, since [1,4][1, 4] and [5,8][5, 8] are disjoint. This is the "dual" of activity selection: the number of points equals the maximum number of pairwise disjoint intervals.

Exercise 9: Huffman code by hand

Build a Huffman code for frequencies 2,3,5,7,11,132, 3, 5, 7, 11, 13 and find the total number of bits.

Answer

Merges 2+3=52 + 3 = 5, 5+5=105 + 5 = 10, 7+10=177 + 10 = 17, 11+13=2411 + 13 = 24, 17+24=4117 + 24 = 41; total 5+10+17+24+41=975 + 10 + 17 + 24 + 41 = 97 bits.

Solution

Each merge adds its weight to the total (Prefix Codes and Huffman's Algorithm). Codeword lengths: 13 and 11 get 2 bits, 7 gets 2 bits, 5 gets 3, and 2 and 3 get 4 bits each: 13⋅2+11⋅2+7⋅2+5⋅3+3⋅4+2⋅4=26+22+14+15+12+8=9713 \cdot 2 + 11 \cdot 2 + 7 \cdot 2 + 5 \cdot 3 + 3 \cdot 4 + 2 \cdot 4 = 26 + 22 + 14 + 15 + 12 + 8 = 97. A fixed-length code would need 3⋅41=1233 \cdot 41 = 123 bits.

cpp · try it yourself
#include <cstdio>
#include <functional>
#include <queue>
#include <vector>

int main() {
    std::priority_queue<int, std::vector<int>, std::greater<int>> q;
    for (int f : {2, 3, 5, 7, 11, 13}) q.push(f);
    int total = 0;
    while (q.size() > 1) {
        int a = q.top(); q.pop();
        int b = q.top(); q.pop();
        std::printf("merge %d + %d = %d\n", a, b, a + b);
        total += a + b;
        q.push(a + b);
    }
    std::printf("total %d bits\n", total);
}
merge 2 + 3 = 5
merge 5 + 5 = 10
merge 7 + 10 = 17
merge 11 + 13 = 24
merge 17 + 24 = 41
total 97 bits

Exercise 10: Two per category

A shop chooses items for a display: from each category at most two items, and the goal is the largest total value. Show that the feasible sets form a matroid, and find the best display for: fruit 9, 4, 7; bread 6, 8; cheese 5, 3, 10, 2.

Answer

It is a partition matroid. Greedy gives fruit 9 and 7, bread 8 and 6, cheese 10 and 5: total 45.

Solution

Hereditary: removing items keeps every category within its limit. Exchange: if ∣A∣<∣B∣\lvert A \rvert < \lvert B \rvert, some category has more items in BB than in AA, so AA has fewer than two from it, and any item of B∖AB \setminus A from that category can be added. By the weighted matroid theorem, greedy is optimal: take items by decreasing value, skipping one when its category is full: 10, 9, 8, 7, 6, then 5 (cheese has only one so far), then 4 (fruit full, skip), 3 and 2 (cheese full, skip). Here greedy is just "the two best of each category", which is obviously optimal; the matroid view matters when constraints are combined in less obvious ways.

Exercise 11: Five jobs with deadlines

Unit-time jobs with deadlines 2,2,1,3,32, 2, 1, 3, 3 and penalties 50,40,30,20,1050, 40, 30, 20, 10. Find a schedule with minimum total penalty.

Answer

Early jobs 1, 2, 4 in the order 2,1,42, 1, 4 (or 1,2,41, 2, 4), then jobs 3 and 5 late: penalty 30+10=4030 + 10 = 40.

Solution

Greedy by decreasing penalty, with the test Nt(A)≤tN_t(A) \le t (Scheduling Unit Tasks): job 1 (deadline 2) accepted; job 2 (deadline 2): N2=2N_2 = 2, accepted; job 3 (deadline 1): N2N_2 would be 3, rejected; job 4 (deadline 3): N3=3N_3 = 3, accepted; job 5 (deadline 3): N3N_3 would be 4, rejected. The accepted jobs run in deadline order in hours 1 to 3, the rejected ones after.

Exercise 12: A ternary counter

A counter stores a number in base 3, with digits 0,1,20, 1, 2. An increment turns trailing 2s into 0s and adds one to the next digit. Show that nn increments from 0 change fewer than 32n\frac{3}{2} n digits in total.

Answer

Digit ii changes exactly ⌊n/3i⌋\lfloor n / 3^i \rfloor times, so the total is less than n∑i≥03−i=32nn \sum_{i \ge 0} 3^{-i} = \frac{3}{2} n.

Solution

Digit ii changes exactly when all lower digits are 2 before the increment, which happens once every 3i3^i increments. Summing the geometric series as in The Aggregate Method gives the bound, so the amortized cost of an increment is below 1.5 digit changes. For example, 9 increments change 9+3+1=139 + 3 + 1 = 13 digits and 27 increments change 27+9+3+1=4027 + 9 + 3 + 1 = 40. In base bb the bound becomes bb−1n\frac{b}{b-1} n.

Exercise 13: A table that triples

A dynamic table triples its size when an insertion finds it full. Find a potential function that gives every insertion the same amortized cost, and find that cost.

Answer

Φ=3 num−size2\Phi = \frac{3\,\mathit{num} - \mathit{size}}{2}; every insertion (after the first) has amortized cost 52\frac{5}{2}.

Solution

Look for Φ=a⋅num−b⋅size\Phi = a \cdot \mathit{num} - b \cdot \mathit{size} that is 0 right after an expansion, when num=size/3\mathit{num} = \mathit{size}/3, and equals num\mathit{num} when the table is full, to pay for copying. That gives a/3=ba/3 = b and a−b=1a - b = 1, so a=32a = \frac{3}{2} and b=12b = \frac{1}{2}. Without expansion, c^=1+32=52\hat{c} = 1 + \frac{3}{2} = \frac{5}{2}. With expansion from a full table of size mm: c=m+1c = m + 1, and Φ\Phi goes from 3m−m2=m\frac{3m - m}{2} = m to 3(m+1)−3m2=32\frac{3(m+1) - 3m}{2} = \frac{3}{2}, so c^=m+1+32−m=52\hat{c} = m + 1 + \frac{3}{2} - m = \frac{5}{2}. This matches the general 1+γγ−11 + \frac{\gamma}{\gamma - 1} for growth factor γ=3\gamma = 3 (Dynamic Tables: Expansion). Φ≥0\Phi \ge 0 because the table is always at least a third full.

Exercise 14: Why the quarter?

A table doubles when full and halves when a deletion leaves it less than a fraction β\beta full. For which β\beta is the amortized cost of every operation O(1)O(1), and why does β=12\beta = \frac{1}{2} fail?

Answer

Any constant β<12\beta < \frac{1}{2} works; β=12\beta = \frac{1}{2} allows thrashing.

Solution

After a doubling or a halving the load factor is 12\frac{1}{2}. With β<12\beta < \frac{1}{2}, the next resize needs either enough insertions to fill the table (about size2\frac{\mathit{size}}{2} of them) or enough deletions to bring it from 12\frac{1}{2} to β\beta (about (12−β)size(\frac{1}{2} - \beta)\mathit{size} of them), and the resize copies at most size\mathit{size} items, so the copies are paid by Θ(size)\Theta(\mathit{size}) operations, a constant each (the constant grows like 11/2−β\frac{1}{1/2 - \beta}). With β=12\beta = \frac{1}{2}, a table that has just doubled is exactly at the threshold, so two deletions halve it and the next insertions double it again: Θ(n)\Theta(n) per operation for an adversary (Dynamic Tables: Contraction). The choice β=14\beta = \frac{1}{4} is the usual one because it gives small constants (3 and 2) and wastes at most a factor 4 in memory.

Test yourself

In Exercise 5 (houses on a street), what does BiB_i stand for?

  1. The best total using exactly house ii
  2. The best total using only houses 1..i1..i
  3. The amount in house ii
  4. The number of houses visited

Where does the greedy algorithm of Exercise 8 place its first point?

  1. At the leftmost start point
  2. At the smallest right endpoint
  3. At the midpoint of the longest interval
  4. At the point covered by the most intervals

What is the amortized number of digit changes per increment of a base-10 counter, by the method of Exercise 12?

  1. Less than 109\frac{10}{9}
  2. Less than 2
  3. Exactly 1
  4. lg⁡10\lg 10