Mim527

lcs

Jul 21st, 2020
1,205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.14 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. int i,j,m,n,c[10][10];
  4. char x[10],y[10],b[10][10];
  5.  
  6. void print(int i, int j)
  7. {
  8.     if(i==0 || j==0)
  9.         return;
  10.     if(b[i][j]=='c')
  11.     {
  12.         print(i-1,j-1);
  13.         printf("%c",x[i-1]);
  14.     }
  15.     else if(b[i][j]=='u')
  16.         print(i-1,j);
  17.     else
  18.         print(i,j-1);
  19. }
  20. void LCS()
  21. {
  22.     m=strlen(x);
  23.     n=strlen(y);
  24.     for(i=0; i<=m; i++)
  25.         c[i][0]=0;
  26.     for(i=0; i<=n; i++)
  27.         c[0][i]=0;
  28.     for(i=1; i<=m; i++)
  29.         for(j=1; j<=n; j++)
  30.         {
  31.             if(x[i-1]==y[j-1])
  32.             {
  33.                 c[i][j]=c[i-1][j-1]+1;
  34.                 b[i][j]='c';
  35.             }
  36.             else if(c[i-1][j]>=c[i][j-1])
  37.             {
  38.                 c[i][j]=c[i-1][j];
  39.                 b[i][j]='u';
  40.             }
  41.             else
  42.             {
  43.                 c[i][j]=c[i][j-1];
  44.                 b[i][j]='l';
  45.             }
  46.         }
  47. }
  48. int main()
  49. {
  50.     printf("Enter 1st sequence:");
  51.     scanf("%s",x);
  52.     printf("Enter 2nd sequence:");
  53.     scanf("%s",y);
  54.     printf("\nThe Longest Common Subsequence is ");
  55.     LCS();
  56.     print(m,n);
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment