Advertisement
Okorosso

Наибольшая общая подпоследовательность

Jun 4th, 2021
774
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9.     ifstream fin("input.txt");
  10.     ofstream fout("output.txt");
  11.  
  12.  
  13.     vector<vector<int>> prev;
  14.     string a, b;
  15.     fin >> b >> a;
  16.     int n = a.size() + 1, m = b.size() + 1;
  17.  
  18.     vector<vector<int>> LCS(n, vector<int>(m));
  19.     vector<char> L;
  20.     for (int i = 0; i < n; i++) {
  21.         for (int j = 0; j < m; j++) {
  22.             LCS[i][j] = 0;
  23.         }
  24.     }
  25.  
  26.     for (int i = 1; i < n; i++) {
  27.         for (int j = 1; j < m; j++) {
  28.             if (a[i - 1] == b[j - 1]) {
  29.                 LCS[i][j] = LCS[i - 1][j - 1] + 1;
  30.             } else {
  31.                 LCS[i][j] = max((LCS[i - 1][j]), (LCS[i][j - 1]));
  32.             }
  33.         }
  34.     }
  35.  
  36.     int i = n;
  37.     int j = m;
  38.     while (i > 0 && j > 0) {
  39.         if (a[i - 1] == b[j - 1]) {
  40.             L.push_back(a[i - 1]);
  41.             i--;
  42.             j--;
  43.         } else if (LCS[i - 1][j] == LCS[i][j]) {
  44.             i--;
  45.         } else {
  46.             j--;
  47.         }
  48.     }
  49.  
  50.     for (int i = L.size() - 1; i > 0; i--) {
  51.         fout << L[i];
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement