字符串 hash

· · 个人记录

今天学了 字符串hash。 感觉没有想象的那么难,学习了一下自然溢出是怎么被卡的,原来还和CRT有关系.

主要原理就是mod两个hash同余 自然溢出哈希本质是模2^{64} ,

Hash(s)=(\sum s_i \cdot P^{k-i})\bmod 2^{64}

利用 unsigned long long 溢出自动取模 2^{64}。

:::info[ Thue-Morse 构造]

对模 2^{64}、基数为奇数 P,存在反例。 定义:

t_i=\text{popcount}(i)\bmod 2

即二进制中 1 的个数的奇偶性:

t = 0,1,1,0,1,0,0,1,\dots

令字符串 A 取 t_i=0 位置的字符,B 取 t_i=1 位置的字符,可证:

H(A) \equiv H(B) \pmod{2^{64}}
但 A \ne B,这就是构造性碰撞,与基数 P 无关(只要 P 是奇数)。

现在我一般用\color{white}{1e9+7} ,\color{white}{1e9+9}作为mod,用\color{white}{131071},\color{white}{8191}为幂次应该不会被卡。

:::info[Code]

const ull M1=1000000007;
const ull M2=1000000009;
const ull P1=131071;
const ull P2=8191;
const int N=3e3+3;
ull h1[N],h2[N];
ull p1[N],p2[N];
void init(string x){
    p1[0]=p2[0]=1;
    for(int i=1;i<(int)x.size();i++){
        h1[i]=(h1[i-1]*P1+x[i])%M1;
        h2[i]=(h2[i-1]*P2+x[i])%M2;
        p1[i]=p1[i-1]*P1%M1;
        p2[i]=p2[i-1]*P2%M2;
    }
}

或

pair<ull,ull> hsh(const string &x){
    ull h=0,hh=0;
    for(char c:x)h=h*M+(ull)(unsigned char)c,hh=hh*N+(ull)(unsigned char)c;
    return {h,hh};
}//可能被卡

:::

$$ \underbrace{\text{$a_1$,$a_2$,....$a_s$}}_{\text{s个}} hash值为:H_s $$ ... $$ \underbrace{\text{$a_k$,$a_{k+1}$,....$a_{k+t-1}$}}_{\text{t个}} hash值为:H_t $$ 拼接后: $Hash_{s+t}$ =$H_s$ $*$ $base^t$+$H_t

另:

\underbrace{\text{$a_s,a_{s+1},....a_{t}$}}_{\text{t-s+1个}} hash_{s-t}:hash_t-(hash_{s-1})*{p[t-s+1]} p[i]=base^i