Advertisement
Josif_tepe

Untitled

Mar 10th, 2022
1,269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4. #include <queue>
  5. #include <algorithm>
  6. #include <cstring>
  7. #include <fstream>
  8. using namespace std;
  9. string a, b;
  10. int dp[3005][3005];
  11. pair<int, int> backtrack[3005][3005];
  12. char bukva[3005][3005];
  13. int rec(int i, int j) {
  14.     if(i == -1 or j == -1) {
  15.         return 0;
  16.     }
  17.     if(dp[i][j] != -1) {
  18.         return dp[i][j];
  19.     }
  20.     int result = 0;
  21.     int r1 = -1, r2 = -1, r3 = -1;
  22.     if(a[i] == b[j]) {
  23.         r1 = rec(i - 1, j - 1) + 1;
  24.     }
  25.     r2 = rec(i - 1, j);
  26.     r3 = rec(i, j - 1);
  27.     result = max(r1, max(r2, r3));
  28.     if(r1 == result) {
  29.         backtrack[i][j] = make_pair(i - 1, j - 1);
  30.         bukva[i][j] = a[i];
  31.     }
  32.     else if(r2 == result) {
  33.         backtrack[i][j] = make_pair(i - 1, j);
  34.         bukva[i][j] = '/';
  35.     }
  36.     else {
  37.         backtrack[i][j] = make_pair(i, j - 1);
  38.         bukva[i][j] = '/';
  39.     }
  40.     return dp[i][j] = result;
  41. }
  42. int main() {
  43.     cin >> a >> b;
  44.     memset(dp, -1, sizeof dp);
  45.    
  46.     rec(a.size() - 1, b.size() - 1);
  47.     pair<int, int> at = make_pair(a.size() - 1, b.size() - 1);
  48.     string s = "";
  49.     while(true) {
  50.         if(at.first >= 0 and at.second >= 0) {
  51.             s += bukva[at.first][at.second];
  52.             at = make_pair(backtrack[at.first][at.second].first, backtrack[at.first][at.second].second);
  53.         }
  54.         else {
  55.             break;
  56.         }
  57.     }
  58.     for(int i = (int) s.size() - 1; i >= 0; i--) {
  59.         if(s[i] != '/') {
  60.             cout << s[i];
  61.         }
  62.     }
  63.     return 0;
  64. }
  65. // 100 000 000
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement