-
Notifications
You must be signed in to change notification settings - Fork 55
/
check_palindrome_in_logn_time.cpp
120 lines (103 loc) · 2.05 KB
/
check_palindrome_in_logn_time.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#include <bits/stdc++.h>
typedef long long int ll;
#define M 1000000007
using namespace std;
ll prefix_hash[100005];
ll prefix_hashr[100005];
ll power(ll base, ll n, ll m)
{
ll ans = 1;
while (n != 0)
{
if (n % 2 == 1)
{
n = n - 1;
ans = (ans * base) % m;
}
else
{
n = n / 2;
base = (base * base) % m;
}
}
return ans;
}
ll compute_substring_hash(ll l, ll r)
{
ll hash = prefix_hash[r];
if (l > 0)
{
hash = (hash - prefix_hash[l - 1] + M) % M;
}
// divide
hash = (hash * power(power(31, l, M), M - 2, M)) % M;
return hash;
}
ll compute_substring_hash1(ll l, ll r)
{
ll hash = prefix_hashr[r];
if (l > 0)
{
hash = (hash - prefix_hashr[l - 1] + M) % M;
}
// divide
hash = (hash * power(power(31, l, M), M - 2, M)) % M;
return hash;
}
void compute(string &s)
{
ll pr = 1;
ll hash = 0;
for (ll i = 0; i < s.size(); i++)
{
hash = (hash + ((s[i] - 'a' + 1) * pr) % M) % M;
prefix_hash[i] = hash;
pr = (pr * 31) % M;
}
}
void computeR(string &s)
{
string temp = s;
reverse(temp.begin(), temp.end());
ll pr = 1;
ll hash = 0;
for (ll i = 0; i < temp.size(); i++)
{
hash = (hash + ((temp[i] - 'a' + 1) * pr) % M) % M;
prefix_hashr[i] = hash;
pr = (pr * 31) % M;
}
}
bool checkPalindrome(ll l, ll r, ll n)
{
ll a = compute_substring_hash(l, r);
ll b = compute_substring_hash1(n - 1 - r, n - 1 - l);
return (a == b);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
string s;
cin >> s;
compute(s);
computeR(s);
ll q;
cin >> q;
ll n = s.size();
// Each query can be answered in logn time complexity
while (q--)
{
ll l, r;
cin >> l >> r;
if (checkPalindrome(l, r, n))
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}