1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <bits/stdc++.h> using namespace std;
string a, b; int dp[100][100]; int c[100][100]; void printAns(int i, int j) {
if (i == -1 || j == -1) return; if (c[i][j] == 0) { printAns(i - 1, j - 1); cout << a[i]; } else if (c[i][j] == 1) printAns(i, j - 1); else printAns(i - 1, j); } int main() {
cin >> a >> b; dp[0][0] = 0; for (int i = 0; i < a.size(); i++) for (int j = 0; j < b.size(); j++) {
if (a[i] == b[j]) { dp[i + 1][j + 1] = dp[i][j] + 1; c[i][j] = 0; } else { if (dp[i + 1][j] > dp[i + 1][j]) { dp[i + 1][j + 1] = dp[i + 1][j]; c[i][j] = 1; } else { dp[i + 1][j + 1] = dp[i][j + 1]; c[i][j] = -1; } } } cout << dp[a.size()][b.size()] << endl; printAns(a.size() - 1, b.size() - 1); cout << endl; }
|