Advertisement
pkbagchi

LCS1

Mar 26th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. /* Dynamic Programming C/C++ implementation of LCS problem */
  2. #include<bits/stdc++.h>
  3.    
  4. int max(int a, int b);
  5.    
  6. /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
  7. int lcs( char *X, char *Y, int m, int n )
  8. {
  9.    int L[m+1][n+1];
  10.    int i, j;
  11.    
  12.    /* Following steps build L[m+1][n+1] in bottom up fashion. Note  
  13.       that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
  14.    for (i=0; i<=m; i++)
  15.    {
  16.      for (j=0; j<=n; j++)
  17.      {
  18.        if (i == 0 || j == 0)
  19.          L[i][j] = 0;
  20.    
  21.        else if (X[i-1] == Y[j-1])
  22.          L[i][j] = L[i-1][j-1] + 1;
  23.    
  24.        else
  25.          L[i][j] = max(L[i-1][j], L[i][j-1]);
  26.      }
  27.    }
  28.      
  29.    /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */
  30.    return L[m][n];
  31. }
  32.    
  33. /* Utility function to get max of 2 integers */
  34. int max(int a, int b)
  35. {
  36.     return (a > b)? a : b;
  37. }
  38.    
  39. /* Driver program to test above function */
  40. int main()
  41. {
  42.   char X[] = "AGGTAB";
  43.   char Y[] = "GXTXAYB";
  44.    
  45.   int m = strlen(X);
  46.   int n = strlen(Y);
  47.    
  48.   printf("Length of LCS is %d", lcs( X, Y, m, n ) );
  49.  
  50.   return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement