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

末蓝、 2022-07-24 08:28 266阅读 0赞

Common Subsequence

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

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

Recommend

Ignatius | We have carefully selected several similar problems for you: 1087 1176 1003 1058 1069

题目意思:

给两个字符串,求这两个字符串相同字符的个数。

解题思路:

20160518185842677

  1. #include<iostream>
  2. #include<cstdio>
  3. #include<cstdlib>
  4. #include<cstring>
  5. #include<algorithm>
  6. using namespace std;
  7. #define MAXN 10010
  8. int dp[MAXN][MAXN];
  9. int main()
  10. {
  11. char a[MAXN],b[MAXN];
  12. while(cin>>a>>b)
  13. {
  14. int i,j;
  15. int n=strlen(a),m=strlen(b);
  16. for(i=0; i<n; ++i)
  17. for(j=0; j<m; ++j)
  18. if(a[i]==b[j])
  19. dp[i+1][j+1]=dp[i][j]+1;
  20. else
  21. dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
  22. cout<<dp[n][m]<<endl;
  23. }
  24. return 0;
  25. }
  26. #include<iostream>
  27. #include<cstdio>
  28. #include<cstdlib>
  29. #include<cstring>
  30. #include<algorithm>
  31. using namespace std;
  32. #define MAXN 10010
  33. int dp[MAXN][MAXN];
  34. int Max(int a,int b,int c)
  35. {
  36. if(a>=b&&a>=c) return a;
  37. else if(b>=a&&b>=c) return b;
  38. else if(c>=a&&c>=b) return c;
  39. }
  40. int main()
  41. {
  42. char a[MAXN],b[MAXN];
  43. while(cin>>a>>b)
  44. {
  45. int i,j;
  46. int n=strlen(a),m=strlen(b);
  47. for(i=0; i<n; ++i)
  48. for(j=0; j<m; ++j)
  49. if(a[i]==b[j])
  50. dp[i+1][j+1]=Max(dp[i][j]+1,dp[i][j+1],dp[i+1][j]);
  51. else
  52. dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
  53. cout<<dp[n][m]<<endl;
  54. }
  55. return 0;
  56. }

发表评论

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

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

相关阅读