hdu 1159 Common Subsequence

喜欢ヅ旅行 2022-05-31 02:10 198阅读 0赞

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

题目大意:

求两个字符串的最长公共子序列

题目解析:

当看到这个题目的时候首先想到的就是最长公共子序列,dp[i][j]表示第一个字符串的前i个字符与第二个字符串的前j个字符的最大公共子序列的长度,可以推导出状态转移方程(简单的模板题)
dp[i+1][j+1] = s1[i]==s2[j] ? dp[i][j]+1:max(dp[i][j+1] , dp[i+1][j]);

代码:

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int maxn = 1000 + 100;
  4. char s1[maxn], s2[maxn];
  5. int len1,len2;
  6. int dp[maxn][maxn];
  7. void solve()
  8. {
  9. for(int i = 0; i < len1; i++)
  10. {
  11. for(int j = 0; j < len2; j++)
  12. {
  13. if(s1[i] == s2[j])
  14. {
  15. dp[i + 1][j + 1] = dp[i][j] + 1;
  16. }
  17. else
  18. {
  19. dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]);
  20. }
  21. }
  22. }
  23. }
  24. int main()
  25. {
  26. //freopen("in.txt","r",stdin);
  27. while(cin >> s1 >> s2)
  28. {
  29. memset(dp,0,sizeof(dp));
  30. len1 = strlen(s1);
  31. len2 = strlen(s2);
  32. solve();
  33. cout<<dp[len1][len2]<<endl;
  34. }
  35. return 0;
  36. }

发表评论

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

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

相关阅读