#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
void LCS_Length(T* x, T* y, int m, int n, int** C, int** D) {
for (int i = 0; i <= m; i++) {
C[i][0] = 0;
}
for (int j = 0; j <= n; j++) {
C[0][j] = 0;
}
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
C[i][j] = 0;
} else if (x[i-1] == y[j-1]) {
C[i][j] = C[i-1][j-1] + 1;
D[i][j] = 1;
} else {
if (C[i-1][j] >= C[i][j-1]) {
C[i][j] = C[i-1][j];
D[i][j] = 2;
} else {
C[i][j] = C[i][j-1];
D[i][j] = 3;
}
}
}
}
}
template <typename T>
void LCS_Print(int** D, T* x, int i, int j) {
if (i == 0 || j == 0) {
return;
}
if (D[i][j] == 1) {
LCS_Print(D, x, i-1, j-1);
cout << x[i-1];
} else {
if (D[i][j] == 2) {
LCS_Print(D, x, i-1, j);
} else {
LCS_Print(D, x, i, j-1);
}
}
}
int main() {
int x_len = 8;
int y_len = 9;
int x[] = {1, 0, 0, 1, 0, 1, 0, 1};
int y[] = {0, 1, 0, 1, 1, 0, 1, 1, 0};
//x_len = 11;
//y_len = 10;
//char x1[x_len];
//char y1[y_len];
//strncpy(x1, "AHPEULALGOW", x_len);
//strncpy(y1, "HVEALQLPUO", y_len);
int** C = new int*[x_len];
int** D = new int*[x_len];
for (int i =0; i <= x_len; i++) {
C[i] = new int[y_len];
D[i] = new int[y_len];
}
for (int i ; i <= x_len; i++) {
for (int j; j <= y_len; j++) {
C[i][j] = 0;
D[i][j] = 0;
}
}
LCS_Length(x, y, x_len, y_len, C, D);
cout << "最大公共子序列: ";
LCS_Print(D, x, x_len, y_len);
cout <<endl;
int l = C[x_len][y_len];
cout << "最大公共子序列长度: " << l << endl;
for (int i =0; i <= x_len; i++) {
delete[] C[1];
delete[] D[i];
}
delete[] C;
delete[] D;
return 0;
}