Advertisement
Oibek

LCS O(n*m) + print all

Nov 29th, 2018
1,342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define ll long long
  5.  
  6. string a, b;
  7. int n, m;
  8.  
  9. int lcs[1001][1001]; //length of lcs
  10. set <string> set_lcs; //all distinct lcs
  11.  
  12. void find_lcs(int n, int m, string s)
  13. {
  14.     if (n == 0 or m == 0)
  15.     {
  16.         set_lcs.insert(s);
  17.         return;
  18.     }
  19.    
  20.     if (a[n-1] == b[m-1])
  21.     {
  22.         s = a[n-1] + s;
  23.         find_lcs(n-1, m-1, s);
  24.     }
  25.     else
  26.     {
  27.         if (lcs[n-1][m] >= lcs[n][m-1])
  28.             find_lcs(n-1, m, s);
  29.         if (lcs[n-1][m] <= lcs[n][m-1])
  30.             find_lcs(n, m-1, s);
  31.     }
  32. }
  33.  
  34. int main()
  35. {
  36.    
  37.     cin >> a >> b;
  38.     n = a.size(), m = b.size();
  39.  
  40.     for (int i = 1; i<=n; i++)
  41.     {
  42.         for (int j = 1; j<=m; j++)
  43.         {
  44.             if (a[i-1] == b[j-1]) lcs[i][j] = lcs[i-1][j-1]+1;
  45.             else lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1]);
  46.         }
  47.     }
  48.  
  49.     find_lcs(n, m, "");
  50.     cout << "LCS length is " << lcs[n][m] << endl
  51.          << "LCS number is " << set_lcs.size() << endl;
  52.     for (auto &s : set_lcs)
  53.         cout << s << " ";
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement