Advertisement
Guest User

Untitled

a guest
Oct 4th, 2019
481
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include <vector>
  5.  
  6.  
  7. void computeArray(const std::string& substring, std::vector<int>& arr)
  8. {
  9. int i = 0;
  10. int j = 1;
  11.  
  12. while (j < substring.length())
  13. {
  14. if (substring[i] == substring[j])
  15. {
  16. i++;
  17. arr[j] = i;
  18. j++;
  19. }
  20. else
  21. {
  22. if (i != 0)
  23. {
  24. i = arr[i - 1];
  25. }
  26. else
  27. {
  28. arr[j] = 0;
  29. j++;
  30. }
  31. }
  32. }
  33. }
  34.  
  35.  
  36. bool KMP(const std::string& recipeScores, int& index, const std::vector<int>& arr, int score)
  37. {
  38. if (recipeScores[index] - '0' == score)
  39. {
  40. index++;
  41. if (index == recipeScores.length())
  42. {
  43. return true;
  44. }
  45. }
  46. else
  47. {
  48. while (index != 0)
  49. {
  50. index = arr[index - 1];
  51.  
  52. if (recipeScores[index] - '0' == score)
  53. {
  54. index++;
  55. return false;
  56. }
  57. }
  58. }
  59.  
  60. return false;
  61. }
  62.  
  63.  
  64. void findRecipeScores(std::string& scores, const std::string& recipesScores)
  65. {
  66. int firstElf = 0;
  67. int secondElf = 1;
  68. int sum = 0;
  69. int index = 0;
  70.  
  71. std::vector<int> arr(recipesScores.length());
  72. computeArray(recipesScores, arr);
  73.  
  74.  
  75. while (true)
  76. {
  77. // Calculating the sum, adding the sum to the end of the string and checking if a matching was found
  78. sum = (scores[firstElf] - '0') + (scores[secondElf] - '0');
  79. scores += std::to_string(sum);
  80.  
  81. if (sum > 9)
  82. {
  83. if (KMP(recipesScores, index, arr, 1) == true)
  84. {
  85. // We added 2 digits to the string and a match was found after the first digit so we delete the remaining digit
  86. scores.erase(scores.end() - 1);
  87. break;
  88. }
  89. }
  90.  
  91. if (KMP(recipesScores, index, arr, sum % 10) == true)
  92. {
  93. break;
  94. }
  95.  
  96. // Calculating the new positions for the first elf and second elf
  97. firstElf = (firstElf + (scores[firstElf] - '0') + 1) % scores.length();
  98. secondElf = (secondElf + (scores[secondElf] - '0') + 1) % scores.length();
  99. }
  100. }
  101.  
  102.  
  103. int main()
  104. {
  105. std::fstream in("input.in", std::fstream::in);
  106. std::fstream out("output.out", std::fstream::out);
  107.  
  108. std::string scores("37");
  109. std::string recipesScores;
  110. in >> recipesScores;
  111.  
  112. findRecipeScores(scores, recipesScores);
  113.  
  114. out << scores.length() - recipesScores.length();
  115.  
  116. in.close();
  117. out.close();
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement