[2016-05-09] [51nod] [1006 longest common subsequence LCS]

Source: Internet
Author: User

    • Time: 2016-05-09-21:12:54
    • Title Number: [2016-05-09][51nod][1006 longest common sub-sequence LCS]
    • Main topic: [2016-05-09][51nod][1006 longest common sub-sequence lcs].md
    • Analysis: Dynamic Planning
      • DP[I][J] Represents the length of the longest common subsequence of string A in the first position, string B at position J
      • DP[I][J] = dp[i-1][j-1] + 1 if a[i] = = A[j]
      • else dp[i][j] = = Max (Dp[i-1][j], dp[i][j-1]);
      • The maximum length is dp[n][m], n is the length of a, m is the length of B
      • To restore a string, just go back to the place where the dp[i][j] just started to change.
  
 
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<algorithm>
  4. using namespace std;
  5. const int maxn = 1E3 + 10;
  6. char a[maxn],b[maxn],ans[maxn];
  7. int dp[maxn][maxn];
  8. int main(){
  9. scanf ( "%s%s " , a + 1 b + 1 );
  10. int n = strlen(a+1),m = strlen(b+1);
  11. memset(dp,0,sizeof(dp));
  12. for ( int i = 1 ; I <= n ++ i ) {
  13. for(int j = 1 ; j <= m ; ++j){
  14. if(a[i] == b[j]){
  15. DP [ i ][ j = DP [ i - 1 ][ j - 1 + 1
  16. }else dp[i][j] = max(dp[i][j-1],dp[i-1][j]);
  17. }
  18. }
  19. int cur = 0;
  20. for ( int i = n j = m DP [ i ][ j ];-- i ,-- j //return to the place where the value was first updated
  21. while ( DP [ i ][ j ] == DP [ i - 1 ][ j -- i
  22. while ( DP [ i ][ j ] == DP [ i ][ j - 1 ]) -- j ;
  23. ans[cur++] = a[i];
  24. }
  25. reverse(ans,ans+cur);
  26. ans[cur] = ‘\0‘;
  27. printf("%s\n",ans);
  28. return 0;
  29. }


From for notes (Wiz)

[2016-05-09][51nod][1006 longest common subsequence LCS]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.