Experiment: 09
Aim: To implement Longest Common Subsequence and analyze it’s time
complexity
Source Code:
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> dp, direction;
// contains direction for the lcs sequence....
// the three respective direction are: 0(up), 1(down) and 2(diagonal)
string finalLCS; // will store final lcs string
void getstring(string &s, string &t, int i, int j)
{
if (i < 0 || j < 0)
{
// before ending direction array traversal, reverse the string
int n = [Link]();
for (int i = 0; i < n / 2; i++)
swap(finalLCS[i], finalLCS[n - 1 - i]);
return;
}
if (direction[i][j] == 2)
finalLCS += s[i], getstring(s, t, i - 1, j - 1);
else if (direction[i][j] == 0)
getstring(s, t, i - 1, j);
else
getstring(s, t, i, j - 1);
}
void lcs(string s, string t)
{
// assigning dp and direction tables
[Link]([Link]() + 1, vector<int>([Link]() + 1));
[Link]([Link](), vector<int>([Link]()));
for (int i = 1; i <= [Link](); i++)
{
for (int j = 1; j <= [Link](); j++)
// if equal then diagonal+1
if (s[i - 1] == t[j - 1])
dp[i][j] = dp[i - 1][j - 1] + 1, direction[i - 1][j - 1] = 2;
// if unequal then max of up and left element...
else if (dp[i - 1][j] >= dp[i][j - 1])
dp[i][j] = dp[i - 1][j], direction[i - 1][j - 1] = 0;
else
dp[i][j] = dp[i][j - 1], direction[i - 1][j - 1] = 1;
}
// getstring function to traverse
getstring(s, t, [Link]() - 1, [Link]() - 1);
cout << "The Longest Common Subsequence of " << s << " and " << t << " is: " <<
finalLCS << endl;
}
int main()
{
string s, t;
cout << "Enter first string: ";
cin >> s;
cout << "Enter the second string: ";
cin >> t;
// algorithm start
clock_t c_start = clock();
lcs(s, t);
// algorithm ends
clock_t c_end = clock();
double time_taken = double(c_end - c_start);
cout << "Time taken by Longest Common Subsequence is: " << time_taken <<
"ms" << endl;
}
Output: