-
Notifications
You must be signed in to change notification settings - Fork 3
/
rolling_hash.cpp
65 lines (50 loc) · 1.48 KB
/
rolling_hash.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
typedef long long int ll;
struct RollingHash {
vector<ll> pwr, hsh;
ll A, M;
int n;
RollingHash(vector<int> s, ll _A = 31, ll _M = 1e9 + 7) {
n = s.size();
pwr.resize(n + 1);
hsh.resize(n + 1);
A = _A, M = _M;
pwr[0] = 1;
for (int i = 1; i <= n; i++) pwr[i] = pwr[i - 1] * A % M;
hsh[0] = s[0] % M + 1;
for (int i = 1; i < n; i++) {
hsh[i] = (hsh[i - 1] * A % M) + s[i] + 1;
if (hsh[i] >= M) hsh[i] -= M;
}
}
ll getHash(int x, int y) {
assert(x >= 0 and x < n and y >= 0 and y <= n);
return (hsh[y] + M - ((x - 1 >= 0) ? hsh[x - 1] * pwr[y - x + 1] % M : 0)) % M;
}
};
struct RollingHash {
vector<ll> pwr, hsh;
ll A, M;
int n;
RollingHash(string s, ll _A = 257, ll _M = 1e9 + 7) {
n = s.size();
pwr.resize(n + 1);
hsh.resize(n + 1);
A = _A, M = _M;
pwr[0] = 1;
for (int i = 1; i <= n; i++) pwr[i] = pwr[i - 1] * A % M;
hsh[0] = s[0] % M + 1;
for (int i = 1; i < n; i++) {
hsh[i] = (hsh[i - 1] * A % M) + s[i] + 1;
if (hsh[i] >= M) hsh[i] -= M;
}
}
ll getHash(int x, int y) {
assert(x >= 0 and x < n and y >= 0 and y <= n);
return (hsh[y] + M - ((x - 1 >= 0) ? hsh[x - 1] * pwr[y - x + 1] % M : 0)) % M;
}
};
struct PalindromeChecker {
RollingHash hash;
RollingHash revHash;
PalindromeChecker(String S)
};