POJ 1458 Common Subsequence (zoj 1733) LCS

Source: Internet
Author: User

 

Question:

Returns the longest common string (LCS) for two substrings)

 

If d (I, j) is set to the length of LCS of A and B, when A [I] = B [j], d (I, j) = d (I-1, j-1) + 1; otherwise d (I, j) = max (d (I-1, j), d (I, J-1)}, time complexity is O (nm ), n and m are the lengths of sequence A and sequence B, respectively.

You can use a scrolling array to optimize the space complexity.

 

The following section does not describe the use of scrolling arrays.

 

Optimized version of space without scrolling array ....

 

#include
 
  #include
  
   const int MAXN=512;char a[MAXN],b[MAXN];int dp[MAXN][MAXN];int main(){while(~scanf(%s%s,a+1,b+1)){memset(dp,0,sizeof(dp));int len_a=strlen(a+1);int len_b=strlen(b+1);for(int i=1;i<=len_a;i++){for(int j=1;j<=len_b;j++){if(a[i] == b[j])dp[i][j]= dp[i-1][j-1]+1;elsedp[i][j]= dp[i][j-1] > dp[i-1][j]? dp[i][j-1] : dp[i-1][j];}}printf(%d,dp[len_a][len_b]);}}
  
 

 

 

Scroll array optimization space:

Set dp1 to the previous column, and dp2 to the next column.

 

#include
 
  #include
  
   const int MAXN=512;char a[MAXN],b[MAXN];int dp1[MAXN],dp2[MAXN];int main(){while(~scanf(%s%s,a+1,b+1)){memset(dp1,0,sizeof(dp1));memset(dp2,0,sizeof(dp2));int len_a=strlen(a+1);int len_b=strlen(b+1);for(int i=1;i<=len_a;i++){for(int j=1;j<=len_b;j++){if(a[i] == b[j])dp2[j]= dp1[j-1]+1;elsedp2[j]= dp2[j-1] > dp1[j]? dp2[j-1] : dp1[j]; }memcpy(dp1,dp2,sizeof(dp2));}printf(%d,dp1[len_b]);}}
  
 


 

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.