// The longest common subsequence in C++
#include <iostream>
#include <cstring>
using namespace std;
void lcsAlgo(char *S1, char *S2, int m, int n) {
int LCS_table[m + 1][n + 1];
// Building the mtrix in bottom-up way
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
LCS_table[i][j] = 0;
else if (S1[i - 1] == S2[j - 1])
LCS_table[i][j] = LCS_table[i - 1][j - 1] + 1;
else
LCS_table[i][j] = max(LCS_table[i - 1][j], LCS_table[i][j - 1]);
}
}
int index = LCS_table[m][n];
char lcsAlgo[index + 1];
lcsAlgo[index] = '\0';
int i = m, j = n;
while (i > 0 && j > 0) {
if (S1[i - 1] == S2[j - 1]) {
lcsAlgo[index - 1] = S1[i - 1];
i--;
j--;
index--;
}
else if (LCS_table[i - 1][j] > LCS_table[i][j - 1])
i--;
else
j--;
}
// Printing the sub sequences
cout << "S1 : " << S1 << "\nS2 : " << S2 << "\nLCS: " << lcsAlgo << "\n";
}
int main() {
char S1[] = "ACADB";
char S2[] = "CBDA";
int m = strlen(S1);
int n = strlen(S2);
lcsAlgo(S1, S2, m, n);
}
Ly8gVGhlIGxvbmdlc3QgY29tbW9uIHN1YnNlcXVlbmNlIGluIEMrKwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3N0cmluZz4KCnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp2b2lkIGxjc0FsZ28oY2hhciAqUzEsIGNoYXIgKlMyLCBpbnQgbSwgaW50IG4pIHsKICBpbnQgTENTX3RhYmxlW20gKyAxXVtuICsgMV07CgoKICAvLyBCdWlsZGluZyB0aGUgbXRyaXggaW4gYm90dG9tLXVwIHdheQogIGZvciAoaW50IGkgPSAwOyBpIDw9IG07IGkrKykgewogICAgZm9yIChpbnQgaiA9IDA7IGogPD0gbjsgaisrKSB7CiAgICAgIGlmIChpID09IDAgfHwgaiA9PSAwKQogICAgICAgIExDU190YWJsZVtpXVtqXSA9IDA7CiAgICAgIGVsc2UgaWYg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