Salta al contenuto
Note per Studenti Greedy Exercises - CD Tracks, Shortest-First Scheduling and Boxing Report

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

  1. Greedy choice: the first choice, the one that looks locally best, made without solving subinstances.
  2. Clean-up and residual subinstance: what is removed after the choice; what remains is one subinstance of the same problem.
  3. 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.
  4. 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.
  5. 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.
  6. 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 d1..dnd_1..d_n in fixed order, capacity dmaxd_{max} times t1..tnt_1..t_n of nn jobs weights p1≤⋯≤pnp_1 \le \dots \le p_n in (0,1](0,1]
Goal minimum number of CDs minimum cumulative waiting time minimum number of boxes (at most 2 objects, weight ≤1\le 1)
Greedy choice the longest prefix that fits on the first CD the job of minimum duration first {on}\{o_n\} if n=1n = 1 or p1+pn>1p_1 + p_n > 1, else {o1,on}\{o_1, o_n\}
Clean-up none; residual = suffix none; residual = other n−1n-1 jobs none; residual = {o1..on−1}\{o_1..o_{n-1}\} or {o2..on−1}\{o_2..o_{n-1}\}
Greedy choice (proof) move cs+1..cgc_{s+1}..c_g from CD2CD_2 to CD1CD_1 swap the first job with a shorter one swap two boxes, checking ps+pt≤1p_s + p_t \le 1
Substructure opt(C1..n)=1+opt(Cg+1..n)\mathrm{opt}(C_{1..n}) = 1 + \mathrm{opt}(C_{g+1..n}) Tsum=(n−1) tπ(1)+TsumRT_{sum} = (n-1)\,t_{\pi(1)} + T_{sum}^{R} opt(O)=1+opt(OR)\mathrm{opt}(O) = 1 + \mathrm{opt}(O_R)
Cost Θ(n)\Theta(n) O(nlog⁡n)O(n \log n) (sorting) Θ(n)\Theta(n) (weights already sorted)

Exercise 1: compact burning of tracks on CDs

Statement. For n>0n > 0 there is a string of songs C=⟨c1,…,cn⟩C = \langle c_1, \dots, c_n \rangle, the ii-th of duration did_i. Songs are burned on a sequence of CDs CD1,…,CDkCD_1, \dots, CD_k 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 CC; (2) the total duration on each CD does not exceed dmaxd_{max}. Assume di≤dmaxd_i \le d_{max} for all ii. A feasible solution is a sequence 0=n0<n1<⋯<nk=n0 = n_0 < n_1 < \dots < n_k = n: CDiCD_i holds the substring Cni−1+1..niC_{n_{i-1}+1..n_i}. Minimize kk.

Step 1: greedy choice. Fill the first CD with as many songs as possible: put on CD1CD_1 the songs of the longest prefix C1..gC_{1..g} with ∑j=1gdj≤dmax\sum_{j=1}^{g} d_j \le d_{max} (n1=gn_1 = g), then continue with the rest.

  • Clean-up: none. The residual is the suffix Cg+1..nC_{g+1..n}, with the same dmaxd_{max}. If g=ng = n then k=1k = 1 and the residual is empty (zero CDs).
  • The residual has at least one song less (g≥1g \ge 1 since d1≤dmaxd_1 \le d_{max}), 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 NN holds the ends n0,n1,…n_0, n_1, \dots.

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 CDs

Feasibility. At the start of each iteration sumd is the duration of the songs cN[k]+1,…,ci−1c_{N[k]+1}, \dots, c_{i-1} of the CD under construction and is ≤dmax\le d_{max}: initially d1≤dmaxd_1 \le d_{max}; the else branch adds did_i only if the total stays ≤dmax\le d_{max}; the then branch restarts from di≤dmaxd_i \le d_{max}.

Complexity. The loop runs n−1n-1 times, each with one comparison and one addition at most: n−1n-1 comparisons, so Θ(n)\Theta(n), with O(1)O(1) auxiliary space besides the output.

Worked example. d=(4,3,5,2,6,1,4,7)d = (4, 3, 5, 2, 6, 1, 4, 7) minutes, dmax=10d_{max} = 10, n=8n = 8.

ii did_i sumd before sumd + d_i ≤10\le 10? action
start sumd =4= 4, k=0k=0
2 3 4 7 yes sumd =7= 7
3 5 7 12 no k=1k=1, N[1]=2N[1] = 2, sumd =5= 5
4 2 5 7 yes sumd =7= 7
5 6 7 13 no k=2k=2, N[2]=4N[2] = 4, sumd =6= 6
6 1 6 7 yes sumd =7= 7
7 4 7 11 no k=3k=3, N[3]=6N[3] = 6, sumd =4= 4
8 7 4 11 no k=4k=4, N[4]=7N[4] = 7, sumd =7= 7

