Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxing
In questa pagina 7
These exercises show that a greedy approach often captures the most natural, human strategy, which for some problems is provably optimal, and that writing the algorithm is immediate while proving it optimal remains delicate even for very simple cases. The theory is in Greedy Paradigm and Activity Selectionthe greedy paradigm makes the locally best choice immediately, cleans up the instance and solves the single residual subinstance (tail recursion, hence a loop); the code is easy and correctness is not, requiring the greedy choice property and optimal substructure; case study activity selection with the earliest-finish rule, full proof, Theta(n) after sorting, and counterexamples for wrong greedy rules.Greedy Paradigm and Activity Selection → and, for the most important case, in Huffman Codescharacter-by-character compression needs an injective variable-length code, which prefix codes guarantee; a prefix code is a binary trie with one leaf per character of cost B(T) = sum of f(c) d_T(c), the optimal trie is full with n-1 internal nodes, Huffman repeatedly merges the two lowest-frequency trees using a priority queue (2n-1 extractions, O(n log n)), and optimality follows from the greedy choice (two rarest characters are deepest sibling leaves, by exchange) and substructure B(T) = B(T') + f(x) + f(y).Huffman Codes →.
The method in six steps
- Greedy choice: the first choice, the one that looks locally best, made without solving subinstances.
- Clean-up and residual subinstance: what is removed after the choice; what remains is one subinstance of the same problem.
- Algorithm: follows directly from steps 1 and 2 (tail recursion, hence a loop). Give pseudocode, argue that the output is feasible and compute the complexity.
- Greedy choice property: an optimal solution containing the greedy choice exists. Start from any optimal solution and, if it does not contain it, modify it (exchange, cut-and-paste) without worsening the cost, checking that it stays feasible.
- Optimal substructure property: the part of an optimum left after the greedy choice is optimal for the residual. By contradiction: a better residual, composed with the greedy choice, would give a solution better than the optimum.
- Conclusion: by induction on the size (base: empty instance), the algorithm returns an optimum.
If there is no clean-up (no incompatibility), substructure (step 5) is almost immediate: every solution of the residual can be completed with the greedy choice. This is the case for all three problems below; the more delicate substructure is that of activity selection, where the clean-up is limited.
The three problems compared
| CD tracks | Shortest-first scheduling | (2,1)-boxing | |
|---|---|---|---|
| Instance | durations in fixed order, capacity | times of jobs | weights in |
| Goal | minimum number of CDs | minimum cumulative waiting time | minimum number of boxes (at most 2 objects, weight ) |
| Greedy choice | the longest prefix that fits on the first CD | the job of minimum duration first | if or , else |
| Clean-up | none; residual = suffix | none; residual = other jobs | none; residual = or |
| Greedy choice (proof) | move from to | swap the first job with a shorter one | swap two boxes, checking |
| Substructure | |||
| Cost | (sorting) | (weights already sorted) |
Exercise 1: compact burning of tracks on CDs
Statement. For there is a string of songs , the -th of duration . Songs are burned on a sequence of CDs so that (1) each song is on one CD and the concatenation of CDs by increasing index presents the songs in the same order as ; (2) the total duration on each CD does not exceed . Assume for all . A feasible solution is a sequence : holds the substring . Minimize .
Step 1: greedy choice. Fill the first CD with as many songs as possible: put on the songs of the longest prefix with (), then continue with the rest.
- Clean-up: none. The residual is the suffix , with the same . If then and the residual is empty (zero CDs).
- The residual has at least one song less ( since ), so the recursion ends.
Step 2: algorithm. The recursion is a tail one, so it is iterative: accumulate in sumd the duration of the current CD and, when the next song does not fit, close the CD and open a new one starting with that song. Vector holds the ends .
MIN_NUM_CD(d, dmax) {static constraint: d[i] <= dmax for every i}
n <- d.len
k <- 0; N[0] <- 0
sumd <- d[1] // the first CD starts with song c_1
for i <- 2 to n do
if sumd + d[i] > dmax then
// greedy choice identified: the current CD is full
k <- k + 1
N[k] <- i - 1 // CD k ends with song i-1
sumd <- d[i] // the next CD starts with song i
else
sumd <- sumd + d[i]
N[k+1] <- n // the last CD always ends with the last song
return N // there are k + 1 CDsFeasibility. At the start of each iteration sumd is the duration of the songs of the CD under construction and is : initially ; the else branch adds only if the total stays ; the then branch restarts from .
Complexity. The loop runs times, each with one comparison and one addition at most: comparisons, so , with auxiliary space besides the output.
Worked example. minutes, , .
sumd before |
sumd + d_i |
? | action | ||
|---|---|---|---|---|---|
| start | sumd , |
||||
| 2 | 3 | 4 | 7 | yes | sumd |
| 3 | 5 | 7 | 12 | no | , , sumd |
| 4 | 2 | 5 | 7 | yes | sumd |
| 5 | 6 | 7 | 13 | no | , , sumd |
| 6 | 1 | 6 | 7 | yes | sumd |
| 7 | 4 | 7 | 11 | no | , , sumd |
| 8 | 7 | 4 | 11 | no | , , sumd |
Finally : , so CDs: , , , , .
Step 3: greedy choice property. There is an optimal solution in which holds ().
Proof (cut-and-paste). Let be optimal with . If we are done. Otherwise ; since is the maximum number of songs fitting on a CD from the first, .
Build by moving songs from to . Checks:
- is feasible: it holds , of total duration by definition of .
- does not become empty. It must be : otherwise all songs of would be among and the move would empty it, giving a solution with one CD less than , contradicting optimality.
- is feasible: it holds a subset of its previous songs.
- Order: the concatenation still presents the songs in the original order.
The new sequence has the same number of CDs as : it is optimal and contains the greedy choice.
Step 4: optimal substructure. If is optimal and contains the greedy choice, then form an optimal solution of the residual .
Proof. There is no clean-up. The arrangement on is a feasible solution of using CDs. If it were not optimal, a solution of the residual with fewer than CDs, composed with the greedy choice, would give a solution of the original instance with fewer than CDs, contradicting the optimality of .
In formula: .
Step 5: correctness by induction on . Base: , zero CDs. Step: MIN_NUM_CD puts on and proceeds on the residual, optimally by induction; the number of CDs is .
Why greedy suffices here. The song order is fixed: the solution is a partition of the string, and filling the first CD can never lose, because any other partition closes the first CD earlier or at the same point. If songs could be reordered the problem would be bin packing, NP-hard (outside the program).
Exercise 2: shortest-first job scheduling
Statement. A job is a program to run on a machine . There are jobs with execution times . A schedule is a bijection , with jobs executed in the order . Under the waiting time of the -th executed job is the sum of the times of the jobs run before, and the goal is to minimize the cumulative waiting time . Prove the Shortest-Job First (SJF) property: for any optimal schedule , . Then give the algorithm and optimal substructure.
Step 1: a formula for the cost. The time of the job in position appears in the waiting time of all jobs executed after it, i.e. positions , which are . So The first job has weight , the second , and so on: jobs run first count more, which is why short ones should go first.
Example. . In order the waits are , (formula: ). In order (durations ) the waits are and .
Step 2: the SJF property. Proof by contradiction with exchange. Let be optimal and suppose it violates SJF: and is not of minimum duration. Then there is a shorter job , , executed in a position : .
Build by swapping and : , , otherwise. Compare waits:
- : both .
- : the sum contains position but not position . Compared with it has in place of :
- : the sum contains both positions, swapped: same addends, so .
The decrease is for each of the indices , i.e. times: contradicting optimality.
Remark: the property holds for every optimum (stronger than "there exists an optimum"). With equal times there may be several optima, all with a first job of minimum duration.
Step 3: algorithm and substructure. Viewing the choice of as the greedy choice, SJF says it is a job of minimum duration. There is no clean-up: the residual is the set of the other jobs. Repeating the choice, the resulting schedule is obtained by sorting jobs by non-decreasing duration. The code is a call to a sorting routine, cost .
SJF_SCHEDULE(t)
sort indices 1..n by t non-decreasing // O(n log n)
pi(i) <- index of the job in position i of the order
return piOptimal substructure. Let be optimal and the schedule of the following jobs (the residual). The wait of each residual job under is that under minus . The residual has jobs, so The first term does not depend on : if were not optimal, replacing it with a better schedule (cut-and-paste) would give a lower cost than . So is optimal for the residual.
Correctness. By induction on the number of jobs: for the empty schedule is optimal; for the sorted schedule starts with a job of minimum duration (SJF), continues with the sorted schedule of the residual, optimal by induction, and by the formula costs .
A second reading. In the decreasing weights are matched with the times: the sum is minimal when large weights go to small times (rearrangement inequality), i.e. with non-decreasing times.
Exercise 3: (2,1)-boxing
Statement. Let be objects of weights , normalized in and sorted: . A boxing of is a partition into non-empty subsets (boxes). It is a (2,1)-boxing if every box has and total weight . Find a (2,1)-boxing of minimum cardinality with a greedy approach.
Example. With there are three (2,1)-boxings: all singletons, and (the pair weighs ). The last two are optimal, with 2 boxes.
Step 1: greedy choice. Look at the heaviest object , the hardest to place. Cases:
- : .
- and : even paired with the lightest object the weight exceeds , so with any other object it would: goes alone, .
- and : make the box , pairing the heaviest with the lightest.
In case 3 the choice is "reckless": it settles for pairing with even though a heavier object might still fit with , wasting capacity. The greedy choice property will show nothing is lost.
Clean-up: none. The residual is: cases 1 and 2, ; case 3, . It is still sorted and satisfies the same hypotheses.
Step 2: algorithm. Indices first and last delimit the residual .
BOXING_2_1(O, p) {p sorted non-decreasing}
n <- |O|
B <- {}
first <- 1; last <- n
while first <= last do
if first = last or p[first] + p[last] > 1 then // cases 1 and 2
B <- B U { {o_last} }
else // case 3
B <- B U { {o_first, o_last} }
first <- first + 1
last <- last - 1
return Blast always decreases, first increases only in case 3.
It returns a (2,1)-boxing. Each iteration boxes and, in case 3, also , then excludes them; the loop ends with , after boxing every object in exactly one box. Boxes have one or two objects and total weight .
Complexity. last decreases by per iteration, so iterations are at most and at least . Each does one sum and one comparison: (plus if weights are not sorted).
Worked example. Weights , .
| iter. | first, last | case | box | after (first, last) | |
|---|---|---|---|---|---|
| 1 | 1, 8 | 2 | 1, 7 | ||
| 2 | 1, 7 | 3 | 2, 6 | ||
| 3 | 2, 6 | 3 | 3, 5 | ||
| 4 | 3, 5 | 3 | 4, 4 | ||
| 5 | 4, 4 | 1 | 4, 3 (end) |
Result: boxes, the optimum.
Step 3: greedy choice property. There is an optimal (2,1)-boxing containing the greedy choice.
Proof. Cases 1 and 2. In every (2,1)-boxing is alone, so every boxing contains .
Case 3 (greedy box , ). Let be an optimal (2,1)-boxing.
- If and are in the same box, it is exactly .
- Otherwise they are in distinct boxes and . Build
Checks:
- Number of boxes. ; if the second new box were empty there would be one box less, contradicting optimality, so .
- The greedy box is feasible by hypothesis.
- The second box has at most two objects ( brings at most one besides , at most one besides ). If it has one, the weight constraint holds. If two, say , : ( is the heaviest) and (constraint on ), i.e. . Summing,
- Other objects stay in their boxes.
So is a (2,1)-boxing of the same cardinality as , hence optimal, and contains the greedy choice.
Step 4: optimal substructure. If is optimal and contains the greedy choice, the other boxes form an optimal (2,1)-boxing of .
Proof. No clean-up. The boxes other than the greedy one contain exactly the objects of and respect the constraints, so they are a feasible . If it were not optimal, adding the greedy box to an optimal (2,1)-boxing of would give a boxing of with fewer boxes than (cut-and-paste), contradicting its optimality.
In formula , .
Step 5: correctness by induction on . Base: , no boxes. Step: the algorithm makes the greedy choice of case 1, 2 or 3 and proceeds on the residual (the part between first and last), optimal by induction; by substructure the number of boxes is .
Counterexamples: proving that a strategy is wrong
To show that a greedy strategy is not optimal, one instance suffices. For activity selection "shortest duration" (instance : picks and gets 1 activity, the optimum has 2) and "fewest incompatibilities" are wrong. Greedy also fails when activities have weights to maximize: dynamic programming is needed (Dynamic Programming - Paradigm and Memoizationdynamic programming improves on divide and conquer by storing the solutions of repeated subinstances in a table; Fibonacci shows the gap (F_n - 1 additions recursively, n - 1 with a table), memoization is recursion plus a global table, and optimization problems follow a five-step scheme built on optimal substructure and cut-and-paste.Dynamic Programming - Paradigm and Memoization →).
Typical exam questions
- Which two properties must be proved for a greedy algorithm and what changes without clean-up? Answer: greedy choice (an optimum containing it, by exchange) and optimal substructure (contradiction with cut-and-paste); without clean-up the residual is simply what remains and substructure follows at once.
- Prove that in every optimal schedule the first job has minimum duration. Answer: formula ; swap (first, not minimum) with a shorter in position : waits for , unchanged for ; the total drops by .
- How many CDs for with ? Answer: (greedy: ).
Versione ripasso
- Method: (1) greedy choice, (2) clean-up and residual, (3) algorithm (feasible, complexity), (4) greedy choice by exchange without worsening cost, (5) substructure by contradiction with cut-and-paste, (6) induction on size. Without clean-up substructure is immediate. Theory: Greedy Paradigm and Activity Selectionthe greedy paradigm makes the locally best choice immediately, cleans up the instance and solves the single residual subinstance (tail recursion, hence a loop); the code is easy and correctness is not, requiring the greedy choice property and optimal substructure; case study activity selection with the earliest-finish rule, full proof, Theta(n) after sorting, and counterexamples for wrong greedy rules.Greedy Paradigm and Activity Selection →.
- CD tracks: longest prefix of duration on the first CD;
sumdrestarts from ; . Proof: move from to ( does not become empty, else the optimum would have a CD too many). Example , : CDs, . Greedy suffices because the order is fixed; with reordering it is bin packing. - Shortest-first: ; sort by non-decreasing duration, . SJF holds for every optimum: swapping with a shorter job lowers the total by . . Example : in index order, sorted.
- (2,1)-boxing: greedy box ( or ) else ; indices
first/last; , between and iterations. Proof: swap two boxes with and , so . Example with 8 objects: boxes. - Counterexamples: to refute a greedy rule one instance suffices (activities: shortest duration, fewest incompatibilities). With weights or free reordering greedy is not enough.
- Typical mistakes: proving only existence of an optimum when "every optimum" is asked; not checking feasibility after the exchange; forgetting the case where a CD or box becomes empty; not closing with induction.