题目链接:http://poj.org/problem?id=3274
题意+思路: 点击这里
补充:因为有减法运算,所以可能会造成运算后结果为负数,所以需要把结果统一转换成正数[不然数组下标访问不到负数位置],还有要先把0放入哈希表,不然会出现长度为1但是没有匹配的情况
比如:1 3
7
结果为1,如果没把0放进哈希表则结果为0
#include<iostream> #include<algorithm> #include<cstring> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<time.h> using namespace std; typedef long long int LL; const int MAXN=100000+5; const int MAXK=30+5; const int MOD=999991; int Num[MAXN][MAXK]; //data storage struct Node{ int id,Next; }Cow[MAXN]; int n,k,S[MAXN][MAXK]; int Scnt,Head[MOD];//hash table void Init(){ //initialization memset(Head,-1,sizeof(Head)); memset(S,0,sizeof(S)); Scnt=0; } void AddNode(int HashN,int idx){ Cow[Scnt].id=idx; Cow[Scnt].Next=Head[HashN]; Head[HashN]=Scnt++; } bool cmp(int idx,int idy){ //compare two array for(int i=0;i<k;i++){ if(S[idx][i]!=S[idy][i]){ return false; } } return true; } int solve(){ int ans=0; for(int i=0;i<=n;i++){ //insert 0 into the hash table first! int HashNum=0; //i==0 then insert 0 into the hash table because Data from 1 to n for(int j=0;j<k;j++){ HashNum=((HashNum+S[i][j])+MOD)%MOD; } for(int j=Head[HashNum];j!=-1;j=Cow[j].Next){ if(cmp(i,j)){ ans=max(ans,i-j); } } AddNode(HashNum,i); } return ans; } void make_S(){//make array S for(int i=1;i<=n;i++){ for(int j=0;j<k;j++){ S[i][j]=S[i-1][j]+Num[i][j]; } } } void make_C(){ //make array C for(int j=k-1;j>=0;j--){ for(int i=1;i<=n;i++){ S[i][j]-=S[i][0]; } } } int main(){ #ifdef kirito freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif int start=clock(); while(~scanf("%d%d",&n,&k)){ Init(); for(int i=1;i<=n;i++){ int val; scanf("%d",&val); for(int j=0;j<k;j++,val/=2){ Num[i][j]=val%2; } } make_S(); make_C(); printf("%d ",solve()); } #ifdef LOCAL_TIME cout << "[Finished in " << clock() - start << " ms]" << endl; #endif return 0; }