jakaria_hossain

LCS

Oct 23rd, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main()
  4. {
  5. char X[100],Y[100],LCS[100];
  6. scanf("%s",X);
  7. scanf("%s",Y);
  8. int n1=strlen(X),n2=strlen(Y);
  9. int i,j,Table[n1+1][n2+1],k=0;
  10. char direction[n1+1][n2+1];
  11. for(i=0;i<=n1;i++)
  12. {
  13. for(j=0;j<=n2;j++)
  14. {
  15. if(i==0 || j==0)
  16. {
  17. Table[i][j]=0;
  18. direction[i][j]='N';
  19. }
  20. else if(X[i-1]==Y[j-1])
  21. {
  22. Table[i][j]=Table[i-1][j-1]+1;
  23. direction[i][j]='D';
  24. }
  25. else
  26. {
  27. if(Table[i-1][j]>=Table[i][j-1])
  28. {
  29. Table[i][j]=Table[i-1][j];
  30. direction[i][j]='U';
  31. }
  32. else
  33. {
  34. Table[i][j]=Table[i][j-1];
  35. direction[i][j]='L';
  36. }
  37. }
  38. }
  39. }
  40. for(j=n2,i=n1;j>=0,i>=0;j,i)
  41. {
  42. if(Table[i][j]==0)break;
  43. else if(direction[i][j]=='D')
  44. {
  45. LCS[k]=Y[j-1];
  46. i--,j--,k++;
  47. }
  48. else if(direction[i][j]=='L')j--;
  49. else if(direction[i][j]=='U')i--;
  50. }
  51. cout<<endl<<k<<endl;
  52. for(i=k-1;i>=0;i--) printf("%c",LCS[i]);
  53. cout<<endl;
  54. return 0;
  55. }
Add Comment
Please, Sign In to add comment