Wednesday, 4 September 2013

LONGEST COMMON SUBSEQUENCE C PROGRAM



/*CSEMATTER.BLOGSPOT.IN
PROGRAM:C PROGRAM FOR LCS*/

#include<stdio.h>
#include<conio.h>
void print_lcs(char b[20][20],char x[],int,int);
int main()
{
char arr[10],arr1[10];
char b[20][20];
int i,j,k,num,num1,c[20][20];
printf("enter the values to be entered for 1st");
scanf("%d",&num);
 printf("enter the string x\n");
 for(i=1;i<=num;i++)
 scanf("%s",&arr[i]);
 printf("enter the values to be entered for 2nd");
 scanf("%d",&num1);
 printf("enter the string y\n");
  for(i=1;i<=num1S;i++)
  scanf("%s",&arr1[i]);
   for(i=1;i<=num;i++)
   c[i][0]=0;
for(j=0;j<=num1;j++)
c[0][j]=0;
  for(i=1;i<=num;i++)
   {
    for(j=1;j<=num1;j++)
     {
     if(arr[i]==arr1[j])
     {c[i][j]=c[i-1][j-1]+1;
      b[i][j]='d'; // d is for diagonal
     }
     else if(c[i-1][j]>=c[i][j-1])
     {c[i][j]=c[i-1][j];
     b[i][j]='u'; // u is for up
     }
   else
     {c[i][j]=c[i][j-1];
     b[i][j]='s'; // s is for right side
     }
     }
  }
    for(i=0;i<=num;i++)
    {
    for(j=0;j<=num1;j++)
     {
      printf("\t%d",c[i][j]);
     }
     printf("\n");
    }
printf("\n the notation matrix is:\n");
 for(i=1;i<=num;i++)
 {
  for(j=1;j<=num1;j++)
  {
   printf("\t%c",b[i][j]);
  }
  printf("\n");
 }
  printf("\nthe mateched string \n");
  print_lcs(b,arr,num,num1);

   getch();
}

void print_lcs(char e[20][20],char x[10],int i,int j)
{
 if(i==0 || j==0)
 {
  return ;
 }
 if( e[i][j]=='d')
 {
 printf("\t%c",x[i]);
 print_lcs(e,x,i-1,j-1);
 }
 else if (e[i][j]=='u')
{
print_lcs(e,x,i-1,j);
}
else
{
 print_lcs(e,x,i,j-1);
}
}

/*OUTPUT:

enter the values to be entered for 1st7
enter the string x
a
b
c
b
d
a
b
enter the values to be entered for 2nd6
enter the string Y
b
d
c
a
b
a

        0       0       0       0       0       0       0
        0       0       0       0       1       1       1
        0       1       1       1       1       2       2
        0       1       1       2       2       2       2
        0       1       1       2       2       3       3
        0       1       2       2       2       3       3
        0       1       2       2       3       3       4
        0       1       2       2       3       4       4

 the notation matrix is:
        u       u       u       d       s       d
        d       s       s       u       d       s
        u       u       d       s       u       u
        d       u       u       u       d       s
        u       d       u       u       u       u
        u       u       u       d       u       d
        d       u       u       u       d       u

the mateched string
        a       b       c       b
*/

1 comment: