bhupixb

Shortest Common Super sequence

Feb 1st, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. // I can't tell you what it really is,
  2. // I can only tell you what it feels like.
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5. const int N = 1002;
  6. class Sol{
  7.  
  8. char a[N], b[N];
  9. int n, m, dp[N][N];
  10. char nextState[N][N];
  11. char ans[N][N];
  12. public:
  13. int solve(int i, int j) {
  14. if (i == n+1 && j == m+1) return 0;
  15. if (i == n+1) return m-j+1;
  16. if (j == m+1) return n-i+1;
  17. if (dp[i][j] != -1) return dp[i][j];
  18. int ok = 1000, x, y, z;
  19. if (a[i] == b[j]) {
  20. ok = 1 + solve(i+1, j+1);
  21. nextState[i][j] = 'V';
  22. ans[i][j] = a[i];
  23. }
  24. else {
  25. x = 1+solve(i+1,j);
  26. y = 1+solve(i,j+1);
  27. z = 2+solve(i+1,j+1);
  28. if (x < ok) {
  29. ok = x;
  30. ans[i][j] = a[i];
  31. nextState[i][j] = 'D';
  32. }
  33. if (y < ok) {
  34. ok = y;
  35. ans[i][j] = b[j];
  36. nextState[i][j] = 'R';
  37. }
  38. if (z < ok) {
  39. ok = z;
  40. ans[i][j] = '!';
  41. nextState[i][j] = 'V';
  42. }
  43. ok = min({x, y, z});
  44. }
  45. // cout << i << ' ' << j << ' ' << x << ' ' << y << ' ' << z << ' ' << ok << '\n';
  46. return dp[i][j] = ok;
  47. }
  48. string go(string &s1, string &s2) {
  49. for (int i = 0; i < N; ++i) {
  50. for (int j = 0; j < N; ++j) {
  51. dp[i][j] = -1;
  52. ans[i][j] = '@';
  53. nextState[i][j] = '@';
  54. }
  55. }
  56. n = s1.size(), m = s2.size();
  57. for (int i = 0; i < n; ++i) a[i+1] = s1[i];
  58. for (int i = 0; i < m; ++i) b[i+1] = s2[i];
  59. string fin;
  60. solve(1,1);
  61. int i = 1, j = 1;
  62. while (i <= n && j <= m) {
  63. if (ans[i][j] != '!')
  64. fin += ans[i][j];
  65. else fin += a[i] + b[j];
  66. if (nextState[i][j] == 'V') ++i, ++j;
  67. else if (nextState[i][j] == 'D') ++i;
  68. else if (nextState[i][j] == 'R') ++j;
  69. }
  70. while (i <= n) fin += a[i++];
  71. while (j <= m) fin += b[j++];
  72. return fin;
  73. }
  74. };
  75.  
  76. signed main() {
  77. ios::sync_with_stdio(false);
  78. cin.tie(0);
  79. string a, b;
  80. cin >> a >> b;
  81. Sol instance;
  82.  
  83. cout << "the super subsequence is : " << instance.go(a,b);
  84. return 0;
  85. }
  86. // 1). Try forming/rearranging the equations if any
  87. // 2). If problem asks to count, try counting in reverse(it can be easier sometimes)
Add Comment
Please, Sign In to add comment