//
// main.cpp
// Finding Longest Common Subsequence
//
// Created by Himanshu on 14/06/24.
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void printLCSTable(const int m, const int n, vector<vector<int>> dp) {
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
cout << dp[i][j] << " ";
}
cout<<endl;
}
}
vector<vector<int>> LCSTable(const string& X, const string& Y) {
int m = (int) X.length();
int n = (int) Y.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (X[i - 1] == Y[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp;
}
string findLCS(const string& X, const string& Y, const vector<vector<int>>& dp) {
int i = (int) X.length();
int j = (int) Y.length();
string lcs;
while (i > 0 && j > 0) {
cout << "X: " << X[i-1] << ", Y: " << Y[j-1] << "; i: " << i << ", j: " << j << endl;
if (X[i - 1] == Y[j - 1]) {
lcs = X[i - 1] + lcs; // Add this character to the LCS
i--;
j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
i--; // Move Up
} else {
j--; // Move Left
}
}
return lcs;
}
int main() {
string X = "ATDBM";
string Y = "BATCB";
vector<vector<int>> dp = LCSTable(X, Y);
string lcs = findLCS(X, Y, dp);
cout << "The Longest Common Subsequence is: " << lcs << endl << endl;
cout<<"LCS Table"<<endl;
printLCSTable((int) X.size(), (int) Y.size(), dp);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBGaW5kaW5nIExvbmdlc3QgQ29tbW9uIFN1YnNlcXVlbmNlCi8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDE0LzA2LzI0LgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8c3RyaW5nPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKdm9pZCBwcmludExD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y: B; i: 5, j: 5
X: B, Y: B; i: 4, j: 5
X: D, Y: C; i: 3, j: 4
X: D, Y: T; i: 3, j: 3
X: T, Y: T; i: 2, j: 3
X: A, Y: A; i: 1, j: 2
The Longest Common Subsequence is: ATB
LCS Table
0 0 0 0 0 0
0 0 1 1 1 1
0 0 1 2 2 2
0 0 1 2 2 2
0 1 1 2 2 3
0 1 1 2 2 3