[CodeForces 602B]Approximating a Constant Range[构造]

博客探讨了一种数列问题,其中数列元素的绝对差不超过1。目标是找到一个区间,使区间内最大值与最小值之差不超过1,同时最大化区间长度。解题策略涉及记录每个数字出现的最大位置,并根据这些位置确定可能的区间。代码实现展示了具体的解决方案。

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

题目链接: [CodeForces 602B]Approximating a Constant Range[构造]

题意分析:

给出一个数列,各项绝对值之差不超过1,求最大的区间长度,使得区间内最大的数减去最小的数差不超过1。

解题思路:

用p[i]记录数字i出现的最大位置,那么到达数字x时,我们只需要对x-1和x+1的最大位置进行判断,就能确定如何计算区间长度。下面仅讨论其中一种情况:

假设p[x-1]>p[x+1],那么此时组成区间的数应该为x和x-1,这时的区间长度为i - max(p[x + 1], p[x - 2])。这里max里面出现x-2是因为,有可能在x+1之后出现x-2的情况,但是绝不可能出现x+2因为从x+2到x-1必然会经历x+1此时的p[x+1]就被更新了,和原来的定义不符合。

个人感受:

机智啊机智,学习学习Orz

具体代码如下:

#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define lowbit(x) (x & (-x))
#define root 1, n, 1
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1  1
#define ll long long
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;

const int INF = 0x7f7f7f7f;
const int MAXN = 1e5 + 111;

int p[MAXN];

int main()
{
    int n, x, ans = 0;
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &x);
        if (p[x - 1] > p[x + 1]) ans = max(ans, i - max(p[x - 2], p[x + 1]));
        else ans = max(ans, i - max(p[x - 1], p[x + 2]));
        p[x] = i;
    }
    printf("%d\n", ans);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值