每日一题之 hdu1159 Common Subsequence

Problem Description
A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X =< x 1 , x 2 , . . . , x m > another sequence Z =< z 1 , z 2 , . . . , z k > is a subsequence of X if there exists a strictly increasing sequence < i 1 , i 2 , . . . , i k > of indices of X such that for all j = 1 , 2 , . . . , k , x i j = z j . For example, Z =< a , b , f , c > is a subsequence of X =< a , b , c , f , b , c > with index sequence < 1 , 2 , 4 , 6 > . Given two sequences X and Y the problem is to find the length of the maximum-length common subsequence of X and Y.

The program input is from a text file. Each data set in the file contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct. For each set of data the program prints on the standard output the length of the maximum-length common subsequence from the beginning of a separate line.

Sample Input
abcfbc abfcab
programming contest
abcd mnp

Sample Output
4
2
0

题意:

给两个字符串,求最长公共子序列的长度。

思路:

X =< x 1 , x 2 , . . . , x m > Y =< y 1 , y 2 , . . . , y n > 为两个序列, Z =< z 1 , z 2 , z 3 , . . . , z k > 为X和Y的任意LCS。则
如果xm=yn,则zk=xm=yn且Zk−1是Xm−1和Yn−1的一个LCS。
如果xm≠yn,那么zk≠xm,意味着Z是Xm−1和Y的一个LCS。
如果xm≠yn,那么zk≠yn,意味着Z是X和Yn−1的一个LCS。

从上述的结论可以看出,两个序列的LCS问题包含两个序列的前缀的LCS,因此,LCS问题具有最优子结构性质。在设计递归算法时,不难看出递归算法具有子问题重叠的性质。
  设C[i,j]表示Xi和Yj的最长公共子序列LCS的长度。如果i=0或j=0,即一个序列长度为0时,那么LCS的长度为0。根据LCS问题的最优子结构性质,可得如下公式:
  

C [ i , j ] = { 0 i = 0 j = 0 C [ i 1 , j 1 ] + 1 i , j > 0 x i = y j M A X ( C [ i , j 1 ] , C [ i 1 , j ] ) i , j > 0 x i y j


#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>

using namespace std;

const int maxn = 1e3+5;

int main()
{
    string str1,str2;

    while(cin >> str1 >> str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        int dp[len1+5][len2+5];
        memset(dp,0,sizeof(dp));


        for (int i = 0; i <= len1; ++i) {
            for (int j = 0; j <= len2; ++j) {
                if (i == 0 || j == 0) 
                    dp[i][j] = 0;
                else if (str1[i-1] == str2[j-1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                }
                else 
                    dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
            }
        }
        cout << dp[len1][len2] << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/80843244