Given two sequences, print the longest subsequence present in both of them.
Examples:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
#include<iostream>
#include<cstring>
#include<cstdlib>
using
namespace
std;
void
lcs(
char
*X,
char
*Y,
int
m,
int
n )
{
int
L[m+1][n+1];
for
(
int
i=0; i<=m; i++)
{
for
(
int
j=0; j<=n; j++)
{
if
(i == 0 || j == 0)
L[i][j] = 0;
else
if
(X[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
int
index = L[m][n];
char
lcs[index+1];
lcs[index] =
'\0'
;
int
i = m, j = n;
while
(i > 0 && j > 0)
{
if
(X[i-1] == Y[j-1])
{
lcs[index-1] = X[i-1];
i--; j--; index--;
}
else
if
(L[i-1][j] > L[i][j-1])
i--;
else
j--;
}
cout <<
"LCS of "
<< X <<
" and "
<< Y <<
" is "
<< lcs;
}
int
main()
{
char
X[] =
"AGGTAB"
;
char
Y[] =
"GXTXAYB"
;
int
m =
strlen
(X);
int
n =
strlen
(Y);
lcs(X, Y, m, n);
return
0;
}
def lcs(X, Y, m, n):
L = [[ 0 for x in xrange (n + 1 )] for x in xrange (m + 1 )]
for i in xrange (m + 1 ):
for j in xrange (n + 1 ):
if i = = 0 or j = = 0 :
L[i][j] = 0
elif X[i - 1 ] = = Y[j - 1 ]:
L[i][j] = L[i - 1 ][j - 1 ] + 1
else :
L[i][j] = max (L[i - 1 ][j], L[i][j - 1 ])
index = L[m][n]
lcs = [""] * (index + 1 )
lcs[index] = ""
i = m
j = n
while i > 0 and j > 0 :
if X[i - 1 ] = = Y[j - 1 ]:
lcs[index - 1 ] = X[i - 1 ]
i - = 1
j - = 1
index - = 1
elif L[i - 1 ][j] > L[i][j - 1 ]:
i - = 1
else :
j - = 1
print "LCS of " + X + " and " + Y + " is " + "".join(lcs)
X = "AGGTAB"
Y = "GXTXAYB"
m = len (X)
n = len (Y)
lcs(X, Y, m, n)
|
Output:
LCS of AGGTAB and GXTXAYB is GTAB
Comments
Post a Comment