Codeforces 602B Approximating a Constant Range 【dp + 二分】

本文介绍了一个算法问题,即在给定的数据序列中寻找最长的几乎恒定范围,该范围内的最大值与最小值之差不超过1。通过动态规划的方法解决此问题,并详细解释了状态转移过程及其实现。

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

B. Approximating a Constant Range
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

When Xellos was doing a practice course in university, he once had to measure the intensity of an effect that slowly approached equilibrium. A good way to determine the equilibrium intensity would be choosing a sufficiently large number of consecutive data points that seems as constant as possible and taking their average. Of course, with the usual sizes of data, it's nothing challenging — but why not make a similar programming contest problem while we're at it?

You're given a sequence of n data points a1, ..., an. There aren't any big jumps between consecutive data points — for each 1 ≤ i < n, it's guaranteed that |ai + 1 - ai| ≤ 1.

A range [l, r] of data points is said to be almost constant if the difference between the largest and the smallest value in that range is at most 1. Formally, let M be the maximum and m the minimum value of ai for l ≤ i ≤ r; the range [l, r] is almost constant if M - m ≤ 1.

Find the length of the longest almost constant range.

Input

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of data points.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000).

Output

Print a single number — the maximum length of an almost constant range of the given sequence.

Sample test(s)
input
5
1 2 3 3 2
output
4
input
11
5 4 5 5 6 7 8 8 8 7 6
output
5
Note

In the first sample, the longest almost constant range is [2, 5]; its length (the number of data points in it) is 4.

In the second sample, there are three almost constant ranges of length 4[1, 4][6, 9] and [7, 10]; the only almost constant range of the maximum length 5 is [6, 10].



花了快1个小时,o(╯□╰)o 好弱。。。

定义T序列:为一段连续的序列且序列中的最大元素-最小元素<=1。

题意:给定一个由n个元素组成的序列a[],保证相邻元素之间差的绝对值不超过1。问你最长的T序列。


思路:定义dp[i]为以a[i]结尾的最长T序列。用一个结构体存储以下信息

le——序列长度,mx——序列最大元素,mi——序列最小元素。

考虑a[i]的状态,根据a[i] 与 dp[i-1].mi 和 dp[i-1].mx的关系,得到状态转移方程

一、放入元素a[i]依旧是T序列,限制条件dp[i-1].mi <= a[i] <= dp[i-1].mx || dp[i-1].mi == dp[i-1].mx   

    dp[i].le = dp[i-1].le + 1;

    dp[i].mi = min(a[i], dp[i-1].mi);
    dp[i].mx = max(a[i], dp[i-1].mx);

二、放入元素a[i]不再是T序列

    设v1 = min(a[i], a[j]) - 1 和 v2 = max(a[i], a[j]) + 1 即与a[i]矛盾的数(差的绝对值大于1)

    我们的目的是找到离a[i]最近的v1的位置p1和离a[i]最近的v2的位置p2。

    这样就会有

    dp[i].le = i - max(p1, p2);

    dp[i].mi = min(dp[i].mi, a[j]);
    dp[i].mx = max(dp[i].mx, a[j]);

    关键在于快速求出p1和p2。我的想法是先用num结构体记录元素val以及id值,排序后。在num.val里面找到最小     的k使得a[k] = v1,这样num[k + (中间v1元素的个数) - 1].id就是p1,同理求出p2。

    至于求元素个数,用map就好了,边做dp边累加。 这样时间复杂度为O(nlogn)。  


AC代码:


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <vector>
#define INF 0x3f3f3f
#define eps 1e-8
#define MAXN (1000000+10)
#define MAXM (100000)
#define Ri(a) scanf("%d", &a)
#define Rl(a) scanf("%lld", &a)
#define Rf(a) scanf("%lf", &a)
#define Rs(a) scanf("%s", a)
#define Pi(a) printf("%d\n", (a))
#define Pf(a) printf("%.2lf\n", (a))
#define Pl(a) printf("%lld\n", (a))
#define Ps(a) printf("%s\n", (a))
#define W(a) while(a--)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define MOD 1000000007
#define LL long long
#define lson o<<1, l, mid
#define rson o<<1|1, mid+1, r
#define ll o<<1
#define rr o<<1|1
using namespace std;
int a[MAXN], cnt[MAXN];
struct Node{
    int mx, mi, le;
} ;
Node dp[MAXN];
struct Rec{
    int val, id;
};
Rec num[MAXN];
bool cmp(Rec a, Rec b)
{
    if(a.val != b.val)
        return a.val < b.val;
    else
        return a.id < b.id;
}
int Find(int l, int r, int v)
{
    int ans;
    while(r >= l)
    {
        int mid = (l + r) >> 1;
        if(num[mid].val >= v)
        {
            ans = mid;
            r = mid-1;
        }
        else if(num[mid].val < v)
            l = mid+1;
    }
    return ans;
}
map<int, int> fp;
int main()
{
    int n; Ri(n);
    for(int i = 1; i <= n; i++)
    {
        Ri(a[i]);
        num[i].val = a[i];
        num[i].id = i;
    }
    sort(num+1, num+n+1, cmp);
    int ans = 1;
    dp[1].le = 1; dp[1].mx = dp[1].mi = a[1];
    fp.clear(); fp[a[1]]++;
    for(int i = 2; i <= n; i++)
    {
        dp[i].mx = dp[i].mi = a[i];
        fp[a[i]]++;
        int j = i - 1;
        if(dp[j].mi <= a[i] && a[i] <= dp[j].mx || dp[j].mx == dp[j].mi)
        {
            dp[i].le = dp[j].le + 1;
            dp[i].mi = min(dp[i].mi, dp[j].mi);
            dp[i].mx = max(dp[i].mx, dp[j].mx);
        }
        else
        {
            int v1 = min(a[i], a[j]) - 1;
            int v2 = max(a[i], a[j]) + 1;
            int p1, p2;
            if(!fp[v1])
                p1 = 0;
            else
                p1 = Find(1, n, v1) + fp[v1] - 1;
            if(!fp[v2])
                p2 = 0;
            else
                p2 = Find(1, n, v2) + fp[v2] - 1;
            dp[i].le = i - max(num[p1].id, num[p2].id);
            dp[i].mi = min(dp[i].mi, a[j]);
            dp[i].mx = max(dp[i].mx, a[j]);
        }
        ans = max(ans, dp[i].le);
    }
    Pi(ans);
    return 0;
}


当前提供的引用内容并未提及关于Codeforces比赛M1的具体时间安排[^1]。然而,通常情况下,Codeforces的比赛时间会在其官方网站上提前公布,并提供基于不同时区的转换工具以便参赛者了解具体开赛时刻。 对于Codeforces上的赛事而言,如果一场名为M1的比赛被计划举行,则它的原始时间一般按照UTC(协调世界时)设定。为了得知该场比赛在UTC+8时区的确切开始时间,可以遵循以下逻辑: - 前往Codeforces官网并定位至对应比赛页面。 - 查看比赛所标注的标准UTC起始时间。 - 将此标准时间加上8小时来获取对应的北京时间(即UTC+8)。 由于目前缺乏具体的官方公告链接或者确切日期作为依据,无法直接给出Codeforces M1比赛于UTC+8下的实际发生时段。建议定期访问Codeforces平台查看最新动态更新以及确认最终版程表信息。 ```python from datetime import timedelta, datetime def convert_utc_to_bj(utc_time_str): utc_format = "%Y-%m-%dT%H:%M:%SZ" bj_offset = timedelta(hours=8) try: # 解析UTC时间为datetime对象 utc_datetime = datetime.strptime(utc_time_str, utc_format) # 转换为北京时区时间 beijing_time = utc_datetime + bj_offset return beijing_time.strftime("%Y-%m-%d %H:%M:%S") except ValueError as e: return f"错误:{e}" # 示例输入假设某场Codeforces比赛定于特定UTC时间 example_utc_start = "2024-12-05T17:35:00Z" converted_time = convert_utc_to_bj(example_utc_start) print(f"Codeforces比赛在北京时间下将是:{converted_time}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值