提前封装好双模数哈希,后续计算写起来会简便一些。
哈希初始化,底数预处理,取子串对齐后相减等操作保持不变。
struct Hash {//一个用结构体封装的hash双模数哈希
int x,y,MOD1 = 1000000007,MOD2 = 1000000009;
Hash(){}
Hash(int _x,int _y) { x = _x; y = _y; }
Hash operator + (const Hash &a) const {
return Hash((x + a.x) % MOD1,(y + a.y) % MOD2);
}
Hash operator - (const Hash &a) const {
return Hash((x - a.x + MOD1) % MOD1,(y - a.y + MOD2) % MOD2);
}
Hash operator * (const Hash &a) const {
return Hash(1ll * x * a.x % MOD1,1ll * y * a.y % MOD2);
}
ll val() {
return 1ll * x * MOD2 + y;
}
}base(131,13331),hs[N],bs[N];
int main() {
hs[0] = Hash(0,0);
bs[0] = Hash(1,1);
for(int i = 1;i <= n;i ++) {
hs[i] = hs[i-1] * base + s[i] - ‘a‘ + 1;
bs[i] = bs[i-1] * base;
}
return 0;
}
原文:https://www.cnblogs.com/forward77/p/15239879.html