Hills And Valleys
http://codeforces.com/contest/1467/problem/B
题意
\(一个数列里有波峰波谷\)
- \(波谷:a[i]<min(a[i+1],a[i-1]])\)
- \(波峰:a[i]>max(a[i+1],a[i-1])\)
- \(sum = 波峰数+波谷数\)
\(若可以任意修改一个a[i]的值,问如何修改使得序列的sum值最小.\)
思路
\(如果去想修改的细节会很麻烦,所以要找到能够遍历解决的通法\\对于修改任意一个数a[i],其值只会影响到a[i-1]和a[i+1]是否为波峰波谷,\\所以每枚举一个i只用考虑其三元组的变化.\)
代码
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define fi first
#define se second
#define inf 0x3f3f3f3f
const int N = 3e5 + 7;
int a[N];
int n;
int cal(int i) {
if (i <= 1 || i >= n) return 0;
int res = 0;
if (a[i] < min(a[i + 1], a[i - 1])) ++res;
if (a[i] > max(a[i + 1], a[i - 1])) ++res;
return res;
}
int main() {
IO;
int _;
cin >> _;
while (_--) {
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
int sum = 0, ans = inf;
for (int i = 1; i <= n; ++i) sum += cal(i);
for (int i = 1; i <= n; ++i) {
int tmp = sum - cal(i) - cal(i - 1) - cal(i + 1);
int t = a[i];
a[i] = a[i - 1];
ans = min(ans, tmp + cal(i) + cal(i - 1) + cal(i + 1));
a[i] = a[i + 1];
ans = min(ans, tmp + cal(i) + cal(i - 1) + cal(i + 1));
a[i] = t;
}
cout << ans << '\n';
}
return 0;
}