Sajib_Ahmed

LCS

Apr 7th, 2021
533
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #include<iostream>
  3. #include<cstring>
  4. #include<cstdlib>
  5. using namespace std;
  6.  
  7.  
  8. void lcs( char *X, char *Y, int m, int n )
  9. {
  10.    int L[m+1][n+1];
  11.  
  12.  
  13.    for (int i=0; i<=m; i++)
  14.    {
  15.      for (int j=0; j<=n; j++)
  16.      {
  17.        if (i == 0 || j == 0)
  18.          L[i][j] = 0;
  19.        else if (X[i-1] == Y[j-1])
  20.          L[i][j] = L[i-1][j-1] + 1;
  21.        else
  22.          L[i][j] = max(L[i-1][j], L[i][j-1]);
  23.      }
  24.    }
  25.  
  26.  
  27.    int index = L[m][n];
  28.  
  29.    char lcs[index+1];
  30.    lcs[index] = '\0';
  31.  
  32.  
  33.    int i = m, j = n,lk=0;
  34.    while (i > 0 && j > 0)
  35.    {
  36.  
  37.       if (X[i-1] == Y[j-1])
  38.       {
  39.           lcs[index-1] = X[i-1];
  40.           i--; j--; index--;lk++;
  41.       }
  42.  
  43.       else if (L[i-1][j] > L[i][j-1])
  44.          i--;
  45.       else
  46.          j--;
  47.    }
  48.  
  49.  
  50.  
  51.  
  52.    cout << "The LCS is :"<< lcs;
  53.    cout<<"\nThe Length of LCS is "<<lk;
  54. }
  55.  
  56.  
  57. int main()
  58. {
  59.   char X[] = "cppa";
  60.   char Y[] = "apple";
  61.  
  62.   int m = strlen(X);
  63.   int n = strlen(Y);
  64.   lcs(X, Y, m, n);
  65.   return 0;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment