fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int vertSize;
  7. int horSize;
  8. int firstNumber;
  9. int lastNumber;
  10. cin >> horSize >> vertSize >> firstNumber >> lastNumber;
  11. //создание динамического массива
  12. int*** arr;
  13. arr = new int**[vertSize];
  14. int count = 1;
  15. int z = 2;
  16. int apos[3];
  17. int bpos[3];
  18. for (int i = 0; i < vertSize; i++)
  19. {
  20. arr[i] = new int*[horSize];
  21. for (int j = 0; j < horSize; j++)
  22. {
  23. arr[i][j] = new int[z];
  24. for (int k = 0; k < 2; k++)
  25. {
  26. arr[i][j][k] = count;
  27. count++;
  28. // определяем позицию наших элементов в массиве
  29. if (arr[i][j][k] == firstNumber)
  30. {
  31. apos[0] = i;
  32. apos[1] = j;
  33. apos[2] = k;
  34. }
  35. if (arr[i][j][k] == lastNumber)
  36. {
  37. bpos[0] = i;
  38. bpos[1] = j;
  39. bpos[2] = k;
  40. }
  41. }
  42. }
  43. }
  44. int hor;
  45. int vert;
  46. // направление движения по вертикали
  47. vert = apos[0] < bpos[0] ? 1 : (apos[0] == bpos[0] ? 0 : -1);
  48. // направление движения по горизонтали
  49. hor = apos[1] < bpos[1] ? 1 : (apos[1] == bpos[1] ? 0 : -1);
  50. int stepCount = 0;
  51. int curCell[3];
  52. for (int i = 0; i < 3; i++)
  53. curCell[i] = apos[i];
  54.  
  55. bool dir;
  56. if (apos[1] < bpos[1] && firstNumber % 2 == 0 || apos[1] > bpos[1] && firstNumber % 2 != 0)
  57. dir = false;
  58. else
  59. dir = true;
  60. while (1)
  61. {
  62. if (dir && vert != 0)
  63. {
  64. if (vert == -1)
  65. {
  66. if (curCell[2] == 0)
  67. curCell[0]--;
  68. curCell[2] = !((bool)curCell[2]);
  69. stepCount++;
  70. }
  71. else
  72. {
  73. if (curCell[2] == 1)
  74. curCell[0]++;
  75. curCell[2] = !((bool)curCell[2]);
  76. stepCount++;
  77. }
  78. }
  79. else if (!dir && hor != 0)
  80. {
  81. if (hor == -1)
  82. {
  83. if (curCell[2] == 0)
  84. curCell[1]--;
  85. curCell[2] = !((bool)curCell[2]);
  86. stepCount++;
  87. }
  88. else
  89. {
  90. if (curCell[2] == 1)
  91. curCell[1]++;
  92. curCell[2] = !((bool)curCell[2]);
  93. stepCount++;
  94. }
  95. }
  96. dir = !dir;
  97.  
  98. if (curCell[0] == bpos[0])
  99. vert = 0;
  100. if (curCell[1] == bpos[1])
  101. hor = 0;
  102.  
  103. if (curCell[0] == bpos[0] && curCell[1] == bpos[1] && curCell[2] != bpos[2])
  104. {
  105. curCell[2] = !((bool)curCell[2]);
  106. stepCount++;
  107. }
  108.  
  109. bool end;
  110. for (int i = 0; i < 3; i++)
  111. {
  112. if (curCell[i] != bpos[i])
  113. {
  114. end = false;
  115. break;
  116. }
  117. end = true;
  118. }
  119. if (end)
  120. break;
  121. }
  122. cout << stepCount << endl;
  123. return 0;
  124. }
Success #stdin #stdout 0s 4316KB
stdin
3 2
6 12
stdout
2