hdu 1159 Common Subsequence(最长公共子序列LCS)

Problem Description

A subsequence of a given sequence is the given sequence with some elements (possible none) left out. Given a sequence X = <x1, x2, ..., xm> another sequence Z = <z1, z2, ..., zk> is a subsequence of X if there exists a strictly increasing sequence <i1, i2, ..., ik> of indices of X such that for all j = 1,2,...,k, xij = zj. 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

解题思路:基础dp!求两个字符串的最长公共子序列的长度,则dp[i][j]表示字符串s1的前i个字符与字符串s2的前j个字符构成的最长公共子序列的长度,推导式:当s1的第i个字符与s2的第j个字符相等时,dp[i][j]=dp[i-1][j-1]+1;否则dp[i][j]=max(dp[i-1][j],dp[i][j-1]),表示当前的dp[i][j]为s1的前i-1个字符与s2的前j个字符组成的最长公共子序列的长度即dp[i-1][j]和s1的前i个字符与s2的前j-1个字符组成的最长公共子序列的长度即dp[i][j-1]这两者中的最大值。dp求解的核心就是枚举到当前字符串中的某个字符,都要枚举另外一个字符串中的每个字符,并记录当前的最优解,这样最后求得dp[len1][len2]就是LCS的长度。时间复杂度是O(nm)。

AC代码:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1005;
 4 char s1[maxn],s2[maxn];int len1,len2,dp[maxn][maxn];
 5 int main(){
 6     while(cin>>(s1+1)>>(s2+1)){
 7         memset(dp,0,sizeof(dp));
 8         len1=strlen(s1+1),len2=strlen(s2+1);
 9         for(int i=1;i<=len1;i++){
10             for(int j=1;j<=len2;j++){
11                 if(s1[i]==s2[j])dp[i][j]=dp[i-1][j-1]+1;
12                 else dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
13             }
14         }
15         cout<<dp[len1][len2]<<endl;
16     }
17     return 0;
18 }

 

posted @ 2018-04-21 16:15  霜雪千年  阅读(174)  评论(0编辑  收藏  举报