Advertisement
Nayeemzaman

LCS

Dec 13th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.58 KB | None | 0 0
  1.  
  2. #include<stdio.h>
  3. #include<string.h>
  4. int main()
  5. {
  6.     int i=0,j=0,lcs[100][100],lnx,lny,k;
  7.     char x[100],y[100];
  8.     printf("Enter the first(x) string : ");
  9.     scanf("%s",&x);
  10.     printf("Enter the second(y) string : ");
  11.     scanf("%s",&y);
  12.     lnx = strlen(x);
  13.     lny = strlen(y);
  14.     for(i=1; i<=lnx; i++)
  15.     {
  16.         lcs[i][0]=0;
  17.     }
  18.     for(j=1; j<=lny; j++)
  19.     {
  20.         lcs[0][j]=0;
  21.     }
  22.     for(i=1; i<=lnx; i++)
  23.     {
  24.         for(j=1; j<=lny; j++)
  25.         {
  26.             if(x[i-1]==y[j-1])
  27.             {
  28.                 lcs[i][j]=lcs[i-1][j-1]+1;
  29.             }
  30.             else if(lcs[i-1][j]>=lcs[i][j-1])
  31.             {
  32.                 lcs[i][j]=lcs[i-1][j];
  33.             }
  34.             else
  35.             {
  36.                 lcs[i][j]=lcs[i][j-1];
  37.             }
  38.         }
  39.     }
  40.     printf("\n\nLCS table:\n\n    ");
  41.     for(k=0; k<lny; k++)
  42.     {
  43.         printf("%c ",y[k]);
  44.     }
  45.     printf("\n ");
  46.     for(i=0; i<=lnx; i++)
  47.     {
  48.         if(i!=0)
  49.         {
  50.             printf("%c",x[i-1]);
  51.         }
  52.  
  53.         for(j=0; j<=lny; j++)
  54.         {
  55.             printf(" %d",lcs[i][j]);
  56.         }
  57.         printf("\n");
  58.     }
  59.     printf("\n\nThe lenght of LCS is %d\n",lcs[lnx][lny]);
  60.     i=lnx;
  61.     j=lny;
  62.     while(i>0 && j>0){
  63.         if(lcs[i-1][j]!=lcs[i][j] && lcs[i][j-1]!=lcs[i][j]){
  64.             printf("%c",x[i-1]);
  65.             i--;
  66.             j--;
  67.         }
  68.         else if(lcs[i-1][j]==lcs[i][j]){
  69.             i--;
  70.         }
  71.         else if(lcs[i][j-1]==lcs[i][j]){
  72.             j--;
  73.         }
  74.  
  75.     }
  76.  
  77.     return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement