poj 3274 Gold Balanced Lineup

http://poj.org/problem?id=3274

不得不说自己的哈希水平很烂 此题完全抄了别人的代码,看来以后要看看哈希呀

先贴代码日后消化

#include<iostream>
#include<string>
#include<string.h>
#include<queue>
#include<math.h>
#include<stdio.h>
#include<map>

using namespace std;
const int N=100010;
const int prime=99983;
int n,k;
int hash[1000000];
int a[N][31],c[N][31],sum[N][31];
inline int hashcode(int *a)
{
    int p=0;
    for(int i=0;i<k;++i)
    {
        p=((p<<2)+((a[i]>>4))^(a[i]<<10));
    }
    p=p%prime;
    if(p<0)
    p=p+prime;
    return p;
}
int main()
{
    scanf("%d %d",&n,&k);
    memset(hash,-1,sizeof(hash));
    memset(c,0,sizeof(c));
    memset(sum,0,sizeof(sum));
    hash[hashcode(c[0])]=0;
    int ans,i,j,itemp;
    ans=0;
    for(i=1;i<=n;++i)
    {
        scanf("%d",&itemp);
        for(j=0;j<k;++j)
        {
            a[i][j]=itemp%2;
            itemp=itemp>>1;
            sum[i][j]=sum[i-1][j]+a[i][j];
            c[i][j]=sum[i][j]-sum[i][0];
        }
        int p=hashcode(c[i]);
        while(hash[p]!=-1)
        {
            for(j=1;j<k;++j)
            {
                if(c[i][j]!=c[hash[p]][j])
                break;
            }
            if(j==k)
            {
                if(i-hash[p]>ans)
                ans=i-hash[p];
                break;
            }
            ++p;
        }
        if(hash[p]==-1)
        hash[p]=i;
    }
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(poj)