Lecture 8 Notes

Lecture 8 Notes

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: f t1 and t2 local store = local store of t1 + local store of t2 mark completed flag end end 2. Longest common subsequence (LCS) Problem. Find the longest subsequence common to all sequences in two sets of sequences. If the two set were “DYNAMIC PROGRAMMING” and “ALGORITHM” the longest common subsequence is “AORI”. (1) Find the recursive relation. Let two sequences be defined as the following: a = (a1, a2, …, ax) b = (b1, b2, …, by) We could define the recursive relation by: ⎧ 0 if i = 0 or j = 0 ⎪ lcs( ai , b j ) = ⎨ 1 + lcs( ai−1, b j −1 ) if ai = b j ⎪max(lcs( a , b ), lcs( a , b )) if a ≠ b ⎩ i−1 j i j −1 i j (2) What is the answer of the problem? The answer would be lcs( ax , by ) . (3) Try an example to verify the recursive relation. Here is initial layout of array c. PROGRAMMING -DYNAMIC - 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 A 0 L 0 G 0 O 0 R 0 I 0 T 0 H 0 M 0 After a couple of iterations the table looks like the following. Now it is the turn to fill the blue colored cell. a[i‐1] and b[j‐1] are the same alphabet ‘I’ so the blue cell is filled with 1+c[i‐1, j‐1] which is “2”. A L -DYNAM 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 I 0 1 1 C 0 0 P 0 R 0 O 0 G 0 R 0 A 0 M 0 M 0 I 0 N 0 G 0 G O R I T H M 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 Finally, the table looks like this. Our optimal solution is “4” (the red colored cell). A L G O R I T H M -DYNAM 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 1 0 0 0 0 1 2 I 0 1 1 1 1 1 2 2 2 2 C 0 1 1 1 1 1 2 2 2 2 0 1 1 1 1 1 2 2 2 2 P 0 1 1 1 1 1 2 2 2 2 R 0 1 1 1 1 2 2 2 2 2 O 0 1 1 1 2 2 2 2 2 2 G 0 1 1 2 2 2 2 2 2 2 R 0 1 1 2 2 3 3 3 3 3 A 0 1 1 2 2 3 3 3 3 3 M 0 1 1 2 2 3 3 3 3 4 M 0 1 1 2 2 3 3 3 3 4 I 0 1 1 2 2 3 4 4 4 4 N 0 1 1 2 2 3 4 4 4 4 (4) Express the recursive relation top­down. function lcs(a, b) begin lcsr(a, b, 0, 0) end function lcsr(a, b, i, j) begin if a[i] = null or b[j] = null then return 0 else if a[i] = b[j] then return 1 + lcsr(i+1, j+1) else return max(lcsr(i+1, j), lcsr(i, j+1)) end (5) Use memoization to eliminate redundancy. function lcs(a, b) begin lcsr(a, b, 0, 0) end var m = 2D array (size of first set * size of second set) initialized to -1 G 0 1 1 2 2 3 4 4 4 4 function lcsr(a, b, i, j) begin if m[i,...
View Full Document

This document was uploaded on 03/17/2014 for the course CS 4800 at Northeastern.

Ask a homework question - tutors are online