fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const int N = 3e3 + 5;
  10.  
  11. int n, m;
  12. string s, t;
  13. int dp[N][N]; // dp[i][j] = Độ dài xâu con chung dài nhất khi xét các kí tự từ 1..i của xâu s
  14. // và các kí tự từ 1..j của xâu t
  15.  
  16. int main() {
  17. ios::sync_with_stdio(false);
  18. cin.tie(nullptr);
  19. cin >> s;
  20. cin >> t;
  21.  
  22. n = s.size();
  23. m = t.size();
  24.  
  25. s = ' ' + s;
  26. t = ' ' + t;
  27.  
  28. for (int i = 1; i <= n; i++) {
  29. for (int j = 1; j <= m; j++) {
  30. if (s[i] == t[j]) {
  31. dp[i][j] = dp[i - 1][j - 1] + 1; // xâu con chung dài nhất của đoạn 1..(i-1) của s và 1..(j-1) của t
  32. // bổ sung thêm kí tự chung s[i]
  33. }
  34. else { // s[i] != t[j]
  35. dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); // xem xét là bỏ đi kí tự thứ i của s,
  36. // hoặc bỏ đi kí tự thứ j của t
  37. }
  38. }
  39. }
  40.  
  41. // cout << dp[n][m] << '\n';
  42.  
  43. // Truy vết
  44. int i = n, j = m;
  45. string ans = "";
  46. while (i > 0 && j > 0) {
  47. if (s[i] == t[j]) {
  48. ans += s[i];
  49. i = i - 1, j = j - 1;
  50. }
  51. else {
  52. if (dp[i - 1][j] > dp[i][j - 1]) {
  53. i = i - 1;
  54. }
  55. else {
  56. j = j - 1;
  57. }
  58. }
  59. }
  60.  
  61. reverse(ans.begin(), ans.end());
  62.  
  63. cout << ans << '\n';
  64. }
Success #stdin #stdout 0.01s 5288KB
stdin
axyb
abyxb
stdout
ayb