今天学了 字符串hash。
感觉没有想象的那么难,学习了一下自然溢出是怎么被卡的,原来还和CRT有关系.
主要原理就是mod两个hash同余
自然溢出哈希本质是模264
,
Hash(s)=(∑si⋅Pk−i)mod264
利用unsigned long long 溢出自动取模 264。
Thue−Morse 构造
对模 264、基数为奇数 P,存在反例。
定义:
ti=popcount(i)mod2
即二进制中 1 的个数的奇偶性:
t=0,1,1,0,1,0,0,1,…
令字符串 A 取 ti=0 位置的字符,B 取 ti=1 位置的字符,可证:
H(A)≡H(B)(mod264)
但 A=B,这就是构造性碰撞,与基数 P 无关(只要 P 是奇数)。
现在我一般用1e9+7 ,1e9+9作为mod,用131071,8191为幂次应该不会被卡。
Code
C++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;
}
}
或
C++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};
}//可能被卡
Ps:
s个a1,a2,....ashash值为:Hs
…
t个ak,ak+1,....ak+t−1hash值为:Ht
拼接后: Hashs+t =Hs ∗ baset+Ht
另:
t-s+1个as,as+1,....at
hashs−t:hasht−(hashs−1)∗p[t−s+1]
p[i]=basei