Finally N[5]=8N[5] = 8: N=(0,2,4,6,7,8)N = (0, 2, 4, 6, 7, 8), so 55 CDs: {4,3}\{4,3\}, {5,2}\{5,2\}, {6,1}\{6,1\}, {4}\{4\}, {7}\{7\}.

Step 3: greedy choice property. There is an optimal solution in which CD1CD_1 holds c1,…,cgc_1, \dots, c_g (n1=gn_1 = g).

Proof (cut-and-paste). Let S∗S^\ast be optimal with 0=n0∗<n1∗<⋯<nk∗=n0 = n_0^\ast < n_1^\ast < \dots < n_k^\ast = n. If n1∗=gn_1^\ast = g we are done. Otherwise n1∗=s≠gn_1^\ast = s \ne g; since gg is the maximum number of songs fitting on a CD from the first, s<gs < g.

Build S^\hat S by moving songs cs+1,…,cgc_{s+1}, \dots, c_g from CD2CD_2 to CD1CD_1. Checks:

  1. CD1CD_1 is feasible: it holds c1,…,cgc_1, \dots, c_g, of total duration ≤dmax\le d_{max} by definition of gg.
  2. CD2CD_2 does not become empty. It must be n2∗>gn_2^\ast > g: otherwise all songs of CD2CD_2 would be among cs+1,…,cgc_{s+1}, \dots, c_g and the move would empty it, giving a solution with one CD less than S∗S^\ast, contradicting optimality.
  3. CD2CD_2 is feasible: it holds a subset of its previous songs.
  4. Order: the concatenation still presents the songs in the original order.

The new sequence has the same number kk of CDs as S∗S^\ast: it is optimal and contains the greedy choice. □\square

Step 4: optimal substructure. If S^\hat S is optimal and contains the greedy choice, then CD2,…,CDkCD_2, \dots, CD_k form an optimal solution of the residual Cg+1..nC_{g+1..n}.

Proof. There is no clean-up. The arrangement on CD2,…,CDkCD_2, \dots, CD_k is a feasible solution of Cg+1..nC_{g+1..n} using k−1k - 1 CDs. If it were not optimal, a solution of the residual with fewer than k−1k - 1 CDs, composed with the greedy choice, would give a solution of the original instance with fewer than kk CDs, contradicting the optimality of S^\hat S. □\square

In formula: opt(C1..n)=1+opt(Cg+1..n)\mathrm{opt}(C_{1..n}) = 1 + \mathrm{opt}(C_{g+1..n}).

Step 5: correctness by induction on nn. Base: n=0n = 0, zero CDs. Step: MIN_NUM_CD puts c1,…,cgc_1, \dots, c_g on CD1CD_1 and proceeds on the residual, optimally by induction; the number of CDs is 1+opt(Cg+1..n)=opt(C1..n)1 + \mathrm{opt}(C_{g+1..n}) = \mathrm{opt}(C_{1..n}).

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 MM. There are nn jobs {J1,…,Jn}\{J_1, \dots, J_n\} with execution times tit_i. A schedule is a bijection π:{1,…,n}→{1,…,n}\pi : \{1, \dots, n\} \to \{1, \dots, n\}, with jobs executed in the order ⟨Jπ(1),…,Jπ(n)⟩\langle J_{\pi(1)}, \dots, J_{\pi(n)} \rangle. Under π\pi the waiting time of the ii-th executed job is the sum of the times of the jobs run before, Tiπ=∑j=1i−1tπ(j)(T1π=0),T_i^\pi = \sum_{j=1}^{i-1} t_{\pi(j)} \qquad (T_1^\pi = 0), and the goal is to minimize the cumulative waiting time Tsumπ=∑i=1nTiπT_{sum}^\pi = \sum_{i=1}^{n} T_i^\pi. Prove the Shortest-Job First (SJF) property: for any optimal schedule π∗\pi^\ast, tπ∗(1)=min⁡{ti}t_{\pi^\ast(1)} = \min\{t_i\}. Then give the algorithm and optimal substructure.

Step 1: a formula for the cost. The time tπ(j)t_{\pi(j)} of the job in position jj appears in the waiting time of all jobs executed after it, i.e. positions j+1,…,nj+1, \dots, n, which are n−jn - j. So Tsumπ=∑i=1n∑j=1i−1tπ(j)=∑j=1n−1(n−j) tπ(j).T_{sum}^\pi = \sum_{i=1}^{n} \sum_{j=1}^{i-1} t_{\pi(j)} = \sum_{j=1}^{n-1} (n - j)\, t_{\pi(j)} . The first job has weight n−1n - 1, the second n−2n - 2, and so on: jobs run first count more, which is why short ones should go first.

Example. t=(3,1,4,2)t = (3, 1, 4, 2). In order J1,J2,J3,J4J_1, J_2, J_3, J_4 the waits are 0,3,4,80, 3, 4, 8, Tsum=15T_{sum} = 15 (formula: 3⋅3+2⋅1+1⋅4=153 \cdot 3 + 2 \cdot 1 + 1 \cdot 4 = 15). In order J2,J4,J1,J3J_2, J_4, J_1, J_3 (durations 1,2,3,41, 2, 3, 4) the waits are 0,1,3,60, 1, 3, 6 and Tsum=10T_{sum} = 10.

Step 2: the SJF property. Proof by contradiction with exchange. Let π∗\pi^\ast be optimal and suppose it violates SJF: π∗(1)=r\pi^\ast(1) = r and JrJ_r is not of minimum duration. Then there is a shorter job JsJ_s, ts<trt_s < t_r, executed in a position k>1k > 1: π∗(k)=s\pi^\ast(k) = s.

Build π^\hat\pi by swapping JrJ_r and JsJ_s: π^(1)=s\hat\pi(1) = s, π^(k)=r\hat\pi(k) = r, π^(i)=π∗(i)\hat\pi(i) = \pi^\ast(i) otherwise. Compare waits:

  • i=1i = 1: both 00.
  • 1<i≤k1 < i \le k: the sum ∑j<itπ^(j)\sum_{j<i} t_{\hat\pi(j)} contains position 11 but not position kk. Compared with π∗\pi^\ast it has tst_s in place of trt_r: Tiπ^=Tiπ∗−tr+ts<Tiπ∗.T_i^{\hat\pi} = T_i^{\pi^\ast} - t_r + t_s < T_i^{\pi^\ast}.
  • i>ki > k: the sum contains both positions, swapped: same addends, so Tiπ^=Tiπ∗T_i^{\hat\pi} = T_i^{\pi^\ast}.

The decrease is tr−tst_r - t_s for each of the indices i=2,…,ki = 2, \dots, k, i.e. k−1k - 1 times: Tsumπ^=Tsumπ∗−(k−1)(tr−ts)<Tsumπ∗,T_{sum}^{\hat\pi} = T_{sum}^{\pi^\ast} - (k-1)(t_r - t_s) < T_{sum}^{\pi^\ast}, contradicting optimality. □\square

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 π∗(1)\pi^\ast(1) 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 n−1n-1 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 O(nlog⁡n)O(n \log n).

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 pi

Optimal substructure. Let π∗\pi^\ast be optimal and πR∗\pi_R^\ast the schedule of the following jobs (the residual). The wait of each residual job under πR∗\pi_R^\ast is that under π∗\pi^\ast minus tπ∗(1)t_{\pi^\ast(1)}. The residual has n−1n-1 jobs, so Tsumπ∗=(n−1) tπ∗(1)+TsumπR∗.T_{sum}^{\pi^\ast} = (n - 1)\, t_{\pi^\ast(1)} + T_{sum}^{\pi_R^\ast} . The first term does not depend on πR∗\pi_R^\ast: if πR∗\pi_R^\ast were not optimal, replacing it with a better schedule (cut-and-paste) would give a lower cost than Tsumπ∗T_{sum}^{\pi^\ast}. So πR∗\pi_R^\ast is optimal for the residual.

Correctness. By induction on the number of jobs: for n=0n = 0 the empty schedule is optimal; for n≥1n \ge 1 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 (n−1)tmin⁡+opt(residual)=opt(n-1) t_{\min} + \mathrm{opt}(\text{residual}) = \mathrm{opt}.

A second reading. In Tsumπ=∑j(n−j) tπ(j)T_{sum}^\pi = \sum_j (n-j)\, t_{\pi(j)} the decreasing weights n−1,n−2,…,0n-1, n-2, \dots, 0 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 O={o1,…,on}O = \{o_1, \dots, o_n\} be objects of weights pip_i, normalized in (0,1](0, 1] and sorted: 0<p1≤p2≤⋯≤pn0 < p_1 \le p_2 \le \dots \le p_n. A boxing of OO is a partition into m≤nm \le n non-empty subsets (boxes). It is a (2,1)-boxing if every box has ∣Bi∣≤2|B_i| \le 2 and total weight ≤1\le 1. Find a (2,1)-boxing of minimum cardinality with a greedy approach.

Example. With p=(0.2,0.6,0.7)p = (0.2, 0.6, 0.7) there are three (2,1)-boxings: all singletons, {{0.2,0.6},{0.7}}\{\{0.2, 0.6\}, \{0.7\}\} and {{0.2,0.7},{0.6}}\{\{0.2, 0.7\}, \{0.6\}\} (the pair 0.6+0.70.6 + 0.7 weighs 1.3>11.3 > 1). The last two are optimal, with 2 boxes.

Step 1: greedy choice. Look at the heaviest object ono_n, the hardest to place. Cases:

  1. n=1n = 1: B1={on}B_1 = \{o_n\}.
  2. n>1n > 1 and p1+pn>1p_1 + p_n > 1: even paired with the lightest object o1o_1 the weight exceeds 11, so with any other object it would: ono_n goes alone, B1={on}B_1 = \{o_n\}.
  3. n>1n > 1 and p1+pn≤1p_1 + p_n \le 1: make the box B1={o1,on}B_1 = \{o_1, o_n\}, pairing the heaviest with the lightest.

In case 3 the choice is "reckless": it settles for pairing ono_n with o1o_1 even though a heavier object might still fit with ono_n, wasting capacity. The greedy choice property will show nothing is lost.

Clean-up: none. The residual ORO_R is: cases 1 and 2, {o1,…,on−1}\{o_1, \dots, o_{n-1}\}; case 3, {o2,…,on−1}\{o_2, \dots, o_{n-1}\}. It is still sorted and satisfies the same hypotheses.

Step 2: algorithm. Indices first and last delimit the residual {ofirst,…,olast}\{o_{first}, \dots, o_{last}\}.

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 B

last always decreases, first increases only in case 3.

It returns a (2,1)-boxing. Each iteration boxes olasto_{last} and, in case 3, also ofirsto_{first}, then excludes them; the loop ends with first>lastfirst > last, after boxing every object in exactly one box. Boxes have one or two objects and total weight ≤1\le 1.

Complexity. last decreases by 11 per iteration, so iterations are at most nn and at least ⌈n/2⌉\lceil n/2 \rceil. Each does one sum and one comparison: Θ(n)\Theta(n) (plus O(nlog⁡n)O(n \log n) if weights are not sorted).

Worked example. Weights (0.10,0.20,0.30,0.45,0.60,0.70,0.85,0.95)(0.10, 0.20, 0.30, 0.45, 0.60, 0.70, 0.85, 0.95), n=8n = 8.

iter. first, last pfirst+plastp_{first} + p_{last} case box after (first, last)
1 1, 8 0.10+0.95=1.05>10.10 + 0.95 = 1.05 > 1 2 {o8}\{o_8\} 1, 7
2 1, 7 0.10+0.85=0.95≤10.10 + 0.85 = 0.95 \le 1 3 {o1,o7}\{o_1, o_7\} 2, 6
3 2, 6 0.20+0.70=0.90≤10.20 + 0.70 = 0.90 \le 1 3 {o2,o6}\{o_2, o_6\} 3, 5
4 3, 5 0.30+0.60=0.90≤10.30 + 0.60 = 0.90 \le 1 3 {o3,o5}\{o_3, o_5\} 4, 4
5 4, 4 first=lastfirst = last 1 {o4}\{o_4\} 4, 3 (end)

Result: 55 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 ono_n is alone, so every boxing contains {on}\{o_n\}.

Case 3 (greedy box {o1,on}\{o_1, o_n\}, p1+pn≤1p_1 + p_n \le 1). Let B∗B^\ast be an optimal (2,1)-boxing.

  • If o1o_1 and ono_n are in the same box, it is exactly {o1,on}\{o_1, o_n\}.
  • Otherwise they are in distinct boxes B1∋o1B_1 \ni o_1 and B2∋onB_2 \ni o_n. Build B^=(B∗∖{B1,B2})∪{{o1,on}, (B1∪B2)∖{o1,on}}.\hat B = \big(B^\ast \setminus \{B_1, B_2\}\big) \cup \big\{\{o_1, o_n\},\ (B_1 \cup B_2) \setminus \{o_1, o_n\}\big\}.

Checks:

  1. Number of boxes. ∣B^∣≤∣B∗∣|\hat B| \le |B^\ast|; if the second new box were empty there would be one box less, contradicting optimality, so ∣B^∣=∣B∗∣|\hat B| = |B^\ast|.
  2. The greedy box is feasible by hypothesis.
  3. The second box has at most two objects (B1B_1 brings at most one besides o1o_1, B2B_2 at most one besides ono_n). If it has one, the weight constraint holds. If two, say os∈B1o_s \in B_1, ot∈B2o_t \in B_2: ps≤pnp_s \le p_n (ono_n is the heaviest) and pt+pn≤1p_t + p_n \le 1 (constraint on B2B_2), i.e. pt≤1−pnp_t \le 1 - p_n. Summing, ps+pt≤pn+(1−pn)=1.p_s + p_t \le p_n + (1 - p_n) = 1 .
  4. Other objects stay in their boxes.

So B^\hat B is a (2,1)-boxing of the same cardinality as B∗B^\ast, hence optimal, and contains the greedy choice. □\square

Step 4: optimal substructure. If B^\hat B is optimal and contains the greedy choice, the other boxes B^R\hat B_R form an optimal (2,1)-boxing of ORO_R.

Proof. No clean-up. The boxes other than the greedy one contain exactly the objects of ORO_R and respect the constraints, so they are a feasible B^R\hat B_R. If it were not optimal, adding the greedy box to an optimal (2,1)-boxing of ORO_R would give a boxing of OO with fewer boxes than B^\hat B (cut-and-paste), contradicting its optimality. □\square

In formula opt(O)=1+opt(OR)\mathrm{opt}(O) = 1 + \mathrm{opt}(O_R), opt(∅)=0\mathrm{opt}(\emptyset) = 0.

Step 5: correctness by induction on nn. Base: n=0n = 0, 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 1+opt(OR)=opt(O)1 + \mathrm{opt}(O_R) = \mathrm{opt}(O).

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 [0,5),[4,6),[5,10)[0,5), [4,6), [5,10): picks [4,6)[4,6) 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

  1. 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.
  2. Prove that in every optimal schedule the first job has minimum duration. Answer: formula Tsum=∑j(n−j)tπ(j)T_{sum} = \sum_j (n-j) t_{\pi(j)}; swap JrJ_r (first, not minimum) with a shorter JsJ_s in position kk: waits Ti−tr+tsT_i - t_r + t_s for 2≤i≤k2 \le i \le k, unchanged for i>ki > k; the total drops by (k−1)(tr−ts)(k-1)(t_r - t_s).
  3. How many CDs for d=(4,3,5,2,6,1,4,7)d = (4,3,5,2,6,1,4,7) with dmax=10d_{max} = 10? Answer: 55 (greedy: {4,3},{5,2},{6,1},{4},{7}\{4,3\}, \{5,2\}, \{6,1\}, \{4\}, \{7\}).

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 ≤dmax\le d_{max} on the first CD; sumd restarts from did_i; Θ(n)\Theta(n). Proof: move cs+1..cgc_{s+1}..c_g from CD2CD_2 to CD1CD_1 (CD2CD_2 does not become empty, else the optimum would have a CD too many). Example d=(4,3,5,2,6,1,4,7)d = (4,3,5,2,6,1,4,7), dmax=10d_{max} = 10: 55 CDs, N=(0,2,4,6,7,8)N = (0,2,4,6,7,8). Greedy suffices because the order is fixed; with reordering it is bin packing.
  • Shortest-first: Tsumπ=∑j(n−j) tπ(j)T_{sum}^\pi = \sum_j (n-j)\, t_{\pi(j)}; sort by non-decreasing duration, O(nlog⁡n)O(n \log n). SJF holds for every optimum: swapping with a shorter job lowers the total by (k−1)(tr−ts)(k-1)(t_r - t_s). Tsum=(n−1) tπ(1)+TsumRT_{sum} = (n-1)\,t_{\pi(1)} + T_{sum}^R. Example t=(3,1,4,2)t = (3,1,4,2): 1515 in index order, 1010 sorted.
  • (2,1)-boxing: greedy box {on}\{o_n\} (n=1n=1 or p1+pn>1p_1 + p_n > 1) else {o1,on}\{o_1, o_n\}; indices first/last; Θ(n)\Theta(n), between ⌈n/2⌉\lceil n/2 \rceil and nn iterations. Proof: swap two boxes with ps≤pnp_s \le p_n and pt≤1−pnp_t \le 1 - p_n, so ps+pt≤1p_s + p_t \le 1. Example with 8 objects: 55 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.

Teoria collegata