inlineintmul(int x, int y){ return1ll * x * y % p; } inlineintadd(int x, int y){ return (x += y) >= p ? x - p : x; }
voidinit(char *s, int _base, int _p){ int l = strlen(s + 1); p = _p; base = _base; pow[0] = 1; for (int i = 1; i <= l; ++i) pow[i] = mul(pow[i - 1], base); for (int i = 1; i <= l; ++i) h[i] = add(s[i], mul(h[i - 1], base)); } intget(int l, int r){ return add(h[r], p - mul(h[l - 1], pow[r - l + 1])); } inthash(char *s){ int l = strlen(s + 1); int ans = 0; for (int i = 1; i <= l; ++i) ans = add(s[i], mul(ans, base)); return ans; } } h1, h2;
最快但也是最容易挂的做法,模数直接取 $2^32$
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
structHash { constint base = 131; uint pow[maxn], h[maxn];
voidinit(char *s){ int l = strlen(s + 1); pow[0] = 1; for (int i = 1; i <= l; ++i) pow[i] = pow[i - 1] * base; for (int i = 1; i <= l; ++i) h[i] = s[i] + h[i - 1] * base; } uint get(int l, int r){ return h[r] - h[l - 1] * pow[r - l + 1]; } uint hash(char *s){ int l = strlen(s + 1); uint ans = 0; for (int i = 1; i <= l; ++i) ans = s[i] + ans * base; return ans; } } h;