Advertisement
shabbyheart

lcs using memoisation

Jan 12th, 2020
249
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. // C++ program to memoize
  2. // recursive implementation of LCS problem
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. const int maximum = 1000;
  7. int check=0;
  8. int lcs(string X, string Y, int m, int n, int dp[][maximum])
  9. {
  10.     check++;
  11.     if (m == 0 || n == 0)
  12.         return 0;
  13.  
  14.     if (dp[m - 1][n - 1] != -1)
  15.         return dp[m - 1][n - 1];
  16.  
  17.     if (X[m - 1] == Y[n - 1]) {
  18.  
  19.         dp[m - 1][n - 1] = 1 + lcs(X, Y, m - 1, n - 1, dp);
  20.  
  21.         return dp[m - 1][n - 1];
  22.     }
  23.     else {
  24.  
  25.         dp[m - 1][n - 1] = max(lcs(X, Y, m, n - 1, dp),
  26.                             lcs(X, Y, m - 1, n, dp));
  27.  
  28.         return dp[m - 1][n - 1];
  29.     }
  30. }
  31.  
  32. int main()
  33. {
  34.  
  35.     string X = "AGGTAB";
  36.     string Y = "GXTXAYB";
  37.     int m = X.length();
  38.     int n = Y.length();
  39.  
  40.     int dp[m][maximum];
  41.  
  42.     memset(dp, -1, sizeof(dp));
  43.  
  44.     cout << "Length of LCS: " << lcs(X, Y, m, n, dp);
  45.     cout<<endl<<check<<endl;
  46.  
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement