/lcs_ass

dynamic programming: Longest Common Subsequence

Primary LanguageCMIT LicenseMIT

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:
2
A common subsequence of length 2 is (2, 5).

Example 2

Input:
1
7
4
1 2 3 4
Output:
0
The two sequences do not share elements.

Example 3

Input:
4
2 7 8 3
4
5 2 8 7
Output:
2
One 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:
2
A 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:
3
One 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.