jzoj3464-秀姿势【hash】

正题

给出n个数,删去k种数,使一种数连续的最长。


解题思路

用hash表储存每种数在 left l e f t i i 这个区间内没种数的个数,然后如果这个区间内的种数超过k+1个那么就移动 left l e f t 指针并没次从hash中弹出一个数知道满足条件,最后统计一下答案就好了。


代码

#include
#include
#include
#define hashmath(x) x%p
using namespace std;
const int p=600001;
int n,k,a[100001],hash[p],v[p],s,left,x,need,maxs;
int locate(int x)
{
    int w=hashmath(x),i=0;
    while (hash[(w+i)%p]!=0&&hash[(w+i)%p]!=x&&ireturn (w+i)%p; 
}
int main()
{
    scanf("%d%d",&n,&k);k++;
    for (int i=1;i<=n;i++)
      scanf("%d",&a[i]);
    for (int i=1;i<=n;i++)
    {
        int w=locate(a[i]);
        if (!v[w]) x++;//是一个新种
        v[w]++;hash[w]=a[i];//正常操作
        while(x>k)
        {
            int wz=locate(a[left]);
            v[wz]--;
            if (!v[wz]){
                x--;//这种数已经没了
                hash[wz]=0;
            } 
            left++;
        }
        maxs=max(maxs,v[w]);//统计答案
    }
    printf("%d",maxs);
}

你可能感兴趣的:(数据结构)