fork download
  1. #include<stdio.h>
  2. #include<string.h>
  3.  
  4. int i,j,m,n,c[20][20];
  5. char x[20],y[20],b[20][20];
  6.  
  7. void print(int i,int j)
  8. {
  9. if(i==0 || j==0)
  10. return;
  11. if(b[i][j]=='c')
  12. {
  13. print(i-1,j-1);
  14. printf("%c",x[i-1]);
  15. }
  16. else if(b[i][j]=='l')
  17. print(i-1,j);
  18. else
  19. print(i,j-1);
  20. }
  21.  
  22. void lcs()
  23. {
  24. m=strlen(x);
  25. n=strlen(y);
  26. for(i=0;i<=m;i++)
  27. c[i][0]=0;
  28. for(i=0;i<=n;i++)
  29. c[0][i]=0;
  30. for(i=1;i<=m;i++)
  31. for(j=1;j<=n;j++)
  32. {
  33. if(x[i-1]==y[j-1])
  34. {
  35. c[i][j]=c[i-1][j-1]+1;
  36. b[i][j]='c';
  37. }
  38. else if(c[i-1][j]>=c[i][j-1])
  39. {
  40. c[i][j]=c[i-1][j];
  41. b[i][j]='l';
  42. }
  43. else
  44. {
  45. c[i][j]=c[i][j-1];
  46. b[i][j]='u';
  47. }
  48. }
  49.  
  50. }
  51. int main()
  52. {
  53. printf("Enter 1st sequence:");
  54. scanf("%s",x);
  55. printf("Enter 2nd sequence:");
  56. scanf("%s",y);
  57. printf("\nThe Longest Common Subsequence is: ");
  58. lcs();
  59. print(m,n);
  60. printf("\nLength of LCS is: %d", c[m][n]);
  61. return 0;
  62. }
  63.  
  64.  
Success #stdin #stdout 0s 5288KB
stdin
 
stdout
Enter 1st sequence:Enter 2nd sequence:
The Longest Common Subsequence is: 
Length of LCS is: 0