Algorithms in Engineering - Mock Exam 3
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 Italian course (Algoritmi per l'Ingegneria, Ing. Informatica UniPD, taught in Italian at Padova); it is a simulation, not a real paper. The official exam has two parts: a first part of closed-answer questions on the basics of the course and a second part of problems (design and analysis of an algorithm, proof of a property). The first parts of the real papers are not public: from the official sample papers only the format is known (about ten short questions, one answer each), so the number of questions, the points and the duration are a proposal of this mock: Part 1 has 10 quizzes of 1 point each (four options, exactly one correct, only the letter is written); Part 2 has 2 exercises of 11 points each; total 32 points, 2 hours and 30 minutes, no material allowed. As in the real exam, the second part is not worth correcting if the first one is very poor.
The topics are: recurrences and the Master Theorem, structured matrices, fast exponentiation, DFT and FFT, dynamic programming (LCS, longest palindromic subsequence, matrix chain), greedy scheduling and Huffman codes, hybrid algorithms and parametric induction. Questions and exercises are new (they are not copies of the real exams nor of the other mocks). All numerical results were checked by running the algorithms: the hybrid product against the definition on random inputs with an exact count of the scalar operations, Huffman on Fibonacci frequencies with every tie-breaking for , the matrix chain against all parenthesizations, and every quiz against a direct computation.
Quiz 1
Which of the following recurrences, with and a power of two, has solution ?
- (a)
- (b)
- (c)
- (d)
Show the result
(c)
Show the full solution
- (a) , : threshold , with regularity (): Case 3, .
- (b) : threshold , : Case 1, .
- (c) : threshold , : Case 2, (every level of the tree costs , the levels are ).
- (d) : threshold , : Case 1, .
Typical mistake: answering (a) or (d) because " appears".
Quiz 2
Let and be supercirculant matrices of order with first rows and . What is the first row of ?
- (a)
- (b)
- (c)
- (d)
Show the result
(b)
Show the full solution
Use the recursive product of 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 →: with , the product is supercirculant with blocks and , and Here , , , .
- , . For order the same formulas on scalars: sums and , differences and , products and , so .
- , : sums and , differences and , products and , so .
- , .
The first row of is . Check by definition: entry is .
Wrong options: (a) is the componentwise product of the rows; (c) swaps the two halves ; (d) is the cyclic convolution of the rows, which is the product of circulant (not supercirculant) matrices.
Quiz 3
The Fibonacci matrix is raised to the power with the recursive algorithm POWER (repeated squaring). Each product of two matrices is done with the iterative row-by-column algorithm. How many products between scalars are executed in total?
- (a)
- (b)
- (c)
- (d)
Show the result
(d)
Show the full solution
In Fast Exponentiation by Repeated SquaringPower x^n with an associative operator having an identity, cost = number of applications of the operator; STUPID_POWER costs n-1, the substructure x^n = (x^floor(n/2))^2 (times x for odd n) gives POWER with T(n) = floor(log2 n) + (number of 1 bits of n) - 1, Theta(log n) (worst case 2 floor(log2 n), n = 2^t - 1); iterative versions POWER2 and POWER3 from the binary representation of n; example with the Fibonacci matrix; unit-cost model valid only if the operator does not make operands grow.Fast Exponentiation by Repeated Squaring → the number of applications of the operator is , with the number of bits. For : , , so matrix products (the chain is with costs ). The product of two matrices has scalar products (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 →): .
Wrong options: (a) counts matrix products, not scalar ones; (b) forgets the multiplications by for the odd exponents; (c) is the cost of the definition-based algorithm. As a check, the top-right entry of is (with ).
Quiz 4
What is for ?
- (a)
- (b)
- (c)
- (d)
Show the result
(a)
Show the full solution
The vector is -sparse: whenever is not a multiple of (Notable Transforms and Polynomial ExponentiationSome vector families have a known or cheaper DFT than the general FFT: the constant vector (a,...,a) has DFT (na,0,...,0), the vector (a,0,...,0) has DFT (a,...,a); an (n,k)-sparse vector has a DFT made of k copies of the DFT_{n/k} of its components at multiples of k, and SPARSE_FFT costs 2 (n/k) log2(n/k) with recurrence T(n,k) = T(n/2,k/2). For the power p(x)^k of a polynomial with n coefficients: either repeated squaring with LIN_CONV, O(nk log(nk)), or evaluate p with the FFT on h = 2^ceil(log2((n-1)k+1)) points, raise each value to the k, and invert, Theta(nk log(nk)).Notable Transforms and Polynomial Exponentiation →). Its transform is copies of , because . Directly: , which is for even and for odd (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 →).
Wrong options: (b) puts the nonzero values at frequencies and only, as if the DFT were as sparse as the input; (c) is not the transform of this vector (a nonzero value at index gives in every component, never zeros); (d) is half of the correct vector, a mistake of dividing by .
Quiz 5
The polynomial has coefficients and one wants all the coefficients of with the FFT (evaluate on the roots of unity, raise each value to the -th power, invert). What is the minimum order of the DFT (a power of two) that can be used?
- (a)
- (b)
- (c)
- (d)
Show the result
(c)
Show the full solution
has degree at most , so has degree at most , i.e. coefficients. The values on points determine a polynomial with at most coefficients, so one needs ; the first power of two is (Notable Transforms and Polynomial ExponentiationSome vector families have a known or cheaper DFT than the general FFT: the constant vector (a,...,a) has DFT (na,0,...,0), the vector (a,0,...,0) has DFT (a,...,a); an (n,k)-sparse vector has a DFT made of k copies of the DFT_{n/k} of its components at multiples of k, and SPARSE_FFT costs 2 (n/k) log2(n/k) with recurrence T(n,k) = T(n/2,k/2). For the power p(x)^k of a polynomial with n coefficients: either repeated squaring with LIN_CONV, O(nk log(nk)), or evaluate p with the FFT on h = 2^ceil(log2((n-1)k+1)) points, raise each value to the k, and invert, Theta(nk log(nk)).Notable Transforms and Polynomial Exponentiation →). is too small (: wrap-around would corrupt the coefficients); is not a power of two; works but is not minimal.
Quiz 6
The inverse transform INV_FFT is computed as the course does (the FFT with on the vector, then a division of every component by outside the recursion). How many operations between complex numbers does it perform for order ?
- (a)
- (b)
- (c)
- (d)
Show the result
(b)
Show the full solution
The FFT costs complex operations (four per butterfly, butterflies per level; 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 →): . The final division of the components adds : .
Wrong options: (a) forgets the divisions; (d) is , the cost with precomputed powers of and no divisions; (c) is rounded to a power of two, with no derivation behind it.
Quiz 7
Let and . What is the length of a longest common subsequence of and ?
- (a)
- (b)
- (c)
- (d)
Show the result
(a)
Show the full solution
Fill the table of Longest Common Subsequencethe longest common subsequence of X (m symbols) and Y (n symbols) is found by dynamic programming on pairs of prefixes with l(i,j) = 0 if i = 0 or j = 0, 1 + l(i-1,j-1) if x_i = y_j, max of the two neighbours otherwise; bottom-up costs mn comparisons, reconstruction O(m+n), pure divide and conquer costs C(m+n,m) - 1 internal nodes, and space drops to Theta(min{m,n}) if only the length is needed.Longest Common Subsequence →: on row and column , if , otherwise .
| g | e | n | e | r | a | t | i | o | n | ||
|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | |
| e | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| n | 0 | 0 | 1 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |
| g | 0 | 1 | 1 | 2 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |
| i | 0 | 1 | 1 | 2 | 2 | 2 | 2 | 2 | 3 | 3 | 3 |
| n | 0 | 1 | 1 | 2 | 2 | 2 | 2 | 2 | 3 | 3 | 4 |
| e | 0 | 1 | 2 | 2 | 3 | 3 | 3 | 3 | 3 | 3 | 4 |
| e | 0 | 1 | 2 | 2 | 3 | 3 | 3 | 3 | 3 | 3 | 4 |
| r | 0 | 1 | 2 | 2 | 3 | 4 | 4 | 4 | 4 | 4 | 4 |
The bottom-right cell is . Two common subsequences of length are and . Typical mistake: counting letters in common (, , , , are all in both strings) instead of respecting the order.
Quiz 8
Let . What is the length of a longest palindromic subsequence of ?
- (a)
- (b)
- (c)
- (d)
Show the result
(d)
Show the full solution
Use of String Alignment and Longest Palindromic Subsequencetwo string problems solved by dynamic programming like the LCS; optimal DNA alignment with score matrix S and gap penalty g uses C(i,j) = max{C(i-1,j-1) + s, C(i-1,j) + g, C(i,j-1) + g} in Theta(mn) time and Theta(min{m,n}) space for the cost alone, while the longest palindromic subsequence works on substrings with p(i,j) = 2 + p(i+1,j-1) if x_i = x_j, else max of the two shorter substrings, scanned by diagonals with n(n-1)/2 comparisons.String Alignment and Longest Palindromic Subsequence →: ; if then (with ); otherwise . The first row of the table, by diagonals, is For instance gives , then gives , then gives with (): , the palindrome . The last three letters do not improve it: (all the other branches of the recurrence give at most ; a length would need four disjoint pairs of equal letters nested around the centre, which does not have). Another palindrome of length is .
Typical mistake: taking the longest substring palindrome ( is not one; the longest substring palindromes have length ).
Quiz 9
The matrix chain algorithm MCM (bottom-up, diagonal by diagonal) is applied to a chain of matrices. Counting two multiplications between integers (the three dimensions ) for every value of examined, how many multiplications does it perform?
- (a)
- (b)
- (c)
- (d)
Show the result
(c)
Show the full solution
In Matrix Chain Multiplicationgiven the dimension vector p of a chain of n compatible matrices, find the parenthesization minimizing scalar products; parenthesizations are Catalan numbers (exponential), the subtrees of the last product are optimal (cut-and-paste), c(i,j) = min over k of c(i,k) + c(k+1,j) + p_(i-1) p_k p_j, divide and conquer costs 3^(n-1) - 1, bottom-up by increasing diagonals costs (n^3 - n)/3 products, and memoization never saves anything.Matrix Chain Multiplication → the cost is : for , . Check: the number of values of is , and each costs multiplications.
Wrong options: (a) counts only the values of , without the factor ; (b) is , forgetting the division by in the sum; (d) is , counting the factor twice.
Quiz 10
Five jobs with execution times are run on one machine, one after the other. The waiting time of a job is the sum of the times of the jobs run before it. What is the minimum possible cumulative waiting time (sum of the waiting times of all the jobs)?
- (a)
- (b)
- (c)
- (d)
Show the result
(a)
Show the full solution
By 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 optimum is the Shortest-Job-First order with waits : total . Equivalently . All orders were checked: none gives less.
Wrong options: (b) is the given order (waits ); (c) is the sum of the completion times in the optimal order (); (d) is the longest-first order ().
Exercise 1 (points 11)
A polynomial with coefficients is represented by the vector , and . The product of and (vector ) has coefficients. The cost is the number of sums, differences and products between scalars; assignments, copies and shifts of vectors cost . The algorithm CONV that computes the product by definition (two nested loops, the first term of each coefficient is assigned, not added) costs .
The hybrid algorithm GCONV has a threshold (a power of two, ) and works as follows. Write and , , where have the lower and the higher coefficients of , and the same for .
- Base: if return
CONV. - Divide: compute and (componentwise sums of the coefficient vectors, coefficients each).
- Recurse: , , , each with coefficients.
- Conquer: (componentwise) and return , adding the three vectors placed at positions , , .
1.(a) [2 points] Prove that GCONV is correct.
1.(b) [3 points] Show that the work of a non-base call (Divide plus Conquer) is exactly operations. Write the recurrence of the cost of GCONV and solve it exactly for with the recursion tree.
1.(c) [2 points] Find the power of two that minimizes the coefficient of in . For that , from which on is GCONV cheaper than CONV, and how much does it cost for ?
1.(d) [4 points] For not a power of two a simplified model of the cost is With parametric induction show that there are and such that for all : write the constraints on coming from the base and from the step, and find the smallest they allow.
Show the result
(a) , so the returned polynomial is .
(b) . for , otherwise, and for
(c) The coefficient takes the values for : the optimum is . GCONV with costs (with ), equals CONV for () and is cheaper for every ( against for ). For : against (about one sixth).
(d) Constraints: , from the step; from the base (the binding one). Smallest : for all .
Show the full solution
(a) Correctness. Use the substructure of Divide and Conquer - Paradigm and Call TreeA divide-and-conquer algorithm comes from a substructure property (threshold n0, Divide and Conquer functions) with strictly smaller subinstances; the call tree describes the execution, and D&C has no memory (equal subinstances are recomputed). Complete example: MAX of an array, with correctness by induction, the recurrence, and the exact count n-1 via the theorem on full binary trees.Divide and Conquer - Paradigm and Call Tree →: threshold , base solved by the correct CONV, subinstances of size (the sums also have coefficients, since they add vectors of equal length). By induction on the three recursive calls return the products , , (this is the same idea of Gauss as in the product of complex numbers with three real products, see 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 →). Expanding,
Then
The positions fit: occupies , occupies , occupies , so the result has the coefficients of the product. (Typical mistake: forgetting to subtract and , which leaves the extra terms in the middle.)
(b) Work, recurrence, exact solution.
Work of a non-base call. Divide: and cost sums each, . Conquer: needs two componentwise subtractions of vectors of components, . The final sum has overlaps only where two of the three vectors have a coefficient in the same position: and share positions ( positions), and share ( positions), and share none ( ends at , starts at ); every other coefficient is copied (cost ). So additions, and
Recurrence. With (cost of CONV on coefficients):
Recursion 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 →): , , . With the last non-base level is ; level has nodes of size and work ; the leaves have size . So The first part is , and since we have : it equals . The second part is , subtracted. Summing, With one gets the second form, (the 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 → gives the same order: , , , Case 1). Checks: gives ; , : ; , : . The formula was also confirmed by counting the operations of an implementation on random inputs, for and , with the output compared to the definition.
(c) Choice of the threshold. The leading coefficient is , the cost of the leaves plus the work of the levels above them, per unit of . As in 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 →: a larger replaces levels of the tree (where is linear) with CONV (quadratic), a smaller one leaves too many nodes. Values:
| 1 | 2 | 4 | 8 | 16 | 32 | |
|---|---|---|---|---|---|---|
The real minimizer of (zero of : ) is , so among powers of two the optimum is . Then with , and . The difference
is for (, both cost ), for (), for (). For it is positive: and , so (induction). Hence the hybrid is cheaper for every . For (): , against of CONV (ratio ); the other thresholds give (), (), (). Typical mistake: choosing the threshold from the cost for small only, or taking or (not powers of two: the sizes would stop being integers).
(d) Parametric induction (Parametric InductionParametric induction proves a bound T(n) <= cn+d (or >=) with unknown constants c and d: simulate the induction proof, collect constraints on c and d from the base and the step HP => TH, and if their intersection is nonempty pick the best pair. For MAX it gives exactly T(n) = n-1; it can fail even for true guesses (add a parameter or a lower-order term).Parametric Induction →). Let . Guess: for all , with and real. The simplest guess cannot work: for even the step would need , i.e. , false. A lower-order linear term is needed, as in the notes.
Base (): , i.e. for .
Step (, so ). By [HP] Two rounding facts: and is increasing, so (because ); and for , gives . (If the bound leaves the term positive and growing, which no constant can absorb: so .) Then This must hold for all . If the left side grows with and the condition fails. If the left side is and the condition is , i.e. . If the left side decreases with , the binding case is and it gives (for example , ).
Intersection. The base needs for . For , the four bounds are : the largest, , comes from . For any admissible pair the bound from is , and since the step forces when and when , we get for and for , with equality only at . So the smallest is Check by a normal induction: base : ; : ; : ; : . Step: as above with , , since . Numerically , , and the inequality holds for every .
Remark. The constant is imposed by the single value (where the bound is tight); asking the guess only for the same method gives . Both are above the true asymptotic constant of the power-of-two case: parametric induction gives a valid bound, not the best one. As the notes say, the method can fail or be loose, and a failure does not disprove the guess.
Exercise 2 (points 11)
A file uses characters , and occurs times, where and are the Fibonacci numbers (). The Huffman algorithm is used with the conventions of the course: the trie has the left child lighter (frequency not greater) than the right child, the edge to the left child is labelled and the edge to the right child ; when a leaf and an internal node have the same frequency the leaf is extracted first.
2.(a) [2 points] For draw the Huffman trie, list the six codewords and compute the cost .
2.(b) [4 points] For a generic prove by induction the shape of the trie and give the codeword and the length of , for .
2.(c) [2 points] Compute in closed form, the average codeword length, and compare with a fixed-length code for .
2.(d) [3 points] (Dynamic programming.) Four matrices have dimension vector , i.e. is . With the bottom-up algorithm MCM find the minimum number of scalar products to compute and an optimal parenthesization; say how many values of the algorithm examines and what the left-to-right order costs.
Show the result
(a) Codewords , , , , , (frequencies ); (, the internal nodes).
(b) The trie is a "comb": is a leaf child of the root, a leaf child of the right child, and so on. Codeword of : for (length ); and (length ).
(c) ; total frequency ; average length . For : bits against for the fixed code ( bits per character), average against .
(d) Minimum products, parenthesization ; values of ( multiplications between dimensions); left to right: .
Show the full solution
(a) The case . Frequencies (total ). Run of the algorithm of 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 →:
| step | extracted (left, right) | node created | queue after the step |
|---|---|---|---|
| start | |||
| 1 | |||
| 2 | |||
| 3 | |||
| 4 | |||
| 5 |
In step 2 the leaf and the node have the same frequency : by the convention the leaf is extracted first, so it is the left child. The trie (weights; left, right):
(20)
0/ \1
c6:8 (12)
0/ \1
c5:5 (7)
0/ \1
c4:3 (4)
0/ \1
c3:2 (2)
0/ \1
c1:1 c2:1Codewords: , , , , , . Cost: Check with the internal nodes ( is the sum of their weights): .
(b) The shape, for generic . First a lemma: for . Induction: : ; if true for , then .
Define the comb (): is a root with the leaves (left) and (right); for , is a root whose left child is the leaf and whose right child is . By the lemma the weight of (sum of the frequencies of ) is .
Claim , for : after iterations of the loop of HUFFMAN the queue contains exactly and the leaves .
Base . The initial weights are : the two minima are (every other leaf weighs at least ), and merging them gives (which of the two is the left child is irrelevant for the shape).
Step. Assume with . The queue holds of weight and the leaves of weights (strict because with ). So and are strictly lighter than every other element ( and ): they are the two extracted nodes. Their order: , always true, and with equality only when , i.e. (the tie against of step 2, where the convention puts the leaf on the left). So the leaf is the left child, the right one, and the new node is exactly , of weight . This is .
After iterations the queue contains only : the Huffman trie is the comb . Reading the paths: is reached from by an edge , and its leaf by an edge . To reach the leaf with one goes through (that is edges labelled ) to and then takes the left edge: The leaves hang from , which is reached with ones: , , depth both. For this gives the codewords of (a). The code is prefix-free (all the leaves are leaves of a trie). The longest codeword has bits, so the length grows linearly with .
Typical mistakes: thinking that the tie at step 2 can change the cost (it only exchanges the codewords of and of the leaves below; the cost is the same, and the run with the opposite convention was also checked: every tie-breaking gives the same cost); comparing with instead of with , the weight of the comb.
(c) Cost and average length. The internal nodes are with weights , so by the formula of 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 →, and the lemma, Check : . The file has characters (the lemma with ), so the average length is Since , the average length tends to bits whatever , while the maximum length is (values: : ; : ; : ; : ). A fixed-length code needs bits: for , bits per character, i.e. bits for the characters against (a quarter less); for , bits against . The skewed frequencies make Huffman gain more and more.
(d) Matrix chain (Matrix Chain Multiplicationgiven the dimension vector p of a chain of n compatible matrices, find the parenthesization minimizing scalar products; parenthesizations are Catalan numbers (exponential), the subtrees of the last product are optimal (cut-and-paste), c(i,j) = min over k of c(i,k) + c(k+1,j) + p_(i-1) p_k p_j, divide and conquer costs 3^(n-1) - 1, bottom-up by increasing diagonals costs (n^3 - n)/3 products, and memoization never saves anything.Matrix Chain Multiplication →). is , is , is , is . With and , by increasing diagonals:
- : , , .
- , cell : : ; : . Minimum , . Cell : : ; : . Minimum , .
- , cell : : ; : ; : . Minimum , .
| 1 | 2 | 3 | 4 | |
|---|---|---|---|---|
| 1 | 0 | 84 | 204 | 294 |
| 2 | 0 | 210 | 255 | |
| 3 | 0 | 150 | ||
| 4 | 0 |
Reconstruction: splits into and (each a single product), so the optimum is with scalar products. The values of examined are , i.e. multiplications between dimensions. The five parenthesizations cost , (), (left to right: ), and : the optimum is unique and the left-to-right order costs more. Typical mistake: using in place of in the cost of the last product.
Self-assessment grid
| Exercise | Points | What must be there for full marks | Typical mistakes |
|---|---|---|---|
| Quiz 1 | 1 | Case 2 of the Master Theorem: , , , answer (c) | Looking only at the exponent of ; confusing Cases 2 and 3 |
| Quiz 2 | 1 | Recursive product with and , first row | Componentwise product of the rows; cyclic convolution (circulant, not supercirculant) |
| Quiz 3 | 1 | matrix products, each scalar products: | Counting matrix products or products; forgetting the multiplications by |
| Quiz 4 | 1 | -sparse vector: repeated times | Using the wrong sparsity pattern; dividing by |
| Quiz 5 | 1 | Degree bound , first power of two | Taking or ; choosing |
| Quiz 6 | 1 | Forgetting the divisions; | |
| Quiz 7 | 1 | LCS table with last cell ; order respected | Counting common letters regardless of order |
| Quiz 8 | 1 | Table by diagonals, , palindrome | Confusing subsequence and substring |
| Quiz 9 | 1 | with two products per | Counting only the values of (); |
| Quiz 10 | 1 | SJF order, waits , total | Using the given order; summing completion times |
| 1.(a) | 2 | Gauss identity , positions of the three vectors, induction | Not subtracting and ; no induction on the size |
| 1.(b) | 3 | with the overlaps counted; recurrence with base ; exact with checks | Counting all additions of the shifted sum; forgetting the leaf term |
| 1.(c) | 2 | minimized at (value ), cheaper than CONV for every , for |
Non-power-of-two threshold; comparing only for |
| 1.(d) | 4 | Guess with , why fails, rounding facts, , , base constraints, | One-parameter guess; using with ; not checking the base |
| 2.(a) | 2 | Run of the algorithm with the tie rule, trie, codewords, | Wrong order at the tie; mixing frequencies and depths |
| 2.(b) | 4 | Lemma on , invariant with the comb , strict inequalities, codewords and the two deepest leaves | No induction (only examples); ignoring the tie; missing |
| 2.(c) | 2 | , average length tending to , comparison against | Off-by-one in the sum of the Fibonacci numbers; forgetting that the file has characters |
| 2.(d) | 3 | Table and , with , values of , left to right | Wrong dimensions in ; not reconstructing the parenthesization |