The longest common sub-sequence problem of LSC

Source: Internet
Author: User

Same as most LCS algorithms on the web. Implementations are implemented using DP. The state transfer equation is not written. Skilled in the heart anyway.

Prints the shortest sequence that contains a and B. Of course, the relative position of the characters in A and b in the new sequence will not change.

The main is to familiarize yourself with the code:

#include <cstdio>#include<cstring>using namespacestd;Chara[ +],b[ +];intvisit[ +][ +],dp[ +][ +];voidpriintXinty) {    if(x==0&&y==0)        return ; if(visit[x][y]==1) {pri (x-1, Y1); printf ("%c", a[x-1]); }Else if(visit[x][y]==2) {pri (x-1, y); printf ("%c", a[x-1]); }Else if(visit[x][y]==3) {pri (x, y-1); printf ("%c", b[y-1]); }Else if(visit[x][y]==0&&x>0&&y==0) {pri (x-1, y); printf ("%c", a[x-1]); }Else if(visit[x][y]==0&&y>0&&x==0) {pri (x, y-1); printf ("%c", b[y-1]); }}intMain () { while(SCANF ("%s%s", B)) {        intLa=strlen (a), lb=strlen (b); Memset (DP,0,sizeof(DP)); memset (Visit,0,sizeof(visit));  for(intI=1; i<=la;i++)        {             for(intj=1; j<=lb;j++)            {                if(a[i-1]==b[j-1]) {Dp[i][j]=dp[i-1][j-1]+1; VISIT[I][J]=1; }                Else if(dp[i-1][j]>dp[i][j-1]) {Dp[i][j]=dp[i-1][j]; VISIT[I][J]=2; }                Else if(dp[i-1][j]<=dp[i][j-1]) {Dp[i][j]=dp[i][j-1]; VISIT[I][J]=3;        }}} pri (LA,LB); printf ("\ n"); }    return 0;}

More familiar with the code. It is certainly best to be clear about the heart. Come on.

The longest common sub-sequence problem of LSC

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.