Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7891 | Accepted: 2321 |
Description
Farmer John's N cows (1 ≤ N ≤ 100,000) share many similarities. In fact, FJ has been able to narrow down the list of features shared by his cows to a list of only K different features (1 ≤ K ≤ 30). For example, cows exhibiting feature #1 might have spots, cows exhibiting feature #2 might prefer C to Pascal, and so on.
FJ has even devised a concise way to describe each cow in terms of its "feature ID", a single K-bit integer whose binary representation tells us the set of features exhibited by the cow. As an example, suppose a cow has feature ID = 13. Since 13 written in binary is 1101, this means our cow exhibits features 1, 3, and 4 (reading right to left), but not feature 2. More generally, we find a 1 in the 2^(i-1) place if a cow exhibits feature i.
Always the sensitive fellow, FJ lined up cows 1..N in a long row and noticed that certain ranges of cows are somewhat "balanced" in terms of the features the exhibit. A contiguous range of cows i..j is balanced if each of the K possible features is exhibited by the same number of cows in the range. FJ is curious as to the size of the largest balanced range of cows. See if you can determine it.
Input
Lines 2.. N+1: Line i+1 contains a single K-bit integer specifying the features present in cow i. The least-significant bit of this integer is 1 if the cow exhibits feature #1, and the most-significant bit is 1 if the cow exhibits feature # K.
Output
#include<stdio.h>
#include<string.h>
//#include<iostream>
#define max(i,j) (i > j?i:j)
#define maxn1 200000
#define maxn2 40
#define maxn3 1100000
#define PRIME1 113
#define PRIME2 999983
struct xx {
int data,next;
} lin[maxn3];
int key[maxn1][maxn2] = {0},a[maxn1] = {0},HA[PRIME2+1001] = {0},sum[maxn1][maxn2] = {0};
int ans = 0,k,n;
int judge(int a1[],int a2[],int l)
{
int i;
for(i = 1;i <= l;i++) if (a1[i] != a2[i]) return 0;
return 1;
}
int HASH(int ha[],int l)
{
int i,j,hash = 0;
for(i = 1;i <= l;i++)
hash = (hash*PRIME1 + ha[i])%PRIME2;
return hash+1;
}
void init()
{
int i,j;
scanf("%d%d",&n,&k);
for(i = 1;i <= n;i++)
scanf("%d",&a[i]);
for(i = 1;i <= n;i++)
for(j = 1;j <= k;j++)
sum[i][j] = sum[i-1][j] + ((a[i]>>(j-1))&1);
}
void work()
{
int i,j,t,temp,len = 1;
memset(lin,0,sizeof(lin));
for(i = 0;i <= n;i++){
for(j = 1;j <= k;j++)
key[i][j] = sum[i][j] - sum[i][1];
temp = HASH(key[i],k);
if (HA[temp] > 0) {
lin[len].next = HA[temp];
lin[len].data = i;
HA[temp] = len++;
}
else {
HA[temp] = len;
lin[len].data = i;
lin[len++].next = 0;
}
}
for(i = 0;i <= n;i++) {
temp = HASH(key[i],k);
t = HA[temp];
while ((lin[t].data > i) && (lin[t].data)) {
if (judge(key[i],key[lin[t].data],k))
ans = max(ans,lin[t].data-i);
t = lin[t].next;
}
}
printf("%d\n",ans);
return ;
}
int main()
{
init();
work();
return 0;
}