<OJ_Sicily>Longest Common Subsequence

来源:互联网 发布:二次元动态桌面软件 编辑:程序博客网 时间:2024/06/05 19:40

Description

Given a sequence A = < a1, a2, ..., am >, let sequence B = < b1, b2, ..., bk > be a subsequence of A if there exists a strictly increasing sequence ( i1<i2<i3 ..., ik ) of indices of A such that for all j = 1,2,...,k, aij = bj. For example, B = < a, b, c, d > is a subsequence of A= < a, b, c, f, d, c > with index sequence < 1, 2, 3 ,5 >.

Given two sequences X and Y, you need to find the length of the longest common subsequence of X and Y. 

Input

 The input may contain several test cases.

The first line of each test case contains two integers N (the length of X) and M(the length of Y), The second line contains the sequence X, the third line contains the sequence Y, X and Y will be composed only from lowercase letters. (1<=N, M<=100)

Input is terminated by EOF.

Output

 Output the length of the longest common subsequence of X and Y on a single line for each test case.

题目解释:使用动态规划求解最长公共子序列。这道题在前面有一样的题目。原理可以参考前面的博文。

解题思路:使用动态规划实现最长公共子序列的求解.假设LCS(Xi,Yj) 表示的是Xi和Yj这两个序列的最长公共子序列的解,则有

1.若Xi == Yj,那么LCS(Xi,Yj) = LCS(Xi-1,Yj-1) + 1

2.若Xi != Yj ,那么LCS(Xi,Yj) = max( LCS(Xi-1,Yj) , LCS(Xi,Yj-1) )


<pre name="code" class="cpp">#include <iostream>#include <algorithm>#include <string.h>using namespace std;int c[100][100];int main(int argc, const char * argv[]) {    // insert code here...    int len_X, len_Y;    char strX[100], strY[100];    while (cin >> len_X >> len_Y) {        int i,j;        for (i = 0; i < len_X; i++) {            cin >> strX[i];        }        for (j = 0; j < len_Y; j++) {            cin >> strY[j];        }        memset(c, 0, sizeof(c));        for (i = 0; i <= len_X; i++) {            for (j = 0; j <= len_Y; j++) {                if (i == 0 || j == 0) c[i][j] = 0;                else if (strX[i-1] == strY[j-1] ) c[i][j] = c[i-1][j-1] + 1;                else c[i][j] = max(c[i-1][j], c[i][j-1]);            }        }        cout << c[len_X][len_Y] << endl;    }    return 0;}


0 0
原创粉丝点击