forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
61 lines (57 loc) · 1.68 KB
/
Solution.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
class Hashing {
private:
vector<long long> p;
vector<long long> h;
long long mod;
public:
Hashing(string word, long long base, int mod) {
int n = word.size();
p.resize(n + 1);
h.resize(n + 1);
p[0] = 1;
this->mod = mod;
for (int i = 1; i <= n; i++) {
p[i] = (p[i - 1] * base) % mod;
h[i] = (h[i - 1] * base + word[i - 1] - 'a') % mod;
}
}
long long query(int l, int r) {
return (h[r] - h[l - 1] * p[r - l + 1] % mod + mod) % mod;
}
};
class Solution {
public:
vector<bool> findAnswer(vector<int>& parent, string s) {
int n = s.size();
vector<int> g[n];
for (int i = 1; i < n; ++i) {
g[parent[i]].push_back(i);
}
string dfsStr;
vector<pair<int, int>> pos(n);
auto dfs = [&](this auto&& dfs, int i) -> void {
int l = dfsStr.size() + 1;
for (int j : g[i]) {
dfs(j);
}
dfsStr.push_back(s[i]);
int r = dfsStr.size();
pos[i] = {l, r};
};
dfs(0);
const int base = 13331;
const int mod = 998244353;
Hashing h1(dfsStr, base, mod);
reverse(dfsStr.begin(), dfsStr.end());
Hashing h2(dfsStr, base, mod);
vector<bool> ans(n);
for (int i = 0; i < n; ++i) {
auto [l, r] = pos[i];
int k = r - l + 1;
long long v1 = h1.query(l, l + k / 2 - 1);
long long v2 = h2.query(n - r + 1, n - r + 1 + k / 2 - 1);
ans[i] = v1 == v2;
}
return ans;
}
};