codeforces 695 Div2, Hills And Valleys

题目链接https://codeforces.com/contest/1467/problem/B

思路:

其实在纸上模拟一下就知道,至少需要三个值才能形成凸起或凹陷的情况的,而这种情况的形成完全取决于第二个值,所以只需要将第二个值变为第一个值或第三个值(即a[i] = a[i -1], or a[i] = a[i + 1]),这种情况就会被缓解,我们只需要找到能缓解得最好的那种情况就行了。就遍历数组[1, n - 2]就行了(这里我数组下标是从0开始的)

以下是ac代码

#include <bits/stdc++.h>
using namespace std;

const int M = 3e5 + 10;
typedef long long ll;
int a[M];
int n;
int check(int i){
    int res = 0;
    if(i == 0 || i == n - 1) return 0;
    if(a[i] > a[i - 1] && a[i] > a[i + 1]) res ++;
    else if(a[i] < a[i - 1] && a[i] < a[i + 1]) res ++;
    return res;
}
int main (){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int t; cin >> t;
    while(t --){
        cin >> n;
        int res = 0, sam = 0;
        for(int i = 0; i < n; i ++) cin >> a[i];
        for(int i = 1; i < n - 1; i ++){
            if(a[i] > a[i - 1] && a[i] > a[i + 1]) res ++;
            else if(a[i] < a[i - 1] && a[i] < a[i + 1]) res ++;
        }
        int Max = 0;
        if(res <= 1) cout << 0 << "\n";
        else {
            for(int i = 1; i < n - 1; i ++){
                int pre = check(i - 1) + check(i) + check(i + 1);
                int temp = a[i];
                a[i] = a[i - 1];
                int now1 = check(i - 1) + check(i) + check(i + 1);
                a[i] = a[i + 1];
                int now2 = check(i - 1) + check(i) + check(i + 1);
                a[i] = temp;
                Max = max(Max, pre - min(now1, now2));
            }
            cout << max(res - Max, 0) << "\n";
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值