Common Subsequence(最长公共字串-动态规划)

红太狼 2022-08-02 14:43 234阅读 0赞

Common Subsequence

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 27834 Accepted Submission(s): 12392

Problem Description

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

  1. abcfbc abfcab
  2. programming contest
  3. abcd mnp

Sample Output

  1. 4
  2. 2
  3. 0

Source

Southeastern Europe 2003

  1. #include<cstdio>
  2. #include<iostream>
  3. #include<cstring>
  4. #include<algorithm>
  5. const int N=1010;
  6. using namespace std;
  7. int dp[N][N];
  8. int main()
  9. {
  10. string s1,s2;
  11. int stl1,stl2,i,j;
  12. while(cin>>s1>>s2)
  13. {
  14. memset(dp,0,sizeof(dp));
  15. stl1=s1.size();
  16. stl2=s2.size();
  17. for(i=1;i<=stl1;i++)
  18. {
  19. for(j=1;j<=stl2;j++)
  20. {
  21. if(s1[i-1]==s2[j-1])
  22. {
  23. dp[i][j]=dp[i-1][j-1]+1;
  24. }
  25. else
  26. {
  27. dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
  28. }
  29. }
  30. }
  31. cout<<dp[stl1][stl2]<<endl;
  32. }
  33. }

发表评论

表情:
评论列表 (有 0 条评论,234人围观)

还没有评论,来说两句吧...

相关阅读