forked from jahid-hridoy/Code_Templates
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingle_Hash_Palindrome
More file actions
69 lines (55 loc) · 1.33 KB
/
Single_Hash_Palindrome
File metadata and controls
69 lines (55 loc) · 1.33 KB
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
66
67
68
69
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int MAX = 1e6 + 10;
const int MOD = 1e9 + 7;
const ll base = 31;
ll p[MAX], rev_p[MAX], hsh[MAX], rev_hsh[MAX];
ll InverseMod(ll a, ll b) {
ll res = 1;
while (b) {
if (b & 1) res = (res * a) % MOD;
a = a * a % MOD;
b >>= 1;
}
return res % MOD;
}
void pre() {
p[0] = 1;
rev_p[0] = 1;
ll rev_base = InverseMod(base, MOD - 2);
for (int i = 1; i < MAX; i++) {
p[i] = p[i - 1] * base % MOD;
rev_p[i] = rev_p[i - 1] * rev_base % MOD;
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
pre();
string s, ans;
cin >> s;
int n = s.size();
for (int i = 0; i < n; i++) {
hsh[i + 1] = (hsh[i] + ((s[i] - 'a' + 1) * p[i]) % MOD) % MOD;
}
for(int i = n-1, j = 0; i >= 0; i--, j++){
rev_hsh[j + 1] = (rev_hsh[j] + ((s[i]-'a' + 1) * p[j]) % MOD) % MOD;
}
int ans = 0;
for(int i = 1; i <= n; i++){
for(int j = 0; j < n; j++){
int L = j;
int R = j+i-1;
ll pre_hash = (hsh[R+1]-hsh[L]+MOD)%MOD;
pre_hash = (pre_hash * rev_p[L])%MOD;
ll suf_hash = (rev_hsh[n-L]-rev_hsh[n-R-1]+MOD)%MOD;
suf_hash = (suf_hash * rev_p[n-R-1])%MOD;
if(pre_hash == suf_hash){
ans++;
}
}
}
cout << ans << '\n';
return 0;
}