fork download
  1. #include <bits/stdc++.h>
  2.  
  3. #define ll long long
  4. #define el cout << '\n'
  5. #define ic pair<int, int>
  6. #define fi first
  7. #define se second
  8.  
  9. using namespace std;
  10.  
  11. const int maxn = 1e6;
  12. const int INF = 1e9;
  13.  
  14. struct Node
  15. {
  16. ic best_1, best_2;
  17.  
  18. Node(ic best_1 = ic(INF, '#'), ic best_2 = ic(INF, '#')) :
  19. best_1(best_1), best_2(best_2) {};
  20. };
  21.  
  22. int n, ans = INF;
  23. Node dp[maxn + 10][5];
  24. string s;
  25.  
  26. char get_char(char c, int v)
  27. {
  28. v -= 2;
  29. c += v;
  30. if (c < 'a')
  31. c += 'z' - 'a' + 1;
  32. if (c > 'z')
  33. c -= 'z' - 'a' + 1;
  34. return c;
  35. }
  36. void minimize(Node &a, ic b)
  37. {
  38. if (a.best_1.fi >= b.fi)
  39. {
  40. if (a.best_1.se != b.se)
  41. a.best_2 = a.best_1;
  42. a.best_1 = b;
  43. }
  44. else if (a.best_2.fi >= b.fi && a.best_1.se != b.se)
  45. a.best_2 = b;
  46. }
  47.  
  48. int main()
  49. {
  50. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  51. if (fopen("REMOVEPALIN.INP", "r"))
  52. {
  53. freopen("REMOVEPALIN.INP", "r", stdin);
  54. freopen("REMOVEPALIN.OUT", "w", stdout);
  55. }
  56.  
  57. cin >> s;
  58. n = s.size();
  59. s = ' ' + s;
  60. if (n == 1)
  61. return cout << 0, 0;
  62. for (int y = 0; y <= 4; y++)
  63. for (int x = 0; x <= 4; x++)
  64. if (get_char(s[2], y) != get_char(s[1], x))
  65. minimize(dp[2][y], ic(abs(y - 2) + abs(x - 2), get_char(s[1], x)));
  66. for (int i = 3; i <= n; i++)
  67. {
  68. for (int y = 0; y <= 4; y++)
  69. {
  70. for (int x = 0; x <= 4; x++)
  71. {
  72. if (get_char(s[i - 1], x) == get_char(s[i], y))
  73. continue;
  74. if (get_char(s[i], y) != dp[i - 1][x].best_1.se)
  75. minimize(dp[i][y], ic(dp[i - 1][x].best_1.fi + abs(y - 2), get_char(s[i - 1], x)));
  76. if (get_char(s[i], y) != dp[i - 1][x].best_2.se)
  77. minimize(dp[i][y], ic(dp[i - 1][x].best_2.fi + abs(y - 2), get_char(s[i - 1], x)));
  78. }
  79. }
  80. }
  81. // for (int i = 2; i <= n; i++)
  82. // for (int y = 0; y <= 4; y++)
  83. // cout << i << ' ' << get_char(s[i], y) << ' ' << dp[i][y].best_1.fi << ' ' << (char)dp[i][y].best_1.se << ' ' << dp[i][y].best_2.fi << ' ' << (char)dp[i][y].best_2.se, el;
  84. for (int x = 0; x <= 4; x++)
  85. ans = min(ans, dp[n][x].best_1.fi);
  86. cout << ans;
  87. }
Success #stdin #stdout 0.03s 81732KB
stdin
Standard input is empty
stdout
1000000000