0
#include <stdio.h>
#include <string.h>

int m,n,a,c[20][20];
char x[15],y[15],b[20][20];

void print_lcs(int i,int j)
{
    if(i==0 || j==0)
        return;
    if(b[i][j]=='C')
    {
        print_lcs(i-1,j-1);
        printf("%c",x[i-1]);
    }
    else if(b[i][j]=='U')
        print_lcs(i-1,j);
    else
        print_lcs(i,j-1);
}

void lcs()
{
    int i,j;
    m=strlen(x);
    n=strlen(y);
    for(i=0;i<=m;i++)
        c[i][0]=0;
    for(i=0;i<=n;i++)
    {
        printf("0\t");
        c[0][i]=0;
    }
    printf("\n");
    for(i=1;i<=m;i++)
    {
        printf("0\t");
        for(j=1;j<=n;j++)
        {
            if(x[i-1]==y[i-1])
            {
                c[i][j]=c[i-1][j-1]+1;
                b[i][j]='C';
                printf("%dC\t",c[i][j]);
            }
            else if(c[i-1][j]>=c[i][j-1])
            {
                c[i][j]=c[i-1][j];
                b[i][j]='U';
                printf("%dU\t",c[i][j]);
            }
            else
            {
                c[i][j]=c[i][j-1];
                b[i][j]='L';
                printf("%dL\t",c[i][j]);
            }
        }
        printf("\n\n");
    }
    printf("\nLongest common subsequence is:");
    print_lcs(m,n);
    printf("\n");
    printf("\nThe length of the subsequence is:%d",c[m][n]);
}

int main()
{
    printf("Enter the 1st sequence:");
    scanf("%s",&x);
    printf("\nEnter the 2nd sequence:");
    scanf("%s",&y);
    lcs();
    printf("\n");
    getch();
    return 0;
}

函数 print_lcs 从 m,n 开始,用于打印子序列。lcs 函数将找到 lcs 的两个 d 数组 b 有字符 C,U,L 表示左上、上和左元素。我得到的输出不是答案,它给出的子序列比实际答案短。

对于输入 seq 1= 1000101011& seq 2=00011101我得到 lcs as001而实际答案是0001101

4

0 回答 0