Experiment No.2
Experiment No.2
THEORY:
The longest common subsequence problem is finding the longest sequence which exists in both
the given strings.
Subsequence
A sequence Z = <z1, z2, z3, z4, …,zm> over S is called a subsequence of S, if and only if it can be
derived from S deletion of some elements.
Common Subsequence
Suppose, X and Y are two sequences over a finite set of elements. We can say that Z is a common
subsequence of X and Y, if Z is a subsequence of both X and Y.
If a set of sequences are given, the longest common subsequence problem is to find a common
subsequence of all the sequences that is of maximal length.
ALGO:
C = array(0..m, 0..n)
for i := 0..m
C[i,0] = 0
for j := 0..n
C[0,j] = 0
for i := 1..m
for j := 1..n
if X[i] = Y[j]
C[i,j] := C[i-1,j-1] + 1
else
return C[m,n]
ANALYSIS:
Code:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
int i,j,m,n,k;
int b[100][100],c[100][100];
char x[100],y[100];
char t[100],p[100];
clrscr();
gets(x);
gets(y);
if(strlen(x)>strlen(y))
{
m=strlen(x);
n=strlen(y);
else
m=strlen(y);
n=strlen(x);
for(i=0;i<=m;i++)
c[i][0]=0;
for(j=0;j<=n;j++)
c[0][j]=0;
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
if(x[i-1]==y[j-1])
c[i][j]=c[i-1][j-1]+1;
b[i][j]=-1;
}
else if(c[i-1][j]>=c[i][j-1])
c[i][j]=c[i-1][j];
b[i][j]=1;
else
c[i][j]=c[i][j-1];
b[i][j]=0;
for(i=0;i<=m;i++)
for(j=0;j<=n;j++)
printf("\t%d",c[i][j]);
printf("\n");
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
printf("\t %d",b[i][j]);
printf("\n");
i=m;
j=n;
k=0;
while(i>=0 || j>=0)
if(b[i][j]==1)
i--;
else if(b[i][j]==0)
j--;
else
t[k]=y[j-1];
k++;
i--;
j--;
strrev(t);
getch();
/*Use below Input and execute your code and attach output screenshot below*/
*/
Output:-