Longest Common subsequence LCs

Source: Internet
Author: User

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.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.