当前位置:   article > 正文

【入门DP】最长公共子序列_a subsequence of a given sequence is the given…

a subsequence of a given sequence is the given…

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.

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

题意:给定两组字符串,要求找出最长公共子序列。要求字母必须相同,且在各自的序列中位置   顺序相同。

找状态方程:(注意:)当都为0时候是不存在序列的,所以至少为1才能计算;

   因此有两种状态:

 如果前i项的字母和前j项的字母序列相同 :dp[i][j] = d[i-1][j-1] + 1 ;

    否则  dp[i][j] = max (dp[i-1][j] , dp[i][j-1] ) ;

AC代码:

  1. #include <iostream>
  2. #include <cstring>
  3. #include <cstdio>
  4. #include <algorithm>
  5. using namespace std ;
  6. int dp[1000][1000] ;
  7. char str1[1100] , str2[1100];
  8. int main()
  9. {
  10. while(cin>>str1>>str2)
  11. {
  12. int len1 = strlen(str1);
  13. int len2 = strlen(str2);
  14. for(int i = 0 ; i<=len1;i++)
  15. {
  16. dp[i][0] = 0 ;
  17. }
  18. for(int i = 0 ; i<=len2;i++)
  19. {
  20. dp[0][i] = 0 ;
  21. }
  22. for(int i = 1 ; i <=len1 ;i++)
  23. {
  24. for(int j = 1; j<=len2 ; j++)
  25. {
  26. if(str1[i-1]==str2[j-1])
  27. {
  28. dp[i][j] = dp[i-1][j-1]+1;
  29. }
  30. else
  31. {
  32. dp[i][j] = max(dp[i-1][j] , dp[i][j-1]);
  33. }
  34. }
  35. }
  36. cout<<dp[len1][len2]<<endl;
  37. }
  38. return 0 ;
  39. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/939763
推荐阅读
相关标签
  

闽ICP备14008679号