#模拟赛1# B - Hills And Valleys

该博客讨论了一种算法问题,涉及如何通过改变一个数字来最小化一串数字中山峰(值大于左右两侧)和山谷(值小于左右两侧)的数量。作者提供了思路,即遍历序列并尝试将每个数字替换为左侧或右侧的数字,计算新的山峰和山谷数量,最终找到最优解。代码实现使用C++,包括判断山峰和山谷的辅助函数以及解决方案的主体部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

https://codeforces.com/problemset/problem/1467/B

在这里插入图片描述
就是一列高高低低的数字,改变其中的一个数字,使得这一列中山峰+山谷的数目最小

思路

其实就是先找到原来的总数目,然后从1—n-1位一个数字一个数字的改变,①变成左边的数字,求出这时数目的最小的,②变成右边的数字,求出这时候数目最小的,不断往后遍历求出,得到最后的结果
感觉虽然能大致想出来,但是具体的代码实现还是要加强

代码

//平平无奇复制粘贴。。

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

const int N = 3e5;
int a[N], n;

int isValley(int i) {
    return (i > 0 && i < n - 1 && a[i] < a[i - 1] && a[i] < a[i + 1]);
}

int isHill(int i) {
    return (i > 0 && i < n - 1 && a[i] > a[i - 1] && a[i] > a[i + 1]);
}

int solveTestCase() {
    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> a[i];

    int is[n] = {};
    int s = 0;
   
    for (int i = 1; i < n - 1; i++) {
        if (isHill(i) || isValley(i))
            is[i] = 1, s++;
    }

    int ans = s;
    for (int i = 1; i < n - 1; i++) {
        int temp = a[i];
        a[i] = a[i - 1];
        ans = min(ans, s - is[i - 1] - is[i] - is[i + 1] + isHill(i - 1) + isValley(i - 1) + isHill(i) + isValley(i) + isHill(i + 1) + isValley(i + 1));
        a[i] = a[i + 1];
        ans = min(ans, s - is[i - 1] - is[i] - is[i + 1] + isHill(i - 1) + isValley(i - 1) + isHill(i) + isValley(i) + isHill(i + 1) + isValley(i + 1));
        a[i] = temp;
    }

    cout << ans << "\n";
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    int t = 1;
    cin >> t;
    while (t--)
        solveTestCase();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值