Salta al contenuto
Note per Studenti Greedy Paradigm and Activity Selection Report

Greedy Paradigm and Activity Selection

In questa pagina 4

The third paradigm after divide and conquer and 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 →. It applies to optimization problems: among the feasible solutions of an instance, find one of minimum or maximum cost.

From dynamic programming to greedy

In a DP algorithm the optimal solution is obtained by composing a sequence of choices, and the information saved to rebuild it (the index k⋆k^\star for matrix chains, the arrow in the LCS table) is precisely the choices. But each choice is deliberate: it can only be made after solving many subinstances (all the values of kk, all three LCS subinstances). This caution makes DP widely applicable but has a cost (a table and work per cell).

For some problems the approach can be reversed:

  1. Greedy choice: make immediately the first choice, the one that locally looks best, without solving any subinstance.
  2. Clean-up: remove the elements incompatible with the choice. What is left is a single subinstance, the residual subinstance, solved with the same procedure.

Consequences.

The code comes before the analysis. In D&C and DP one studies the substructure and then writes the algorithm; here the code follows directly from the definitions of greedy choice and clean-up, and is easy. The hard work is proving it correct, and equally natural greedy choices may give wrong solutions.

The two properties to prove

Greedy choice property. There is always an optimal solution that contains the greedy choice. It guarantees that the reckless choice does not compromise optimality.

Optimal substructure property. There is an optimal solution that, besides the greedy choice, contains an optimal solution of the residual subinstance.

Typical techniques:

  • Greedy choice: start from any optimal solution A^\hat A; if it does not contain the greedy choice, modify it (exchange, or cut-and-paste) into A⋆A^\star containing it, without worsening the cost. Then A⋆A^\star is still optimal.
  • Substructure: by contradiction. If the part of A⋆A^\star left after the greedy choice were not optimal for the residual, replace it with an optimal one (cut-and-paste) obtaining a better solution of the original instance: contradiction.

Theorem (correctness scheme). If a greedy algorithm always makes the greedy choice, cleans up and solves the residual recursively, and the two properties hold, then it returns an optimal solution.

Proof. By induction on the instance size. Base: the empty instance, the empty solution is optimal. Step: assume the algorithm is correct on smaller instances, in particular on the residual, which is strictly smaller. By the two properties there is an optimal A⋆A^\star made of the greedy choice and an optimal solution of the residual. The algorithm returns the greedy choice plus the solution that the induction hypothesis guarantees optimal for the residual: same cost as A⋆A^\star, hence optimal. □\square

The inductive reasoning is always the same: only the two properties change from problem to problem. See Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxinghow to set up and prove a greedy exercise (greedy choice, clean-up, algorithm, greedy choice property by exchange, optimal substructure by contradiction, induction) applied to three problems with empty clean-up: CD tracks (fill the first CD, Theta(n)), shortest-first scheduling (sort by duration, SJF holds for every optimum, O(n log n)) and (2,1)-boxing (pair the heaviest with the lightest, Theta(n)).Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxing →.

The counterexample. To show that a greedy strategy is wrong it suffices to give one instance in which the greedy choice excludes every optimum, which is much easier than proving correctness.

The activity selection problem

A shared resource (a classroom) and a set of activities S={a1,…,an}S = \{a_1, \dots, a_n\} that want to use it. Activity aja_j occupies the interval [sj,fj)[s_j, f_j) with sj<fjs_j < f_j (start included, finish excluded).

Definition. Two activities aia_i and aja_j are compatible if their intervals are disjoint, i.e. sj≥fiorsi≥fj.s_j \ge f_i \quad\text{or}\quad s_i \ge f_j . A subset is mutually compatible if all pairs are. The problem (activity selection) asks for a mutually compatible subset of maximum cardinality.

Since intervals are open on the right, an activity ending and another starting at the same instant are compatible.

