Advertisement
konopleva_karina

Untitled

Feb 28th, 2021
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. template <typename It, typename Cmp=std::less<typename std::iterator_traits<It>::value_type>>
  6. void InplaceMerge(It first_beg, It first_end, It second_beg, It second_end, Cmp cmp=Cmp()) {
  7. size_t first_part_size = std::distance(first_beg, first_end);
  8. size_t second_part_size = std::distance(second_beg, second_end);
  9.  
  10. if (!first_part_size || !second_part_size) {
  11. return;
  12. }
  13.  
  14. if (first_part_size == 1 && second_part_size == 1) {
  15. if (*first_beg > *second_beg) {
  16. std::swap(*first_beg, *second_beg);
  17. }
  18. return;
  19. }
  20.  
  21. It B1_beg = first_beg;
  22. It B1_end;
  23.  
  24. It B2_beg;
  25. It B3_beg = second_beg;
  26.  
  27. It B3_end;
  28.  
  29. It B4_beg;
  30. It B4_end = second_end;
  31.  
  32. if (first_part_size >= second_part_size) {
  33. B1_end = B1_beg + first_part_size / 2;
  34. B2_beg = B1_end;
  35. auto sep = std::lower_bound(second_beg, second_end, *B2_beg);
  36. B3_end = sep;
  37. B4_beg = sep;
  38. } else {
  39. B3_end = B3_beg + second_part_size / 2;
  40. B4_beg = B3_end;
  41. auto sep = std::upper_bound(first_beg, first_end, *B4_beg);
  42. B1_end = sep;
  43. B2_beg = sep;
  44. }
  45.  
  46. std::rotate(B2_beg, B3_beg, B3_end);
  47. auto B3_size = std::distance(B3_beg, B3_end);
  48. InplaceMerge(B1_beg, B1_end, B2_beg, B2_beg + B3_size);
  49. InplaceMerge(B2_beg + B3_size, B3_end, B4_beg, B4_end);
  50. }
  51.  
  52. int main() {
  53. std::vector<int> arr;
  54. size_t first_part_size = 0;
  55. std::cin >> first_part_size;
  56. arr.resize(first_part_size);
  57.  
  58. int elem;
  59. for(auto& i : arr) {
  60. std::cin >> elem;
  61. i = elem;
  62. }
  63.  
  64. size_t second_arr_size = 0;
  65. std::cin >> second_arr_size;
  66.  
  67. arr.resize(first_part_size + second_arr_size);
  68. for(auto it = arr.begin() + first_part_size; it != arr.end(); it = std::next(it)) {
  69. std::cin >> elem;
  70. *it = elem;
  71. }
  72.  
  73. InplaceMerge(arr.begin(), arr.begin() + first_part_size, arr.begin() + first_part_size, arr.end());
  74.  
  75. for(const auto& val : arr) {
  76. std::cout << val << ' ';
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement