POJ 1458 Common Subsequence(简单DP,LCS)

 

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, x ij = 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.

Input

The program input is from the std input. Each data set in the input contains two strings representing the given sequences. The sequences are separated by any number of white spaces. The input data are correct.

Output

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题,最长公共子序列问题(LCS)。
题解:

  假设有两个字符串s1s2...sn和t1t2...tm,定义dp[i][j]:=
s1s2...si和t1t2...tj(i<=n,j<=m)。

  由此,dp[i][j]对应的公共子序列可能是如下几种情况。
  1.当s[i+1]=s[j+1]时,在s1...si和t1...tj的公共子序列的末尾加上si+1
  2.
当s[i+1]≠s[j+1]时,s1...si和t1...tj+1的公共子序列,或者s1...si+1和t1..tj的公共子序列。

  由以上的几种情况可以得到递推关系:
    dp[i+1][j+1]=dp[i][j]+1 (s[i]==t[i])
    dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j])   (其他情况)
  
 时间复杂度为O(nm),dp[n][m]就是LCS的长度。
 

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int dp[1001][1001];
int main()
{
    string a,b;
    while(cin>>a>>b)
    {
        memset(dp,0,sizeof(dp));
        int lena=a.length(),lenb=b.length();
        for(int i=1;i<=lena;i++)
            for(int j=1;j<=lenb;j++)
            {
                if(a[i-1]==b[j-1])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
            }
        cout<<dp[lena][lenb]<<endl;
    }
    return 0;
}

 

posted @ 2017-09-01 20:57  Zireael  阅读(142)  评论(0编辑  收藏  举报