ELFHash

· · 个人记录

ELFHash是众多高效字符串哈希函数里的一种,

主要是利用了字符(char)以四位储存的特性,

结合位运算,保证最终哈希值能被所有字符影响,

并且得益于位运算,哈希值的大小相当随机,难以产生冲突

过程:

对字符串从前向后扫描

对于每个字符ch:

我们发现一直不停左移的话

最靠左边的四位左移后将被抛去,不会如我们希望的对结果产生影响

那么我们,

在下一步左移开始前,应当单独取出最左边的四位二进制数,

以这个四位二进制数来影响在它后面的不会被立即抛去的位置,

并且被影响的位置不应当在4的整数倍,

不然就等价于对加入时的单个字符做修改,(很可能)会增大冲突概率

对应过来就是:

int ELF(char *str){
    unsigned int has=0,x=0;
    while(*str){//只要指针指向地址所储存的字符不是空字符
        has=(has<<4)+(*str);
        if(x=(has&0xf0000000)){
            has^=(x>>24);
            has&=~x;        
        }
        str++;
    }
    return (int)has&0x7fffffff;
}

str:str作为一个指针,str表示解析str所在地址,其值为str所在地址的元素

而c风格字符串结尾会带有一个'/0'表示结束,其值为0,此时就会跳出循环

has&=~x:清空has尾四位

为什么是x>>24?:理论上来说可能只要大于等于4(不被抛去),小于等于28(不被右界抛去)就行了.

例题 Luogu P3370 [模板]字符串哈希

这题要是x>>28还有一个点过不了

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N=50000;
const int M=2000;
template<class T>inline void read(T &num){
    char ch;
    while(!isdigit(ch=getchar()));
    num=ch-'0';
    while(isdigit(ch=getchar()))num=num*10+ch-'0';
}

int exi[N];
int sum,n,has;
char str[M];

bool put_has(int pos){
    int ini=pos;
    pos%=N;
    while(exi[pos]!=-1&&exi[pos]!=ini){
        pos++;
        if(pos==N)pos=0;
    }
    if(exi[pos]==ini)return 1;
    else exi[pos]=ini;
    return 0;
}

int ELF(char *str){
    unsigned int has=0,x=0;
    while(*str){
        has=(has<<4)+(*str);
        if(x=(has&0xf0000000)){
            has^=(x>>24);
            has&=~x;        
        }
        str++;
    }
    return (int)has&0x7fffffff;
}

int main(){
    memset(exi,-1,sizeof(exi));
    read(n);
    sum=n;
    for(int i=1;i<=n;++i){
        scanf("%s",str);
        has=ELF(str);
        if(put_has(has))sum--;
    }
    printf("%d\n",sum);
    return 0;
}