struct Hash {
using u64 = unsigned long long;
u64 base = 13331;
vector<u64> pow, hash;
Hash(string &s) {
s = " " + s;
int N = s.size();
pow.resize(N + 1), hash.resize(N + 1);
pow[0] = 1, hash[0] = 0;
for (int i = 1; i < s.size(); i ++) {
pow[i] = pow[i - 1] * base;
hash[i] = hash[i - 1] * base + s[i];
}
}
u64 get(int l, int r) {
return hash[r] - hash[l - 1] * pow[r - l + 1];
}
//拼接两个子串
u64 link(int l1, int r1, int l2, int r2) {
return get(l1, r1) * pow[r2 - l2 + 1] + get(l2, r2);
}
bool same(int l1, int r1, int l2, int r2) {
return get(l1, r1) == get(l2, r2);
}
};
struct DoubleHash {
const int n;
const i64 Base1 = 29, MOD1 = 1e9 + 7;
const i64 Base2 = 131, MOD2 = 1e9 + 9;
vector<i64> ha1, ha2, pow1, pow2;
vector<i64> rha1, rha2;
DoubleHash(string &s, int n1) : n(n1), ha1(n + 1), ha2(n + 1), pow1(n + 1), pow2(n + 1), rha1(n + 1), rha2(n + 1) {
pow1[0] = pow2[0] = 1;
for (int i = 1; i <= n; i++) {
pow1[i] = pow1[i - 1] * Base1 % MOD1;
pow2[i] = pow2[i - 1] * Base2 % MOD2;
}
for (int i = 1; i <= n; i++) {
ha1[i] = (ha1[i - 1] * Base1 + s[i]) % MOD1;
ha2[i] = (ha2[i - 1] * Base2 + s[i]) % MOD2;
rha1[i] = (rha1[i - 1] * Base1 + s[n - i + 1]) % MOD1;
rha2[i] = (rha2[i - 1] * Base2 + s[n - i + 1]) % MOD2;
}
}
pair<i64, i64> get(int l, int r) {
i64 res1 = ((ha1[r] - ha1[l - 1] * pow1[r - l + 1]) % MOD1 + MOD1) % MOD1;
i64 res2 = ((ha2[r] - ha2[l - 1] * pow2[r - l + 1]) % MOD2 + MOD2) % MOD2;
return {res1, res2};
}
//反哈希
pair<i64, i64> get_rhash(int l, int r) {
i64 res1 = ((rha1[n - l + 1] - rha1[n - r] * pow1[r - l + 1]) % MOD1 + MOD1) % MOD1;
i64 res2 = ((rha2[n - l + 1] - rha2[n - r] * pow2[r - l + 1]) % MOD2 + MOD2) % MOD2;
return {res1, res2};
}
//判断s[l, r]是否为回文串
bool is_palindrome(int l, int r) {
return get(l, r) == get_rhash(l, r);
}
pair<i64, i64> add(pair<i64, i64> aa, pair<i64, i64> bb) {
i64 res1 = (aa.first + bb.first) % MOD1;
i64 res2 = (aa.second + bb.second) % MOD2;
return {res1, res2};
}
//aa *= Base的k次方
pair<i64, i64> mul(pair<i64, i64> aa, i64 kk) {
i64 res1 = aa.first * pow1[kk] % MOD1;
i64 res2 = aa.second * pow2[kk] % MOD2;
return {res1, res2};
}
//拼接字符串 r1 < l2 s = s1 + s2
pair<i64, i64> link(int l1, int r1, int l2, int r2) {
return add(mul(get(l2, r2), r1 - l1 + 1), get(l1, r1));
}
};
标签:MOD1,MOD2,return,get,int,i64,哈希,字符串,模板
From: https://www.cnblogs.com/Kescholar/p/18324041