挺值得一做的数据结构题。
个人总感觉能用map做,但是一直wa,所以来用hash了。
不得不说,虽然大家对hash都很熟,但是hash还真挺难写= =(是我蒟蒻了么= =)
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <cmath>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <deque>
#include <algorithm>
using namespace std;
int n,k,ans;
int a[32],b[100010][32],t,h;
int vis[1000010];
int hash(int c[])
{
int ret=0;
for (int i=1;i<k;i++)
ret=(ret<<2+(c[i]>>4)^(c[i]<<10))%1000007;
if (ret<0) ret+=1000007;
return ret;
}
int f(int c[],int d)
{
h=hash(c);
while (vis[h]!=-1)
{
int i;
for (i=1;i<k;i++)
if (c[i]!=b[vis[h]][i]) break;
if (i==k) return vis[h];
h=(h+1)%1000007;
}
vis[h]=d;
return -1;
}
int main()
{
while (scanf("%d%d",&n,&k)==2)
{
ans=0;
memset(vis,-1,sizeof(vis));
memset(a,0,sizeof(a));
memset(b[0],0,sizeof(b[0]));
h=hash(b[0]); vis[h]=0;
for (int i=1;i<=n;i++)
{
scanf("%d",&t);
for (int j=0;j<k;j++) a[j]+=(t>>j)&1;
for (int j=1;j<k;j++) b[i][j]=a[j]-a[0];
t=f(b[i],i);
if (t>=0 && i-t>ans) ans=i-t;
}
printf("%d\n",ans);
}
return 0;
}