Longest Common Subsequence
Dynamic Programming
Part I. Longest Common Subsequence of Two Sequences
Compute the length of a longest common subsequence of two sequences ๐ด = (๐1, ๐2, . . . , ๐n) and ๐ต = (๐1, ๐2, . . . , ๐m), defined as the largest non-negative integer ๐ such that there exist indices 1 โค ๐1 < ๐2 < ยท ยท ยท < ๐p โค ๐ and 1 โค ๐1 < ๐2 < ยท ยท ยท < ๐p โค ๐, such that ๐i1 = ๐j1 , . . . , ๐ip = ๐jp .
Input: two sequences ๐ด and ๐ต of lengths n and m respectively.
Output: the length p of their longest common subsequence
Input format
First line: ๐. Second line: ๐1, ๐2, . . . , ๐๐. Third line: ๐. Fourth line: ๐1, ๐2, . . . , ๐๐. Constraints. 1 โค ๐, ๐ โค 100; โ29 < ๐๐, ๐๐ < 29.
Output Format
Output ๐.
Example 1
Input: 3 2 7 5 2 2 5 Output: 2A common subsequence of length 2 is (2, 5).
Example 2
Input: 1 7 4 1 2 3 4 Output: 0The two sequences do not share elements.
Example 3
Input: 4 2 7 8 3 4 5 2 8 7 Output: 2One common subsequence is (2, 7). Another one is (2, 8).
Implement the solution to the LCP2 problem in file lcp2.c
.
Part II. Longest Common Subsequence of Three Sequences
Given three sequences ๐ด = (๐1, ๐2, . . . , ๐n), ๐ต = (b1, b2, . . . , bm), and ๐ถ = (c1, c2, . . . , cl), find the length of their longest common subsequence, i.e., the largest non-negative integer ๐ such that there exist indices 1 โค ๐1 < ๐2 < ยท ยท ยท < ๐p โค ๐, 1 โค ๐1 < ๐2 < ยท ยท ยท < ๐p โค ๐, 1 โค ๐1 < ๐2 < ยท ยท ยท < ๐p โค ๐ such that ๐i1 = ๐j1 = ๐k1 , . . . , ๐ip = ๐jp = ๐kp.
The input and output formats are the same as for the previous problem.
Example 1
Input: 3 1 2 3 3 2 1 3 3 1 3 5 Output: 2A common subsequence of length 2 is (1, 3).
Example 1
Input: 5 8 3 2 1 7 7 8 2 1 3 8 10 7 6 6 8 3 1 4 7 Output: 3One common subsequence of length 3 in this case is (8, 3, 7). Another one is (8, 1, 7).
Implement the solution to the LCP3 problem in file lcp3.c
.