You are on page 1of 3

//PROGRAM FOR LONGEST COMMON SUBSEQUENCE

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#define MAX 12
void LCS_Length(char[],char[],int,int);
void print_LCS(char[MAX][MAX],char[],int,int);
void main()
{
char X[10],Y[10],ans;
int i,j;
clrscr();
cout<<"\nEnter the first sequence(less then or equal to 10 charaters):";
gets(X);
i=strlen(X);
cout<<"\nEnter the second sequence:";
gets(Y);
j=strlen(Y);
LCS_Length(X,Y,i,j);
getch();
}
void LCS_Length(char X[10],char Y[10],int m,int n)
{
int i,j;
int C[MAX][MAX];
char B[MAX][MAX];
for(i=0;i<MAX;i++)
for(j=0;j<MAX;j++)
B[i][j]='0';
for(i=1;i<=m;i++)
C[i][0]=0;
for(j=0;j<=n;j++)
C[0][j]=0;
for(i=0;i<=m;i++)
{
for(j=0;j<=n;j++)
{
if(X[i]==Y[j])
{

C[i+1][j+1]=C[i][j]+1;
B[i+1][j+1]='\\';
}
else if(C[i][j+1]>=C[i+1][j])
{
C[i+1][j+1]=C[i][j+1];
B[i+1][j+1]='|';
}
else
{
C[i+1][j+1]=C[i+1][j];
B[i+1][j+1]='-';
}
}
}
cout<<"The C matrix is:\n";
for(i=0;i<=m;i++)
{
for(j=0;j<=n;j++)
cout<<"\t"<<C[i][j];
cout<<"\n";
}
cout<<"The B matrix is:\n";
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
cout<<"\t"<<B[i][j];
cout<<"\n";
}
cout<<"\nThe combined Matrix C & B is \n";
for(i=0;i<=m;i++)
{
for(j=0;j<=n;j++)
{
if((i==0)||(j==0))
cout<<C[i][j];
else
cout<<B[i][j]<<C[i][j];
}
cout<<"\n";
}
cout<<"\nThe length of the Longest Common Subsequence is \n"<<C[m][n];
cout<<"\nThe Longest Sequence is : ";
print_LCS(B,X,m,n);
}
void print_LCS(char B[MAX][MAX],char X[10],int i,int j)

{
if(i==0||j==0)
return;
if(B[i][j]=='\\')
{
print_LCS(B,X,i-1,j-1);
cout<<X[i-1];
}
else if(B[i][j]=='|')
print_LCS(B,X,i-1,j);
else
print_LCS(B,X,i,j-1);
}

You might also like