Algorithms in Engineering - Mock Exam 1
Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.
In questa pagina 13
Mock exam built on the model of the written exams of the equivalent course in Italian (Algoritmi per l'Ingegneria, UniPD). The real test has two parts: a closed-answer questionnaire on the basics of the course (Part 1) and problems of design and analysis of an algorithm and of proof of a property (Part 2). The questionnaire of the real exams is not public: the number of questions, the points and the duration below are our proposal, drawn from the official sample questionnaires of the Italian course.
- Part 1 (10 points): Quiz 1-10, four options each, exactly one correct, 1 point each; only the answer is written, without working.
- Part 2 (22 points): Exercise 1 (11 points) and Exercise 2 (11 points).
- Total: 32 points. Duration: 2 hours and 30 minutes (proposal). No notes, books or calculators.
- Cost model, unless stated otherwise: only operations between scalars (sums, differences, products, comparisons between numbers) cost ; assignments, copies and index computations cost .
The quizzes and the exercises are new: they are not the ones of the official tests nor of the other mock exams. Every result was checked by running a program: the loop counts, the recurrences (evaluated by running them), the operation count of the FFT (by instrumenting the code) and the DFT values against the direct definition; for Exercise 1 the closure, the symmetry and the commutativity on 1000 random pairs of matrices up to order , the three-product algorithm against the matrix product, and the exact operation counts for ; for Exercise 2 the greedy algorithm against all the permutations on 3000 random instances with up to jobs, the substructure identity and the exchange step on every permutation. The correct letters of the quizzes are spread as A: 2, B: 2, C: 3, D: 3.
Quiz 1
An algorithm receives a positive integer written in binary on bits (so ) and computes with a loop that performs additions between integers, each of unit cost. Taking as size the number of bits of the input, the number of additions is:
- A. , linear in the size.
- B. , quadratic in the size.
- C. , exponential in the size.
- D. , logarithmic in the size.
Show the result
C.
Show the full solution
The cost is a function of the size of the instance, not of the value it represents (Computational Problems, Algorithms and Cost ModelA computational problem is a total, not necessarily single-valued relation between instances and solutions; an algorithm is a function from instances to solutions and solves the problem if its output is always related to its input. Correctness means agreement with the specification; complexity is the cost as a function of input size, by default in the worst case, with unit-cost instructions chosen meaningfully.Computational Problems, Algorithms and Cost Model →). Here the value lies between and , so the number of additions lies between and : it is , exponential in the number of bits. The same happens with trial division to test primality ( steps).
- A, B, D are false: they treat as if it were the size (" is linear") instead of its logarithm.
Typical mistake: answering "linear" because the loop is a single loop. It is linear in the value , not in the length of its encoding.
Quiz 2
How many times is the command x = x + 1 executed by the following fragment when ?
for i = 1 to n-1:
for j = i+1 to n:
for k = j to n:
x = x + 1- A.
- B.
- C.
- D.
Show the result
A. .
Show the full solution
The three loops count the triples with . Group them by : for each there are values of () and values of (). With : For : .
Second reading: the condition means with , i.e. a choice of distinct values out of : .
- B () counts the triples with strictly: it forgets that starts from .
- C () and D are results of wrong bounds.
Quiz 3
Let and for . What is ?
- A.
- B.
- C.
- D.
Show the result
D. .
Show the full solution
Recurrence tree (Recurrence Relations - Recursion Tree and General FormulaThe recurrence tree has the shape of the call tree of the worst instance and T(n) is the sum of the works of its nodes. For the family T(n) = s(n) T(f(n)) + w(n) with base T0 for n <= n0, counting nodes per level with the iterates of f and the level f*(n,n0) gives the closed formula T(n) = sum over levels of [product of s] w + [product of s] T0, proved by induction and applied to merge sort, Hanoi and square-root recurrences.Recurrence Relations - Recursion Tree and General Formula →): the node of size has work , every node has children of half size, the leaves (size ) cost .
| level | nodes | size | work per node | level work |
|---|---|---|---|---|
| 0 | ||||
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 (leaves) |
Total . Closed form: (check: , ; ).
- A is : the leaves were counted as free ().
- B is : the term was forgotten.
- C is : the work of the root was forgotten.
Quiz 4
Which of the following recurrences, with and a power of , has solution by the Master Theorem?
- A.
- B.
- C.
- D.
Show the result
B.
Show the full solution
| , | threshold | case | result | ||
|---|---|---|---|---|---|
| A | , | , regularity | 3 | ||
| B | , | 2 | |||
| C | , | 1 | |||
| D | , | , regularity | 3 |
The logarithmic factor appears only in the balanced case (Case 2): every level of the tree has the same work and there are levels.
Quiz 5
The product of two matrices is computed with the hybrid algorithm: if it uses the iterative product, which performs operations between scalars; if it makes one step of Strassen's algorithm, i.e. recursive calls on matrices of order plus operations between scalars for the divisions and the recombinations. How many operations between scalars does it perform for and ?
- A.
- B.
- C.
- D.
Show the result
C. .
Show the full solution
The recursion tree is cut at size (Hybrid AlgorithmsHybridization combines two algorithms for the same problem so the result has the asymptotics of the better one and, if possible, lower constants. Choosing the algorithm only by the starting size (STUPID_HYBRID) does not help; changing the base case of the recursion (H_MUL: iterative product for n <= n0 at every leaf of Strassen's tree) gives cost n^(log2 7)(2n0+5)/n0^(log2 7 - 2) - 6n^2, minimal for n0 = 8 with leading constant about 3.92.Hybrid Algorithms →, Strassen's AlgorithmStrassen computes the n x n product with 7 recursive calls instead of 8, using 10 matrix additions in Divide and 8 in Conquer: T(n) = 7T(n/2) + (9/2)n^2, Theta(n^(log2 7)) with exact solution 7n^(log2 7) - 6n^2. Its leading constant 7 is more than three times that of the iterative algorithm (2), so Strassen beats it only from n = 655 (from 1024 for powers of two).Strassen's Algorithm →): the internal levels are (sizes ) and the leaves have size .
- Leaves: leaves, each costing : .
- Internal levels: level has nodes of size and work :
Total . With the closed form : .
- A is , the purely iterative algorithm (): the hybrid with is slightly cheaper.
- B is : the term was forgotten.
- D is pure Strassen (): .
Quiz 6
Pure Strassen's algorithm (recursion down to matrices, one scalar product at the leaves) is applied to two matrices of order . How many operations between scalars does it perform in total?
- A.
- B.
- C.
- D.
Show the result
A. .
Show the full solution
and (Strassen's AlgorithmStrassen computes the n x n product with 7 recursive calls instead of 8, using 10 matrix additions in Divide and 8 in Conquer: T(n) = 7T(n/2) + (9/2)n^2, Theta(n^(log2 7)) with exact solution 7n^(log2 7) - 6n^2. Its leading constant 7 is more than three times that of the iterative algorithm (2), so Strassen beats it only from n = 655 (from 1024 for powers of two).Strassen's Algorithm →: additions in Divide and in Conquer, i.e. operations on matrices of order , each costing ):
- ;
- .
Closed form: .
- B is the iterative product, : for small it is cheaper than Strassen ().
- D is : the additions of the top level were forgotten.
- C is : wrong depth of the recursion.
Quiz 7
What are the real part and the imaginary part of , where ?
- A. and
- B. and
- C. and
- D. and
Show the result
D. .
Show the full solution
Powers of repeat with period (DFT and Roots of UnityThe DFT of order n evaluates a polynomial with degree bound n at the n n-th roots of unity, y_i = p(w^i) with w = e^{2 pi i/n}; it is the product by the Fourier matrix F_n, an invertible Vandermonde matrix. The roots form a multiplicative group and satisfy three lemmas: cancellation (w_{dn}^{dk} = w_n^k, w_n^{n/2} = -1), halving (the squares of the n roots are the n/2 roots of order n/2, each twice) and summation (the sum of the powers of w^k is n if k is a multiple of n, 0 otherwise). Linear convolution theorem: (c|0) = DFT^{-1}{2n}(DFT{2n}(a|0) times DFT_{2n}(b|0)).DFT and Roots of Unity →): , so . By the cancellation lemma with , , : . In angles: .
- A is (), B is , C is .
Typical mistake: not reducing the exponent and getting the angle without removing the full turns ().
Quiz 8
Let . What is ?
- A.
- B.
- C.
- D.
Show the result
B. .
Show the full solution
- ;
- ;
- ;
- .
Check with the FFT split (Fast Fourier TransformThe FFT computes the DFT_n (n a power of two) by divide and conquer: split the coefficients by index parity, p(x) = p0(x^2) + x p1(x^2), and by the halving lemma two DFTs of order n/2 suffice; y_i = y0_i + w^i y1_i and y_{i+n/2} = y0_i - w^i y1_i. The recurrence T(n) = 2T(n/2) + 2n with T(1) = 0 has exact solution 2 n log2 n. The inverse has matrix F^{-1}_{ij} = w^{-ij}/n and is obtained with the FFT on negative powers (then dividing by n outside the recursion) or with a reversed DFT_n(y). LIN_CONV multiplies two polynomials with n coefficients in 12 n log2(2n) + 4n operations.Fast Fourier Transform →): even indices give , odd indices give ; then , , , . Since is real and symmetric, is real, with .
- D has the wrong sign on the odd components; C would be the DFT of a constant vector.
Quiz 9
In the FFT algorithm of the course each iteration of the final loop (the one that combines the two half-size results) performs operations between complex numbers: the product , a sum, a difference and the update of the current power of . How many operations between complex numbers does the algorithm perform in total on a vector of length ?
- A.
- B.
- C.
- D.
Show the result
C. .
Show the full solution
The loop has iterations, so the work of a node of size is and , (Fast Fourier TransformThe FFT computes the DFT_n (n a power of two) by divide and conquer: split the coefficients by index parity, p(x) = p0(x^2) + x p1(x^2), and by the halving lemma two DFTs of order n/2 suffice; y_i = y0_i + w^i y1_i and y_{i+n/2} = y0_i - w^i y1_i. The recurrence T(n) = 2T(n/2) + 2n with T(1) = 0 has exact solution 2 n log2 n. The inverse has matrix F^{-1}_{ij} = w^{-ij}/n and is obtained with the FFT on negative powers (then dividing by n outside the recursion) or with a reversed DFT_n(y). LIN_CONV multiplies two polynomials with n coefficients in 12 n log2(2n) + 4n operations.Fast Fourier Transform →). Every level of the tree costs in total and there are levels of internal nodes (the leaves cost nothing): . For : . Check by the Master Theorem: , , Case 2, (Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →).
- A is (one operation per pair of values).
- B is , the count with the powers of precomputed (one product and two sums per iteration).
- D is , the cost of evaluating the polynomial at the roots with Horner's rule.
Quiz 10
Let and for a power of . Which statement is true?
- A. By Case 1 of the Master Theorem, .
- B. By Case 2 of the Master Theorem, .
- C. By Case 3 of the Master Theorem, .
- D. The Master Theorem does not apply; unfolding the recurrence gives .
Show the result
D.
Show the full solution
The threshold is and (Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →). Case 1 needs and Case 2 needs : both false, because is larger than . Case 3 needs for some , but : the gap is only logarithmic, so Case 3 fails too. The theorem does not apply.
Unfolding with the general formula (Recurrence Relations - Recursion Tree and General FormulaThe recurrence tree has the shape of the call tree of the worst instance and T(n) is the sum of the works of its nodes. For the family T(n) = s(n) T(f(n)) + w(n) with base T0 for n <= n0, counting nodes per level with the iterates of f and the level f*(n,n0) gives the closed formula T(n) = sum over levels of [product of s] w + [product of s] T0, proved by induction and applied to merge sort, Hanoi and square-root recurrences.Recurrence Relations - Recursion Tree and General Formula →), : level has nodes of work , i.e. per level, and there are leaves of cost : Check: and the formula gives ; .
Applying Case 2 or Case 3 anyway (options B and C) gives the wrong order .
Exercise 1 (points 11)
A matrix of order , , with complex entries is called a Fibonacci-block matrix (FBM) if (any scalar), or and with and FBM of order . For example, an FBM of order is ; taking and one gets the FBM of order The cost model counts the operations between scalars (cost ); assignments and copies are free.
- (a) [3 points] Prove by induction on that the FBM of order are closed under sum, difference and product, that every FBM is symmetric and that two FBM of the same order commute.
- (b) [1 point] Prove that an FBM of order is determined by its first row, and give the exact number of operations needed to sum two FBM given by their first rows.
- (c) [3 points] The block formula of the product needs recursive products of matrices of order (besides sums). Design an algorithm
FB_MUL, which receives the first rows of two FBM and returns the first row of their product, with only recursive calls. Write the pseudocode and prove that it is correct. - (d) [3 points] Write the recurrence for the number of operations of
FB_MUL, solve it exactly with the general formula for recurrences, check the formula for , and give the order of growth with the Master Theorem. - (e) [1 point] Apply
FB_MULto the FBM of order with first rows and and say how many operations are performed. How many would the algorithm with recursive calls perform for ?
Show the result
(a) The FBM are closed under sum, difference, scalar multiple and product; they are symmetric and commutative. For , : with , .
(b) The first row of is , which determines : there are only free parameters. Sum of two FBM: exactly operations (sum of the first rows).
(c) , , ; then and . The first row of the product is .
(d) , ; (so , , ); (Case 1).
(e) , with operations. With recursive calls: , so operations for .
Show the full solution
(a) Closure, symmetry, commutativity. Let be the set of FBM of order . We prove by induction on the statement : for all , (i) ; (ii) , and ( a scalar) belong to ; (iii) and . The method is the one for the structured families (Structured Block Matrices - Reducing Recursive CallsFor recursively structured matrix families (ARB, SIR, RCA, supercirculant) the method is: count the free parameters (n, not n^2), write the block product, prove closure under sum, difference and product by induction, count the distinct block products, and reduce them with sums and differences (2 calls for SC and RCA, 3 for ARB and SIR). If the product leaves the family one cannot recurse on it, which is why one asks for a matrix-vector product instead.Structured Block Matrices - Reducing Recursive Calls →, Supercirculant and Circulant MatricesSupercirculant matrices (alternating recursive quadrants) have only n distinct values: sum in n operations, product in 4n log2 n + n with the trick (A1+A2)(B1+B2) and (A1-A2)(B1-B2) instead of 4 calls (Theta(n^2)); their eigenvalues are the Hadamard transform of the first row (FHT, n log2 n). Circulant matrices are polynomials in the rotation matrix R, their product is the cyclic convolution of the first rows, and the Fourier matrix diagonalizes them: product in O(n log n) with the FFT.Supercirculant and Circulant Matrices →): write the block product with the row-by-column rule and use the hypothesis on the blocks.
Base . Scalars: a matrix is symmetric, sums, products and multiples of scalars are scalars, and scalars commute.
Step. Assume and let , with . (Note that and are in by (ii), so the definition is consistent.)
(i) Symmetry. Transposing a block matrix transposes each block and exchanges the off-diagonal ones: , because , and are symmetric by hypothesis.
(ii) Sum, difference, multiple. , which has the form of an FBM with blocks and , in by hypothesis. The same holds for and .
(iii) Product. Block row-by-column product (fractal property of the product, Matrix Multiplication - Iterative and Recursive Block ProductCost model on n x n matrices (scalar operations, size n or N = n^2); sum in n^2 operations (optimal); iterative row-by-column product with exact cost 2n^3 - n^2; the fractal property of the block product proved on indices; recursive algorithm RMUL with T(n) = 8T(n/2) + n^2, Theta(n^3) and exact solution 2n^3 - n^2: it performs the same operations as the iterative one.Matrix Multiplication - Iterative and Recursive Block Product →); the order of the factors is kept:
- top-left: ;
- top-right: ;
- bottom-left: , the same sum as (same products, in the same order);
- bottom-right: .
So , where and are sums of products of FBM of order , hence in by (ii) and (iii) at order : is an FBM. For the commutativity compute in the same way: its blocks are and . By the commutativity at order , , , , , so and and .
Typical mistakes: checking only the sum and forgetting the product (the delicate part); checking that the bottom-left block equals the top-right one by assuming commutativity of blocks when it is not needed (here the two expressions coincide term by term); using the symmetry of without proving it for .
(b) First row. The first row of is the concatenation of the first rows of and . By induction on the first row determines the matrix: for the matrix is its only entry; for , gives and (its two halves), these give and by hypothesis and then . In other words, if is the number of free parameters, and (the block brings no new information), so and not .
Sum. By (a), (componentwise): exactly operations. Recursively, and , i.e. . Subtraction costs the same.
Why the algorithm works on first rows. If FB_MUL returned the whole matrix, it would have to build the block at each level, i.e. one more sum at every node, which breaks the count. With the first rows, the block is never needed: it is determined by and and is never computed.
(c) Three recursive calls. The block formula of (a) needs the four products , , , (and again, computed once). The trick is the one of Gauss for complex numbers and of Karatsuba (Structured Block Matrices - Reducing Recursive CallsFor recursively structured matrix families (ARB, SIR, RCA, supercirculant) the method is: count the free parameters (n, not n^2), write the block product, prove closure under sum, difference and product by induction, count the distinct block products, and reduce them with sums and differences (2 calls for SC and RCA, 3 for ARB and SIR). If the product leaves the family one cannot recurse on it, which is why one asks for a matrix-vector product instead.Structured Block Matrices - Reducing Recursive Calls →, model "Gauss"): put Then The factors and are FBM by (a), so all three products are products of two FBM of order and the recursion is possible.
FB_MUL(a, b) { a, b: first rows of two FBM of order n = 2^k }
n <- length(a)
if n = 1 then return [a[1] * b[1]]
* a = (a1 | a2), b = (b1 | b2): halves of length n/2 *
ap <- VSUM(a1, a2); bp <- VSUM(b1, b2) { DIVIDE: 2 sums of vectors of length n/2 }
U <- FB_MUL(a1, b1) { RECURSE: 3 calls }
V <- FB_MUL(a2, b2)
Z <- FB_MUL(ap, bp)
E <- VSUM(U, V); F <- VSUB(Z, U) { CONQUER: 2 operations on vectors of length n/2 }
return (E | F) { concatenation: first row of the product }(VSUM and VSUB are the componentwise sum and difference of two vectors of the same length , with operations.)
Correctness (induction on ). The statement is: FB_MUL returns the first row of when and . Base: , the product of two scalars. Step: , , , are the first rows of , , , ; by (b) ap and bp are the first rows of and . By the induction hypothesis , , are the first rows of , , . By the linearity of the first row, is the first row of and is the first row of . By (a) the first row of is .
(d) Recurrence and solution. The internal work of a node of size is: sums in Divide and operations in Conquer, each on vectors of length and cost : (the concatenation is free). So General formula (Recurrence Relations - Recursion Tree and General FormulaThe recurrence tree has the shape of the call tree of the worst instance and T(n) is the sum of the works of its nodes. For the family T(n) = s(n) T(f(n)) + w(n) with base T0 for n <= n0, counting nodes per level with the iterates of f and the level f*(n,n0) gives the closed formula T(n) = sum over levels of [product of s] w + [product of s] T0, proved by induction and applied to merge sort, Hanoi and square-root recurrences.Recurrence Relations - Recursion Tree and General Formula →) with , , , , , : level () has nodes of work , and there are leaves of cost : using . Check: ; (directly: ); (directly: ).
Master Theorem (Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →): , , , threshold . Since with , it is Case 1 (the leaves dominate): . This is much less than , the size of the matrix, because the matrix has only free parameters.
Typical mistakes: writing (counting the four operations at size instead of ); forgetting that and need a sum each; counting ; applying Case 2 because " is linear".
(e) Numerical example and comparison. is the first row of the matrix shown in the text; is that of . At the top level , , , , ap , bp (4 operations). The three recursive calls (each on length , cost ):
| call | result | |||||
|---|---|---|---|---|---|---|
Conquer: and . The first row of the product is . Check with the matrices: the first row of is and the whole product is again an FBM (blocks , and ). Operations: .
Four recursive calls. The algorithm that computes , , , and then ( operations) and ( operations) has and , so (Case 1 with threshold ). Comparison:
| , three calls | ||||||
| , four calls |
For : operations against . The three-call algorithm is never worse and wins from on; the gap grows as against .
Exercise 2 (points 11)
Scheduling with deadlines. A machine must execute jobs one after the other, without interruptions and without idle time, starting at time . The job needs a time (a positive integer) and has a deadline (an integer, not necessarily positive). A schedule is a bijection : the jobs are executed in the order . Under the completion time of the -th executed job is its lateness is (negative if the job finishes early), and the cost of the schedule is the maximum lateness We look for a schedule that minimizes . Example: for and , the order has completion times and latenesses , so .
- (a) [3 points] Give a greedy choice and the clean-up, and write the pseudocode of the resulting algorithm. Show with a counterexample that the rule "execute first the job with the shortest duration" is not optimal.
- (b) [4 points] Prove the greedy choice property: there is an optimal schedule that starts with the greedy choice.
- (c) [3 points] Prove the optimal substructure property and, by induction on , the correctness of the algorithm.
- (d) [1 point] Give the cost of the algorithm, and apply it to and , giving the schedule and its maximum lateness.
Show the result
(a) Greedy choice: a job of minimum deadline (earliest deadline first). Clean-up: none; the residual instance is formed by the other jobs, with deadlines (where is the chosen job). The algorithm sorts the jobs by non-decreasing deadline. Counterexample for the shortest job first: , : shortest first gives , earliest deadline first gives .
(b) If has minimum deadline and is in position of an optimal schedule, moving it to the front gives a schedule that is not worse. (There is an optimal schedule starting with ; not every optimal schedule does.)
(c) , with the residual instance.
(d) (sorting) plus steps of scan. For the example: order , completion times , latenesses , maximum lateness (shortest first would give ).
Show the full solution
(a) Greedy choice, clean-up, algorithm. The method is the one of the greedy exercises (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 →, 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 →): make the first choice immediately, clean up, and solve the residual instance.
- Greedy choice: execute first a job whose deadline is minimum (ties: any).
- Clean-up: none, because no job becomes incompatible. The residual instance consists of the other jobs; since they start at time and not at time , their deadlines are shifted: (this is why the deadlines are allowed to be negative: the residual has the same form as the original problem).
REC_EDF(J) { J: jobs with times t and deadlines d }
if J = {} then return <>
e <- a job of J with minimum deadline // greedy choice
J' <- { (t_j, d_j - t_e) : J_j in J, j != e } // residual instance
return <J_e> followed by REC_EDF(J')The recursion is a tail recursion. Since the shift is the same for all the remaining jobs, it does not change their order, so all the choices follow the order of the original deadlines and the algorithm is a sort:
EDF_SCHEDULE(t, d)
n <- t.len
sort the indices 1..n by non-decreasing d // O(n log n)
pi[1..n] <- the sorted indices
C <- 0; L <- -infinity // L = maximum lateness so far
for i <- 1 to n do
C <- C + t[pi[i]] // completion time of the i-th job
L <- max(L, C - d[pi[i]])
return (pi, L)The shortest job first is not optimal. Take , . Shortest first executes and then : completion times , latenesses and , so . Earliest deadline first executes and then : completion times , latenesses and , so . One instance is enough to disprove a greedy rule. (Also "least slack first" is wrong: with , it executes first, finishing at time with lateness , and then at time with lateness , while the order has latenesses and .)
(b) Greedy choice property. Claim: if has minimum deadline, there is an optimal schedule whose first job is .
Proof (exchange). Let be an optimal schedule, with completion times , and suppose that is in position (if there is nothing to prove). Build by moving to the front, leaving the others in the same relative order: . Compare the latenesses, calling the lateness of in (so ):
- . It now completes at (in it completes after the jobs before it and its own time). Its lateness is .
- The jobs in positions of . They are delayed by : the new completion time is (for the job in position ). Since for , the new completion time is at most . Together with (minimality of ):
- The jobs in positions . Before them are executed the same set of jobs as in , so their completion times, and latenesses, are unchanged.
Every lateness in is at most , hence ; by the optimality of , : is optimal and starts with .
Remark. The claim says "there is", not "every". In the example of (d) there are optimal schedules, and some of them start with (deadline ): for instance has the same maximum lateness . This is different from the shortest-job-first property of the scheduling that minimizes the waiting time, which holds for every optimum.
Typical mistakes: checking only and forgetting that the jobs it overtakes are delayed; not using to bound the latenesses of the delayed jobs; swapping with the first job instead of moving it (a swap also changes the completion times of all the jobs in between, and the argument does not close).
(c) Optimal substructure. Let be a job of minimum deadline, the residual instance (the other jobs with deadlines ) and the minimum maximum lateness. Claim:
Proof. Take any schedule of that starts with and let be the schedule of the other jobs, in the same order (a schedule of ). The job in position of completes at , where are the completion times in (which starts at time ). Its lateness is therefore So, exactly, where the first term is the lateness of (completing at ). The function is non-decreasing, so among the schedules starting with the minimum is obtained with an optimal for (cut-and-paste: if were not optimal for , replacing it with an optimal one would not increase ). Hence the best schedule starting with costs . By (b) some optimal schedule of starts with , so this value is .
(The cost is combined with a maximum, not with a sum as in the waiting-time problem; this is why the substructure is an equality of the form .)
Correctness of the algorithm (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 →): induction on the number of jobs. Base : the only schedule is optimal. Step : assume that the algorithm is correct on instances with jobs, in particular on . REC_EDF places first and then the schedule of , optimal by induction. By the identity above its maximum lateness is by the substructure property. The iterative algorithm makes the same choices, since the shift of the deadlines does not change their order.
(d) Cost and example. Sorting by deadline costs comparisons (for instance with merge sort, at most ); the loop does iterations, each with sum, difference and comparison, i.e. . In total , dominated by the sort.
Example , . Order by deadline: .
| position | job | completion time | lateness | ||
|---|---|---|---|---|---|
| 1 | |||||
| 2 | |||||
| 3 | |||||
| 4 | |||||
| 5 | |||||
| 6 |
The maximum lateness is (job ). The same schedule satisfies the substructure formula: after the residual has times for and deadlines shifted by : ; its best order has completion times and latenesses , so and . For comparison, the shortest job first (order , completion times ) gives latenesses , so .
Self-assessment grid
| Exercise | Points | What must be there for full marks | Typical mistakes |
|---|---|---|---|
| Quiz 1-10 | 10 (1 each) | Quiz 1: size is the number of bits, so . Quiz 2: with the correct bounds. Quiz 3: with the leaves counted. Quiz 4: the balanced case, . Quiz 5: with leaves and internal levels. Quiz 6: . Quiz 7: after reducing the exponent. Quiz 8: . Quiz 9: . Quiz 10: the Master Theorem does not apply, | value taken as size; not included in a loop; leaves forgotten; Case 3 with a logarithmic gap; exponent not reduced modulo ; sign errors in the DFT |
| 1 | 11 | (a) induction with base, closure of sum and product (the bottom-right block is ), symmetry and commutativity; (b) first row, free parameters, cost ; (c) , , , , , pseudocode on first rows, correctness by induction; (d) , exact checked on , Case 1; (e) , operations against | checking only the sum; counting parameters; returning the full matrix (the block costs a sum at each level); ; ; Case 2 instead of Case 1 |
| 2 | 11 | (a) earliest deadline first, shifted residual deadlines, pseudocode, counterexample for the shortest job first; (b) exchange by moving to the front, with the three groups of jobs checked and used; (c) proved with the identity on the completion times, induction; (d) and the schedule with | swapping instead of moving; forgetting the delay of the overtaken jobs; claiming the property for every optimum; additive substructure instead of the maximum; not shifting the deadlines of the residual |
For extra practice on the same topics see Master TheoremThe Master Theorem for T(n) = aT(n/b) + w(n) compares w(n) with the threshold n^(log_b a). Case 1 (w polynomially smaller): Theta(n^(log_b a)); case 2 (same order): Theta(n^(log_b a) log n); case 3 (polynomially larger and regular): Theta(w(n)). Full proof from the levels of the tree, extended version with floors and ceilings, a table of applications, and the misuse when no case applies (w = n log n).Master Theorem →, Strassen's AlgorithmStrassen computes the n x n product with 7 recursive calls instead of 8, using 10 matrix additions in Divide and 8 in Conquer: T(n) = 7T(n/2) + (9/2)n^2, Theta(n^(log2 7)) with exact solution 7n^(log2 7) - 6n^2. Its leading constant 7 is more than three times that of the iterative algorithm (2), so Strassen beats it only from n = 655 (from 1024 for powers of two).Strassen's Algorithm →, Hybrid AlgorithmsHybridization combines two algorithms for the same problem so the result has the asymptotics of the better one and, if possible, lower constants. Choosing the algorithm only by the starting size (STUPID_HYBRID) does not help; changing the base case of the recursion (H_MUL: iterative product for n <= n0 at every leaf of Strassen's tree) gives cost n^(log2 7)(2n0+5)/n0^(log2 7 - 2) - 6n^2, minimal for n0 = 8 with leading constant about 3.92.Hybrid Algorithms →, Structured Block Matrices - Reducing Recursive CallsFor recursively structured matrix families (ARB, SIR, RCA, supercirculant) the method is: count the free parameters (n, not n^2), write the block product, prove closure under sum, difference and product by induction, count the distinct block products, and reduce them with sums and differences (2 calls for SC and RCA, 3 for ARB and SIR). If the product leaves the family one cannot recurse on it, which is why one asks for a matrix-vector product instead.Structured Block Matrices - Reducing Recursive Calls →, Fast Fourier TransformThe FFT computes the DFT_n (n a power of two) by divide and conquer: split the coefficients by index parity, p(x) = p0(x^2) + x p1(x^2), and by the halving lemma two DFTs of order n/2 suffice; y_i = y0_i + w^i y1_i and y_{i+n/2} = y0_i - w^i y1_i. The recurrence T(n) = 2T(n/2) + 2n with T(1) = 0 has exact solution 2 n log2 n. The inverse has matrix F^{-1}_{ij} = w^{-ij}/n and is obtained with the FFT on negative powers (then dividing by n outside the recursion) or with a reversed DFT_n(y). LIN_CONV multiplies two polynomials with n coefficients in 12 n log2(2n) + 4n operations.Fast Fourier Transform → and 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 →.