codeforces 602B

本文讨论了一个算法问题,即在一组数字中找到最长的连续序列,其中最大数与最小数的差不超过1。通过压缩连续相同的数字,算法可以有效解决这个问题。

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

题意:有n个数字,找出最长的一段连续的序列,要求这个序列的最大数和最小数相差不能大于1

分析:一段序列,可能有的会重复,那么就压缩一下,把连续的相同的数字压缩为一个,并记录数字个数,这样在从头走一遍就好了。

/*

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
*/

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
#define maxn 100002
#define INF 0x3f3f3f3f
const int mod=1e9+7;
struct point{
    int x,y;
}a[maxn];
int main()
{
    int n,t,num=1,cnt=0,x;
    scanf("%d",&n);
    scanf("%d",&x);
    for(int i=1;i<n-1;i++){
        scanf("%d",&t);
        if(t==x){
            num++;
        }
        else{
            a[cnt].y=num;
            num=1;
            a[cnt++].x=x;
            x=t;
        }
    }
    scanf("%d",&t);
    if(x==t)a[cnt].y=num+1,a[cnt++].x=x;
    else{
        a[cnt].x=x,a[cnt++].y=num;
        a[cnt].x=t,a[cnt++].y=1;
    }
   // cout<<a[0].x<<a[0].y<<endl;
  //  cout<<a[1].x<<a[1].y<<endl;
    int ans=a[0].y,sum=a[0].y;
    if(cnt==2){
        if(a[0].x==a[1].x||a[0].x==a[1].x+1||a[0].x==a[1].x-1){
            ans=a[0].y+a[1].y;
        }
        else{
            ans=max(a[0].y,a[1].y);
        }
    }
    else if(cnt>2)sum=a[0].y+a[1].y;
    for(int i=2;i<cnt;i++){
        if(a[i].x!=a[i-2].x&&a[i].x!=a[i-1].x){
            ans=max(ans,sum);
            if(a[i].x==a[i-1].x+1||a[i].x==a[i-1].x-1){
                sum=a[i-1].y+a[i].y;
            }
            else{
                sum=a[i].y;
            }
        }
        else{
            sum+=a[i].y;
        }
    }
    ans=max(ans,sum);
    printf("%d\n",ans);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值