Advertisement
rootUser

LCS

Aug 6th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.41 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3.  
  4. int i,j,m,n,c[50][50],count=0;
  5. char x[50],y[50],b[50][50];
  6.  
  7. void print_LCS(int i,int j)
  8. {
  9.     if(i==0 || j==0)
  10.     {
  11.         return;
  12.     }
  13.     if(b[i][j]=='c')
  14.     {
  15.         print_LCS(i-1,j-1);
  16.         printf("%c",x[i-1]);
  17.         count++;
  18.     }
  19.     else if(b[i][j]=='u')
  20.     {
  21.         print_LCS(i-1,j);
  22.     }
  23.     else
  24.     {
  25.         print_LCS(i,j-1);
  26.     }
  27. }
  28.  
  29. void LCS_Length()
  30. {
  31.     m=strlen(x);
  32.     n=strlen(y);
  33.     for(i=0; i<=m; i++)
  34.     {
  35.         c[i][0]=0;
  36.     }
  37.     for(i=0; i<=n; i++)
  38.     {
  39.         c[0][i]=0;
  40.     }
  41.  
  42.  
  43.     ///c -> corner
  44.     ///l -> left
  45.     ///u -> up
  46.  
  47.     for(i=1; i<=m; i++)
  48.         for(j=1; j<=n; j++)
  49.         {
  50.             if(x[i-1]==y[j-1])
  51.             {
  52.                 c[i][j]=c[i-1][j-1]+1;
  53.                 b[i][j]='c';
  54.             }
  55.             else if(c[i-1][j]>=c[i][j-1])
  56.             {
  57.                 c[i][j]=c[i-1][j];
  58.                 b[i][j]='u';
  59.             }
  60.             else
  61.             {
  62.                 c[i][j]=c[i][j-1];
  63.                 b[i][j]='l';
  64.             }
  65.         }
  66. }
  67.  
  68. int main()
  69. {
  70.     printf("Enter 1st sequence:");
  71.     scanf("%s",x);
  72.     printf("Enter 2nd sequence:");
  73.     scanf("%s",y);
  74.     printf("\nThe Longest Common Subsequence is ");
  75.     LCS_Length();
  76.     printf("<");
  77.     print_LCS(m,n);
  78.     printf("> \nThe Length of Subsequence is %d \n",count);
  79.     return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement