[ 10.08 ]CF每日一题系列—— 602B

Description:
  一个数组,保证相邻两个元素值得差小于1,问题,最大值和最小值的差 < 1的区间长度最长是多少ios

Solution:
  仍是卡了一下,原本觉得是模拟就行了,可是卡时间,想来想去最后仍是忽略了一个地方,就是它的保证,相邻元素值得差小于1,就保证了这个序列得变化是以1或0为单位相邻变化的,因此不可能出现5 4 6,因此咱们考虑一个数字x的时候只要去找出现的位置就好,咱们要找的可能区间有x 和 x + 1区间或者x 和 x - 1区间,因此咱们看一下上一个x - 1 出现的位置和x + 1 出现的位置在哪,由于他俩不能共存,若是x - 1出现的位置靠后,咱们要计算的就是 x和x-1区间的长度,要看 (x - 2)出现的位置和x + 1出现位置的最大值,为其限制,反之亦然,用一个dp数组维护就行了数组

#include <iostream>
#include <cstdio>
#include <cstring>
#define inf ( 1 << 28 )
using namespace std;
const int maxn = 1e5 + 1e3;
int x;
int dp[maxn];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        memset(dp,0,sizeof(dp));
        int ans = 0;
        for(int i = 1;i <= n;i++)
        {
            scanf("%d",&x);
            if(dp[x - 1] > dp[x + 1])ans = max(ans,i - max(dp[x + 1],dp[x - 2]));
            else ans = max(ans,i - max(dp[x+2],dp[x-1]));
            dp[x] = i;
        }
        printf("%d\n",ans);
    }
    return 0;
}
相关文章
相关标签/搜索