August 26-Dynamic Planning of LCS

Source: Internet
Author: User

Solve the longest public subsequence problem:

Solution:

For example, the given two sequences are x = <A, B, C, B, D, a, B> and Y = <B, D, C, A, B, a>. The results calculated by the algorithms lcs_length and LCs are shown in:

The template can be written

void lcss(){    int i,j;    int sizex=str1.length();    int sizey=str2.length();    for(i=0;i<=sizex;i++)        lcs[i][0]=0;    for(i=0;i<=sizey;i++)         lcs[0][i]=0;        for(i=1;i<=sizex;i++)            for(j=1;j<=sizey;j++)            {                if(str1[i-1]==str2[j-1])                    lcs[i][j]=lcs[i-1][j-1]+1;                else                    lcs[i][j]=lcs[i-1][j]>=lcs[i][j-1]?lcs[i-1][j]:lcs[i][j-1];            }                          cout<<lcs[sizex][sizey]<<endl;  }  
View code

You can also compress the array:

memset(lcs,0,sizeof(lcs));        for(i=1;i<=n;i++)            for(j=1;j<=n;j++)            {                if(str1[i-1]==str2[j-1])                    lcs[i%2][j]=lcs[(i-1)%2][j-1]+1;                else                    lcs[i%2][j]=lcs[(i-1)%2][j]>lcs[i%2][j-1]?lcs[(i-1)%2][j]:lcs[i%2][j-1];            }    printf("%d\n",lcs[n%2][n]) ; 
View code

 

 

Training Questions:

Http://acm.hdu.edu.cn/diy/contest_show.php? Cid = 24575

August 26-Dynamic Planning of 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.