#include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } const int MAX = 1000001; int calc(vector<int> &elements, int direction) { int changes = 0; int index = 0; while (elements.size() - index >= 2) { int a = elements[index]; int b = elements[index + 1]; if (direction != sgn(b - a)) { elements[index + 1] = a + direction * MAX; changes++; } direction = -direction; index++; } return changes; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n; cin >> n; vector<int> elementsA(n); vector<int> elementsB(n); for (auto i = 0; i < n; i++) { int v; cin >> v; elementsA[i] = v; elementsB[i] = v; } int resultA = calc(elementsA, 1); int resultB = calc(elementsB, -1); cout << min(resultA, resultB) << endl; return 0; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> int sgn(T val) { return (T(0) < val) - (val < T(0)); } const int MAX = 1000001; int calc(vector<int> &elements, int direction) { int changes = 0; int index = 0; while (elements.size() - index >= 2) { int a = elements[index]; int b = elements[index + 1]; if (direction != sgn(b - a)) { elements[index + 1] = a + direction * MAX; changes++; } direction = -direction; index++; } return changes; } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n; cin >> n; vector<int> elementsA(n); vector<int> elementsB(n); for (auto i = 0; i < n; i++) { int v; cin >> v; elementsA[i] = v; elementsB[i] = v; } int resultA = calc(elementsA, 1); int resultB = calc(elementsB, -1); cout << min(resultA, resultB) << endl; return 0; } |