Example. s=(2,1,2,3,5,7)s = (2,1,2,3,5,7), f=(3,5,6,6,7,8)f = (3,5,6,6,7,8), i.e. a1=[2,3)a_1 = [2,3), a2=[1,5)a_2 = [1,5), a3=[2,6)a_3 = [2,6), a4=[3,6)a_4 = [3,6), a5=[5,7)a_5 = [5,7), a6=[7,8)a_6 = [7,8).

The greedy algorithm

Assume a1,…,ana_1, \dots, a_n sorted by non-decreasing finish time, f1≤⋯≤fnf_1 \le \dots \le f_n; otherwise sort in O(nlog⁡n)O(n \log n). The order is crucial for correctness.

  • Greedy choice: the first activity, a1a_1, the one that finishes first. Intuition: it leaves the resource free for the longest contiguous interval.
  • Clean-up: remove the following activities incompatible with a1a_1, i.e. with sj<f1s_j < f_1, up to the first compatible one aga_g, g=min⁡{j:sj≥f1}g = \min\{j : s_j \ge f_1\}. The residual is the suffix ag,…,ana_g, \dots, a_n (empty if none is compatible). Residual instances are always suffixes, identified by an index ii: the main instance is i=1i = 1 and the empty one i=n+1i = n+1.
REC_GREEDY_SEL(s, f, i)                  {activities sorted by finish}
    n <- s.len
    if i > n then return {}
    G <- {i}
    j <- i + 1
    while j <= n and s[j] < f[i] do      // clean-up: discard incompatible ones
        j <- j + 1
    return G U REC_GREEDY_SEL(s, f, j)

In the while condition j <= n is tested first: the opposite order would read s[n+1]. Call with i=1i = 1. The recursion is a tail one and is removed. It suffices to remember the last chosen activity gg and compare every activity with it:

IT_GREEDY_SEL(s, f)
    n <- s.len
    A <- {1}
    g <- 1                               // last greedy choice
    for i <- 2 to n do
        if s[i] >= f[g] then             // compatible with the last choice
            A <- A U {i}
            g <- i
    return A
python
def it_greedy_sel(s, f):          # 1-based indices as in the text; s, f already sorted by finish
    A, g = [1], 1
    for i in range(2, len(s) + 1):
        if s[i - 1] >= f[g - 1]:
            A.append(i); g = i
    return A

Complexity. The scan performs exactly n−1n-1 comparisons (si≥fgs_i \ge f_g for i=2,…,ni = 2, \dots, n) and at most n−1n-1 insertions: Θ(n)\Theta(n). Sorting by finish time costs O(nlog⁡n)O(n \log n) and dominates if the data are unsorted.

Worked example

Same instance, s=(2,1,2,3,5,7)s = (2,1,2,3,5,7), f=(3,5,6,6,7,8)f = (3,5,6,6,7,8).

ii aia_i test si≥fgs_i \ge f_g outcome AA gg
1 [2,3)[2,3) initial choice chosen {1}\{1\} 1 (fg=3f_g = 3)
2 [1,5)[1,5) 1≥31 \ge 3 no discarded {1}\{1\} 1
3 [2,6)[2,6) 2≥32 \ge 3 no discarded {1}\{1\} 1
4 [3,6)[3,6) 3≥33 \ge 3 yes chosen {1,4}\{1,4\} 4 (fg=6f_g = 6)
5 [5,7)[5,7) 5≥65 \ge 6 no discarded {1,4}\{1,4\} 4
6 [7,8)[7,8) 7≥67 \ge 6 yes chosen {1,4,6}\{1,4,6\} 6

The clean-up after choosing a1a_1 removes a2a_2 and a3a_3 (they start before f1=3f_1 = 3): the first activity of the residual subinstance is a4a_4, since s4=3≥f1=3s_4 = 3 \ge f_1 = 3. The result has 3 activities, the maximum ({a1,a5,a6}\{a_1, a_5, a_6\} is also optimal).

Why the clean-up may be limited. It removes only the incompatible activities that immediately follow a1a_1, not all those incompatible with a1a_1. This does not compromise correctness: an incompatible activity not removed will be incompatible with some later greedy choice and discarded then. Example with (3,5),(4,6),(5,7),(4,8),(7,9)(3,5), (4,6), (5,7), (4,8), (7,9): after choosing a1=[3,5)a_1 = [3,5) the clean-up removes a2a_2 (4<54 < 5) and stops at a3=[5,7)a_3 = [5,7); the residual {a3,a4,a5}\{a_3, a_4, a_5\} still contains a4=[4,8)a_4 = [4,8), incompatible with a1a_1, but a3a_3 is chosen and discards a4a_4 (4<74 < 7); the result is {a1,a3,a5}\{a_1, a_3, a_5\}, optimal. The effect is a single linear scan.

Correctness

Notation: Si={ai,…,an}S_i = \{a_i, \dots, a_n\} (suffix), g(i)=min⁡{j>i:sj≥fi}g(i) = \min\{j > i : s_j \ge f_i\} (with Sg(i)=∅S_{g(i)} = \emptyset if none exists), opt(i)\mathrm{opt}(i) the maximum cardinality of a mutually compatible subset of SiS_i, opt(n+1)=0\mathrm{opt}(n+1) = 0.

Greedy choice property. SiS_i has an optimal solution containing aia_i.

Proof (exchange). Let A^\hat A be optimal for SiS_i. If ai∈A^a_i \in \hat A put A⋆=A^A^\star = \hat A. Otherwise let aha_h be the activity of A^\hat A of minimum index; since ai∉A^a_i \notin \hat A, h>ih > i. Put A⋆=(A^∖{ah})∪{ai},∣A⋆∣=∣A^∣.A^\star = (\hat A \setminus \{a_h\}) \cup \{a_i\}, \qquad |A^\star| = |\hat A| . We must show A⋆A^\star is feasible, i.e. aia_i is compatible with every aj∈A^∖{ah}a_j \in \hat A \setminus \{a_h\}. Since aja_j and aha_h are together in A^\hat A they are compatible: sj≥fhs_j \ge f_h or sh≥fjs_h \ge f_j. The second is impossible: it would give fj≤sh<fh≤fjf_j \le s_h < f_h \le f_j (the last inequality because j>hj > h and the order is by finish). So sj≥fhs_j \ge f_h and by the order fi≤fh≤sj,f_i \le f_h \le s_j , so aja_j starts after aia_i finishes: compatible. □\square

Optimal substructure property. opt(i)=1+opt(g(i))\mathrm{opt}(i) = 1 + \mathrm{opt}(g(i)).

Proof. (≤\le) By the greedy choice property there is an optimal AA of SiS_i with ai∈Aa_i \in A. Every aj∈A∖{ai}a_j \in A \setminus \{a_i\} is compatible with aia_i and has fj≥fif_j \ge f_i, so sj≥fis_j \ge f_i (the other alternative si≥fjs_i \ge f_j would give fj≤si<fif_j \le s_i < f_i). An activity with sj≥fis_j \ge f_i has j>ij > i, hence j≥g(i)j \ge g(i) by minimality: A∖{ai}⊆Sg(i)A \setminus \{a_i\} \subseteq S_{g(i)} and is compatible, so ∣A∣−1≤opt(g(i))|A| - 1 \le \mathrm{opt}(g(i)).

(≥\ge) Let BB be optimal for SgS_g, g=g(i)g = g(i). Not every solution of SgS_g will do: it may contain activities incompatible with aia_i (like a4a_4 above). By the greedy choice property applied to SgS_g, choose an optimal BB containing aga_g. Every other aj∈Ba_j \in B is compatible with aga_g and has j>gj > g, so sj≥fg>sg≥fis_j \ge f_g > s_g \ge f_i; also aga_g has sg≥fis_g \ge f_i by definition of gg. So {ai}∪B\{a_i\} \cup B is feasible and opt(i)≥1+opt(g)\mathrm{opt}(i) \ge 1 + \mathrm{opt}(g). □\square

Theorem. REC_GREEDY_SEL(s,f,i)\mathrm{REC\_GREEDY\_SEL}(s, f, i) returns a feasible solution of SiS_i of cardinality opt(i)\mathrm{opt}(i).

