当前位置:网站首页>Longest common subsequence

Longest common subsequence

2022-06-10 06:17:00 Xiao--Ming

Problem description

    A subsequence of a given sequence is a sequence obtained by deleting some elements from the sequence .

To be precise , If you give a sequence X=<x1,x2,…,xm>,

Then another sequence Z<z1,z2,,zk> yes X The subsequence of is the existence of a strictly increasing subscript sequence <i1,i2,…,ik>, Such that for all j=1,2,…,k Yes :   Xij=Zj

for example , Sequence z=<B,C,D,B> It's a sequence X=<A,B,C,B,D,A,B> The subsequence , The corresponding increasing subscript sequence is <2,3,5,7>.

The sample input

ABCBDAB

BDCABA

Sample output

 4

 BCBA

Refer to the answer :

#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
int max(int a,int b)
{
    return a>b?a:b;
}
const int maxlen=201;
int c[maxlen][maxlen];	// The length of the longest common subsequence 
int n,i,j,l1,l2;
char x[maxlen],y[maxlen];
string z="";
int main()
{
    scanf("%s%s",x,y);
    l1=strlen(x);
    l2=strlen(y);
    for (i=1; i<=l1; i++)
        for (j=1; j<=l2; j++)
            if(x[i-1]==y[j-1])
                c[i][j]=c[i-1][j-1]+1;
            else
                c[i][j]=max(c[i-1][j],c[i][j-1]);
    printf("%d\n",c[l1][l2]);
    i=l1;
    j=l2;
    while (i && j)
        if(x[i-1]==y[j-1])
        {
            z=x[--i]+z; //string Class overloads the operator “+”、“=”, Can be used directly 
            j--;
        }
        else if (c[i-1][j]>c[i][j-1])
            i--;
        else
            j--;
    printf("%s\n",z.c_str());   //string Class should add .c_str() Get the corresponding string value 
    return 0;
}

 

原网站

版权声明
本文为[Xiao--Ming]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206100617173290.html