题意: t组数据,每组输入一个长度为n的序列,如果a[i]<a[i+1]>a[i+2],则称之为山峰,如果a[i]>a[i+1]<a[i+2],则称之为山谷。
我们可以修改数组中的一个数据,求数组中最少的山谷和山峰之和。
思路: 在输入时可以将山峰和山谷的位置标记起来,在修改数据的时候在标记点修改是最优的,可以将a[i]改为a[i-1]和a[i+1]。
如果a[i-1]和a[i+1]都为标记点,则判断两边哪一边的贡献更大。
如果只有单边,则要注意,因为可能会出现修改后有新的山峰/山谷出现
以上是我总结出来的四种修改会产生新的山峰/山谷的情况。(画的丑,供参考)
如果a[i-1]和a[i+1]都不是标记点,则只需要处理a[i]
完整代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<map>
#include<queue>
#include<vector>
#include<stack>
#define ll long long
using namespace std;
const int inf = 1e9 + 7;
int a[300005];
int vis[300005];
int main()
{
int t;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
int ans = 0;
for (int i = 1; i <= n; i++) {
vis[i] = 0;
scanf("%d", &a[i]);
if (i >= 3) {
if (a[i] > a[i - 1] && a[i - 1] < a[i - 2]) {
vis[i - 1] = 1;
ans++;
}
else if (a[i]<a[i - 1] && a[i - 1]>a[i - 2]) {
vis[i - 1] = 1;
ans++;
}
}
}
int cnt = 0;
int maxn = 0;
for (int i = 2; i < n; i++) {
if (vis[i]) {
cnt = 1;
if (vis[i + 1]) {
cnt = 2;
if (vis[i - 1]) {
if (a[i] > a[i + 1] && a[i - 1] <= a[i + 1])cnt++;
else if (a[i] < a[i + 1] && a[i - 1] >= a[i + 1])cnt++;
}
else if ((i-2>0)&&((a[i + 1] > a[i - 1] && a[i - 1] < a[i - 2]) || (a[i + 1]<a[i - 1] && a[i - 1]>a[i - 2])))cnt--;
}
maxn = max(maxn, cnt);
if (vis[i - 1]) {
cnt = 2;
if (vis[i + 1]) {
if (a[i] > a[i - 1] && a[i + 1] <= a[i - 1])cnt++;
else if (a[i] < a[i - 1] && a[i + 1] >= a[i - 1])cnt++;
}
else if ((i+2<=n)&&((a[i - 1] < a[i + 1] && a[i + 2] < a[i + 1]) || (a[i - 1] > a[i + 1] && a[i + 2] > a[i + 1])))cnt--;
}
maxn = max(maxn, cnt);
}
}
printf("%d\n", ans - maxn);
}
return 0;
}