Longest Common Subsequence 題解報告

Description

Problem C: Longest Common Subsequence

Sequence 1:

Sequence 2:


Given two sequences of characters, print the length of the longest common subsequence of both sequences. For example, the longest common subsequence of the following two sequences:

abcdgh
aedfhr
is adh of length 3.

Input consists of pairs of lines. The first line of a pair contains the first string and the second line contains the second string. Each string is on a separate line and consists of at most 1,000 characters

For each subsequent pair of input lines, output a line containing one integer number which satisfies the criteria stated above.

Sample input

a1b2c3d4e
zz1yy2xx3ww4vv
abcdgh
aedfhr
abcdefghijklmnopqrstuvwxyz
a0b0c0d0e0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0
abcdefghijklmnzyxwvutsrqpo
opqrstuvwxyzabcdefghijklmn

Output for the sample input

4
3
26
14                                                                                                                                                          

題目:    最長公共子序列(LCS),經典的動態規劃題目。即給出兩個序列,找出公共子序列的最大長度。
注意點:  子序列不一定是連續的。
分析:arry[i][j]  i表示a序列中 0到i-1 的子序列,j表示b序列中 0到j-1 的子序列,arry[i][j]表示這兩段子序列中公共子序列的最大長度。
      通過長度繼承分析可以得到遞推公式  1.a[i-1]==b[j-1]時, arry[i][j]=arry[i-1][j-1]+1;(長度在原來的基礎上增加一個)
                                        2.a[i-1]!=b[j-1]時,arry[i][j]=max(arry[i-1][j],arry[i][j-1]);(即取已有長度中最大的一個來繼承)
    下面給出代碼供參考。
#include <iostream>
#include <string.h>
using namespace std;
 char a[1005],b[1005];
int arry[1005][1005];
int main()
{
    int i,j;
    while(cin.getline(a,1005),cin.getline(b,1005))
    {
        memset(arry,0,sizeof(arry));
        int len1=strlen(a);
        int len2=strlen(b);
        for(i=1;i<=len1;i++)
        {
            for(j=1;j<=len2;j++)
            {
                if(a[i-1]==b[j-1])
                    arry[i][j]=arry[i-1][j-1]+1;
                else
                    arry[i][j]=max(arry[i-1][j],arry[i][j-1]);
            }
        }
        cout<<arry[len1][len2]<<endl;
    }
    return 0;
}



 
發佈了24 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章