Common Subsequence

╰半橙微兮° 2022-04-13 14:40 272阅读 0赞

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

分析:这个题,也是简单的动态规划。主要考虑,一个数列的前i项和前j项,所能构成的最大子序列。
  1. /*#include"stdio.h"
  2. #include"string.h"
  3. char a[1000];
  4. char b[1000];
  5. int dp[1000][1000];
  6. int max(int a,int b)
  7. {
  8. if(a<b)
  9. return b;
  10. else
  11. return a;
  12. }
  13. int fdp(int i,int j)
  14. { if(dp[i][j]!=0)
  15. return dp[i][j];
  16. if(i==0||j==0)
  17. return 0;
  18. else
  19. {
  20. if(a[i-1]==b[j-1])
  21. return fdp(i-1,j-1)+1;
  22. else
  23. {
  24. return max(fdp(i-1,j),fdp(i,j-1));
  25. }
  26. }
  27. }
  28. int main()
  29. { int i,j;
  30. while(~scanf("%s%s",a,b))
  31. { memset(dp,0,sizeof(dp));
  32. i=strlen(a);
  33. j=strlen(b);
  34. memset(dp,0,sizeof(dp));
  35. printf("%d\n",fdp(i,j));
  36. }
  37. }
  38. */
  39. //上面是用递归做的一个程序。但是时间超限。于是采用下面这种dp。也是用循环所做本意是一样的。
  40. #include"stdio.h"
  41. #include"string.h"
  42. int max(int a,int b)
  43. {
  44. if(a<b)
  45. return b;
  46. else
  47. return a;
  48. }
  49. char a[1000],b[1000];
  50. int dp[1000][1000];
  51. int main()
  52. {
  53. int x,y,i,j;;
  54. while(~scanf("%s%s",a,b))
  55. {
  56. x=strlen(a);
  57. y=strlen(b);
  58. for(i=0; i<x; i++)
  59. {
  60. dp[0][i]=0;
  61. }
  62. for(i=0; i<y; i++)
  63. dp[i][0]=0;
  64. for(i=1; i<=x; i++)//因为要下面的判断是a[i-1]==b[j-1]。所以这里需要等于x
  65. for(j=1; j<=y; j++)
  66. {
  67. if(a[i-1]==b[j-1])
  68. dp[i][j]=dp[i-1][j-1]+1;
  69. else
  70. {
  71. dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
  72. }
  73. }
  74. printf("%d\n",dp[x][y]);
  75. }
  76. }

发表评论

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

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

相关阅读