#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector <int> a(n); for(int i = 0; i < n; i++) cin >> a[i]; vector <vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(2))); dp[0][0][0] = 0; dp[0][1][0] = 1; dp[0][0][1] = 0; dp[0][1][1] = 1; for(int i = 1; i < n; i++){ for(int k = 0; k < 2; k++){ dp[i][1][k] = min(dp[i-1][0][k], dp[i-1][1][k]) + 1; if(((k+i)%2 == 0 && a[i] > a[i-1]) || ((k+i)%2 == 1 && a[i] < a[i-1])) dp[i][0][k] = min(dp[i-1][0][k], dp[i-1][1][k]); else dp[i][0][k] = dp[i-1][1][k]; } } cout << min({dp[n-1][0][0], dp[n-1][1][0], dp[n-1][0][1], dp[n-1][1][1]}) << "\n"; 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 | #include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; vector <int> a(n); for(int i = 0; i < n; i++) cin >> a[i]; vector <vector<vector<int>>> dp(n, vector<vector<int>>(2, vector<int>(2))); dp[0][0][0] = 0; dp[0][1][0] = 1; dp[0][0][1] = 0; dp[0][1][1] = 1; for(int i = 1; i < n; i++){ for(int k = 0; k < 2; k++){ dp[i][1][k] = min(dp[i-1][0][k], dp[i-1][1][k]) + 1; if(((k+i)%2 == 0 && a[i] > a[i-1]) || ((k+i)%2 == 1 && a[i] < a[i-1])) dp[i][0][k] = min(dp[i-1][0][k], dp[i-1][1][k]); else dp[i][0][k] = dp[i-1][1][k]; } } cout << min({dp[n-1][0][0], dp[n-1][1][0], dp[n-1][0][1], dp[n-1][1][1]}) << "\n"; return 0; } |