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;
}

The function print_lcs starts from m,n and used to print the subsequence. the lcs function will find the lcs the two d array b has characters C,U,L meaning top left, upper and left elements. The output I get is not the answer, it gives a subsequence shorter than the actual answer.

For input seq 1=1000101011 & seq 2=00011101 I get lcs as 001 whereas the actual answer is 0001101

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
gospelslide
  • 179
  • 2
  • 2
  • 12

0 Answers0