LCS: two sequences S1 and S2 are given. The largest public part of these two sequences S3 is the longest public subsequence of S1 and S2. PUBLIC PART
It must appear in the same order, but it does not need to be continuous.
LCS has the optimal sub-structure and satisfies the overlapping sub-problems. Therefore, we can use dynamic planning to solve the LCS problem.
The recursive formula can be obtained from the optimal sub-structure of the LCS problem:
Reference code:
# Include <iostream> using namespace STD; # define M 7 # define N 6 int LCS (char * X, char * y, int C [M + 1] [n + 1], int B [M + 1] [n + 1]) {int M = m, n = N; for (INT I = 0; I <= m; I ++) C [I] [0] = 0; For (Int J = 0; j <= N; j ++) C [0] [J] = 0; For (INT I = 1; I <= m; I ++) {for (Int J = 1; j <= N; j ++) {If (X [I] = Y [J]) {c [I] [J] = C [I-1] [J-1] + 1; B [I] [J] = 0 ;} else if (C [I-1] [J]> = C [I] [J-1]) {C [I] [J] = C [I-1] [J]; B [I] [J] = 1;} else {C [I] [J] = C [I] [J-1]; B [I] [J] =-1 ;}} return C [m] [N];} void printlcs (int B [] [7], char * X, int I, Int J) {if (I = 0 | j = 0) {return;} If (B [I] [J] = 0) {printlcs (B, X, I-1, J-1); cout <X [I];} else if (B [I] [J] = 1) {printlcs (B, x, I-1, J);} else {printlcs (B, X, I, J-1);} int main () {char X [M + 1] = {'0', 'A', 'B', 'C', 'B', 'D', 'A ', 'B'}; char y [n + 1] = {'0', 'B', 'D', 'C', 'A', 'B ', 'A'}; int C [M + 1] [n + 1]; // note that the size must be strlen + 1; because 0 int B [M + 1] [n + 1]; cout <LCS (X, Y, C, B) <Endl; cout <"X: "<x <Endl; cout <" Y: "<Y <Endl; For (INT I = 1; I <= 7; I ++) {for (Int J = 1; j <= 6; j ++) {cout <B [I] [J] <ends ;}cout <Endl ;} cout <"the oldest sequence is:" <Endl; printlcs (B, X, 7, 6 );}
View code
Note that our B [0] [I] B [I] [0] does not store anything.
Output: 4
Bcba.