Proof. Induction on n−i+1n - i + 1. Base: i>ni > n, returns ∅\emptyset, opt=0\mathrm{opt} = 0. Step: the algorithm returns {ai}∪R\{a_i\} \cup R with R=REC_GREEDY_SEL(s,f,g(i))R = \mathrm{REC\_GREEDY\_SEL}(s, f, g(i)) (the clean-up loop computes exactly g(i)g(i)). By induction RR is feasible in Sg(i)S_{g(i)} with opt(g(i))\mathrm{opt}(g(i)) elements; its first element is aga_g and the others start after fgf_g, so all start after fif_i and {ai}∪R\{a_i\} \cup R is feasible, with cardinality 1+opt(g(i))=opt(i)1 + \mathrm{opt}(g(i)) = \mathrm{opt}(i). □\square

The iterative algorithm computes the same indices (it compares each activity with the last chosen one and, by transitivity of the increasing finish times, with all earlier ones).

Greedy choices that do not work

Other choices look reasonable but are wrong; one counterexample each suffices.

Strategy Instance What happens
shortest duration [0,5),[4,6),[5,10)[0,5), [4,6), [5,10) picks [4,6)[4,6) (duration 2), incompatible with both others: 1 activity, while {[0,5),[5,10)}\{[0,5),[5,10)\} has 2
earliest start [0,10),[1,2),[3,4)[0,10), [1,2), [3,4) picks [0,10)[0,10) and blocks everything: 1 against 2
fewest incompatibilities 11 activities: A [0,4)A\,[0,4), B [5,9)B\,[5,9), C [10,14)C\,[10,14), D [15,19)D\,[15,19), S [8,11)S\,[8,11), L1 [2,6)L_1\,[2,6), L2 [3,7)L_2\,[3,7), L3 [3,6)L_3\,[3,6), R1 [12,16)R_1\,[12,16), R2 [13,17)R_2\,[13,17), R3 [12,17)R_3\,[12,17) SS has 2 incompatibilities (with BB and CC), all others at least 3: the choice falls on SS and at most 3 activities result; the optimum {A,B,C,D}\{A, B, C, D\} has 4

The symmetric rule works: sorting by non-increasing start and choosing the activity that starts last, with the same kind of clean-up, mirrors the proof above.

Beware of weights. If each activity has a weight and the sum of weights is maximized, the earliest-finish greedy is not enough ([0,10)[0,10) with weight 100 against [0,5),[5,10)[0,5), [5,10) with weight 1 each): dynamic programming is needed.

Typical exam questions

  1. For s=(2,1,2,3,5,7)s = (2,1,2,3,5,7), f=(3,5,6,6,7,8)f = (3,5,6,6,7,8), what is the index of the first activity of the residual subinstance after the first greedy choice and clean-up? Answer: greedy choice a1=[2,3)a_1 = [2,3); a2a_2 (1<31 < 3) and a3a_3 (2<32 < 3) are removed, a4a_4 has s4=3≥f1=3s_4 = 3 \ge f_1 = 3: index 4.
  2. Which two properties ensure the correctness of a greedy algorithm and how are they proved? Answer: greedy choice (an optimum containing it exists: exchange from an optimum without worsening the cost) and optimal substructure (contradiction with cut-and-paste); correctness follows by induction on the size.
  3. Why is sorting by finish time crucial? Give a counterexample for "shortest duration". Answer: the exchange uses fi≤fh≤sjf_i \le f_h \le s_j, which needs the finish order; counterexample [0,5),[4,6),[5,10)[0,5), [4,6), [5,10).

