Codeforces Round #695 (Div. 2) B. Hills And Valleys

题意: 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值