Advertisement
Weezle

Untitled

Jul 11th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. /**
  5. * Циклически сдвиньте элементы массива вправо на заданное количество позиций s.
  6. * (A[0] переходит на место A[s-1], A[1] на место A[s], ..., последний элемент переходит на место A[s-2]).
  7. * Используйте минимально возможное количество операций присваивания. Не используйте дополнительный массив
  8. * @param arr
  9. * @param length
  10. * @param shift
  11. * @return
  12. */
  13. void shift_array(int* arr, const int length, const int shift)
  14. {
  15. int lastindex = 0;
  16. int indexsolve = 0;
  17. int a = 0;
  18. int b = 0;
  19. int countofoper = length;
  20. while (countofoper>1)
  21. {
  22. b = indexsolve - shift % length > 0 ? indexsolve - shift % length : (indexsolve - shift % length + length) ;
  23. b %= length;
  24. a = arr[b];
  25. arr[b] = arr[lastindex];
  26. arr[lastindex] = a;
  27. countofoper--;
  28. if (b == lastindex)
  29. {
  30. lastindex++;
  31. indexsolve = lastindex;
  32. }
  33. else
  34. {
  35. indexsolve = b;
  36. }
  37. }
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43. int length, shift;
  44. int* array;
  45.  
  46. std::ifstream file("input.txt");
  47. file >> length >> shift;
  48.  
  49. array = new int[length];
  50. for (int i = 0; i < length; ++i)
  51. file >> array[i];
  52.  
  53. shift_array(array, length, shift);
  54. file.close();
  55.  
  56. std::ofstream output("output.txt");
  57. for (int i = 0; i < length; ++i)
  58. output << array[i] << ' ';
  59. output.close();
  60. delete[] array;
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement