2020-05-30 07:26:30 +08:00
|
|
|
// Longest common subsequence - Dynamic Programming
|
2016-11-28 00:21:40 +08:00
|
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
2017-04-10 17:59:58 +08:00
|
|
|
|
2020-05-30 12:02:09 +08:00
|
|
|
void Print(int trace[20][20], int m, int n, string a) {
|
|
|
|
if (m == 0 || n == 0) {
|
2018-03-28 05:14:19 +08:00
|
|
|
return;
|
|
|
|
}
|
2020-05-30 12:02:09 +08:00
|
|
|
if (trace[m][n] == 1) {
|
2019-08-21 10:10:08 +08:00
|
|
|
Print(trace, m - 1, n - 1, a);
|
|
|
|
cout << a[m - 1];
|
2020-05-30 12:02:09 +08:00
|
|
|
} else if (trace[m][n] == 2) {
|
2019-08-21 10:10:08 +08:00
|
|
|
Print(trace, m - 1, n, a);
|
2020-05-30 12:02:09 +08:00
|
|
|
} else if (trace[m][n] == 3) {
|
2019-08-21 10:10:08 +08:00
|
|
|
Print(trace, m, n - 1, a);
|
2018-03-28 05:14:19 +08:00
|
|
|
}
|
2017-04-10 17:59:58 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 12:02:09 +08:00
|
|
|
int lcs(string a, string b) {
|
2018-03-28 05:14:19 +08:00
|
|
|
int m = a.length(), n = b.length();
|
2019-08-21 10:10:08 +08:00
|
|
|
int res[m + 1][n + 1];
|
2018-03-28 05:14:19 +08:00
|
|
|
int trace[20][20];
|
|
|
|
|
|
|
|
// fills up the arrays with zeros.
|
2020-05-30 12:02:09 +08:00
|
|
|
for (int i = 0; i < m + 1; i++) {
|
|
|
|
for (int j = 0; j < n + 1; j++) {
|
2018-03-28 05:14:19 +08:00
|
|
|
res[i][j] = 0;
|
|
|
|
trace[i][j] = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-30 12:02:09 +08:00
|
|
|
for (int i = 0; i < m + 1; ++i) {
|
|
|
|
for (int j = 0; j < n + 1; ++j) {
|
|
|
|
if (i == 0 || j == 0) {
|
2018-03-28 05:14:19 +08:00
|
|
|
res[i][j] = 0;
|
2019-08-21 10:10:08 +08:00
|
|
|
trace[i][j] = 0;
|
2018-03-28 05:14:19 +08:00
|
|
|
}
|
|
|
|
|
2020-05-30 12:02:09 +08:00
|
|
|
else if (a[i - 1] == b[j - 1]) {
|
2019-08-21 10:10:08 +08:00
|
|
|
res[i][j] = 1 + res[i - 1][j - 1];
|
2020-05-30 07:26:30 +08:00
|
|
|
trace[i][j] = 1; // 1 means trace the matrix in upper left
|
|
|
|
// diagonal direction.
|
2020-05-30 12:02:09 +08:00
|
|
|
} else {
|
|
|
|
if (res[i - 1][j] > res[i][j - 1]) {
|
2019-08-21 10:10:08 +08:00
|
|
|
res[i][j] = res[i - 1][j];
|
2020-05-30 07:26:30 +08:00
|
|
|
trace[i][j] =
|
|
|
|
2; // 2 means trace the matrix in upwards direction.
|
2020-05-30 12:02:09 +08:00
|
|
|
} else {
|
2019-08-21 10:10:08 +08:00
|
|
|
res[i][j] = res[i][j - 1];
|
2020-05-30 07:26:30 +08:00
|
|
|
trace[i][j] =
|
|
|
|
3; // means trace the matrix in left direction.
|
2018-03-28 05:14:19 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Print(trace, m, n, a);
|
|
|
|
return res[m][n];
|
2016-11-28 00:21:40 +08:00
|
|
|
}
|
2017-04-10 17:59:58 +08:00
|
|
|
|
2020-05-30 12:02:09 +08:00
|
|
|
int main() {
|
2019-08-21 10:10:08 +08:00
|
|
|
string a, b;
|
|
|
|
cin >> a >> b;
|
|
|
|
cout << lcs(a, b);
|
2018-03-28 05:14:19 +08:00
|
|
|
return 0;
|
2017-04-10 17:01:19 +08:00
|
|
|
}
|