|
| 1 | +#include <iostream> |
| 2 | +#include <math.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +void print(string s1, int **dp, int **s, int m, int n) |
| 6 | +{ |
| 7 | + if (n >= 1 && m >= 1) |
| 8 | + { |
| 9 | + if (s[m][n] == 1) |
| 10 | + { |
| 11 | + print(s1, dp, s, m - 1, n - 1); |
| 12 | + cout << s1[m - 1]; |
| 13 | + } |
| 14 | + else if (s[m][n] == 2) |
| 15 | + { |
| 16 | + print(s1, dp, s, m, n - 1); |
| 17 | + } |
| 18 | + else |
| 19 | + { |
| 20 | + print(s1, dp, s, m - 1, n); |
| 21 | + } |
| 22 | + return; |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +int main() |
| 27 | +{ |
| 28 | + string s1, s2; |
| 29 | + cin >> s1; |
| 30 | + cin >> s2; |
| 31 | + int m = s1.length(); |
| 32 | + int n = s2.length(); |
| 33 | + |
| 34 | + // int dp[m + 1][n + 1]; |
| 35 | + int **dp = (int **)malloc((m + 1) * sizeof(int *)); |
| 36 | + for (int i = 0; i < m + 1; i++) |
| 37 | + { |
| 38 | + dp[i] = (int *)malloc((n + 1) * sizeof(int)); |
| 39 | + } |
| 40 | + |
| 41 | + for (int i = 0; i < m + 1; i++) |
| 42 | + { |
| 43 | + dp[i][0] = 0; |
| 44 | + } |
| 45 | + for (int j = 0; j < n + 1; j++) |
| 46 | + { |
| 47 | + dp[0][j] = 0; |
| 48 | + } |
| 49 | + // int s[m + 1][n + 1]; |
| 50 | + int **s = (int **)malloc((m + 1) * sizeof(int *)); |
| 51 | + for (int i = 0; i < m + 1; i++) |
| 52 | + { |
| 53 | + s[i] = (int *)malloc((n + 1) * sizeof(int)); |
| 54 | + } |
| 55 | + for (int i = 1; i < m + 1; i++) |
| 56 | + { |
| 57 | + for (int j = 1; j < n + 1; j++) |
| 58 | + { |
| 59 | + |
| 60 | + if (s1[i - 1] == s2[j - 1]) |
| 61 | + { |
| 62 | + dp[i][j] = dp[i - 1][j - 1] + 1; |
| 63 | + s[i][j] = 1; |
| 64 | + } |
| 65 | + else |
| 66 | + { |
| 67 | + if (dp[i - 1][j] < dp[i][j - 1]) |
| 68 | + { |
| 69 | + dp[i][j] = dp[i][j - 1]; |
| 70 | + s[i][j] = 2; |
| 71 | + } |
| 72 | + else |
| 73 | + { |
| 74 | + dp[i][j] = dp[i - 1][j]; |
| 75 | + s[i][j] = 3; |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + } |
| 80 | + cout << dp[m][n] << "\n"; |
| 81 | + print(s1, dp, s, m, n); |
| 82 | + return 0; |
| 83 | +} |
0 commit comments