Versione ripasso

  • From DP to greedy: in DP each choice is deliberate (many subinstances solved first); in greedy the locally best choice is made at once, then the instance is cleaned up (clean-up) and a single residual subinstance remains.
  • Consequences: linear subinstance space, no repeated subinstances (memoization useless); tail recursion becomes a loop; simple, fast, often linear algorithms. It does not always work: good cases are minimum spanning trees, shortest paths, 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 →.
  • Code first, proof later. Correctness needs two properties: (1) greedy choice, an optimum contains the greedy choice (start from an optimum A^\hat A, exchange to A⋆A^\star without worsening cost); (2) optimal substructure, an optimum contains the greedy choice plus an optimum of the residual (contradiction and cut-and-paste).
  • Correctness scheme: induction on size; base the empty instance; step: by (1) and (2) an optimum made of greedy choice plus an optimum of the residual exists, the algorithm returns greedy choice plus the residual solution, optimal by induction, hence of the same cost. To refute a strategy, a counterexample suffices.
  • Activity selection: aj=[sj,fj)a_j = [s_j, f_j); compatible if sj≥fis_j \ge f_i or si≥fjs_i \ge f_j (touching endpoints are fine). Find a mutually compatible subset of maximum cardinality. Sort by finish time (O(nlog⁡n)O(n \log n)).
  • Choice and clean-up: greedy choice a1a_1 (earliest finish); clean-up removes the next ones with sj<f1s_j < f_1 up to g=min⁡{j:sj≥f1}g = \min\{j : s_j \ge f_1\}; residual is the suffix ag..ana_g..a_n. The clean-up is limited: an incompatible one not removed (e.g. a4=[4,8)a_4 = [4,8) in (3,5),(4,6),(5,7),(4,8),(7,9)(3,5),(4,6),(5,7),(4,8),(7,9)) is discarded by a later choice.
  • Iterative code: A <- {1}; g <- 1; for i <- 2 to n: if s[i] >= f[g] then A <- A U {i}; g <- i. Exactly n−1n-1 comparisons, Θ(n)\Theta(n). In REC_GREEDY_SEL the while tests j <= n first.
  • Example: s=(2,1,2,3,5,7)s = (2,1,2,3,5,7), f=(3,5,6,6,7,8)f = (3,5,6,6,7,8): a2,a3a_2, a_3 discarded (1,2<31, 2 < 3), a4a_4 chosen (3≥33 \ge 3), a5a_5 discarded (5<65 < 6), a6a_6 chosen (7≥67 \ge 6): {a1,a4,a6}\{a_1, a_4, a_6\}, optimal. The residual after a1a_1 starts at a4a_4.
  • Greedy choice (proof): A^\hat A optimal, aha_h of minimum index, A⋆=A^∖{ah}∪{ai}A^\star = \hat A \setminus \{a_h\} \cup \{a_i\}. For any other aj∈A^a_j \in \hat A: the alternative sh≥fjs_h \ge f_j would give fj≤sh<fh≤fjf_j \le s_h < f_h \le f_j, impossible, so sj≥fhs_j \ge f_h and fi≤fh≤sjf_i \le f_h \le s_j: A⋆A^\star is feasible with the same cardinality.
  • Substructure (proof): opt(i)=1+opt(g(i))\mathrm{opt}(i) = 1 + \mathrm{opt}(g(i)). ≤\le: an optimum A∋aiA \ni a_i has A∖{ai}⊆Sg(i)A \setminus \{a_i\} \subseteq S_{g(i)}, since sj≥fis_j \ge f_i implies j>ij > i hence j≥g(i)j \ge g(i). ≥\ge: take an optimum of SgS_g containing aga_g (not any one, it might have activities incompatible with aia_i); the others start after fg>sg≥fif_g > s_g \ge f_i, so {ai}∪B\{a_i\} \cup B is feasible.
  • Wrong strategies (counterexamples): shortest duration ([0,5),[4,6),[5,10)[0,5), [4,6), [5,10): 1 against 2), earliest start ([0,10),[1,2),[3,4)[0,10), [1,2), [3,4)), fewest incompatibilities (11 activities: optimum 4, greedy gets 3). The symmetric version (non-increasing start order) is correct. With weights greedy is not enough: use DP.
  • Typical mistakes: not sorting by finish; using sj≤fis_j \le f_i (excluding compatibility at a point); taking any optimum of the residual without imposing its greedy choice; skipping the feasibility check of the exchange; miscounting comparisons (n−1n-1, not nn).

Teoria collegata