-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3331-find-subtree-sizes-after-changes.cpp
More file actions
37 lines (36 loc) · 1.03 KB
/
3331-find-subtree-sizes-after-changes.cpp
File metadata and controls
37 lines (36 loc) · 1.03 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
class Solution {
public:
vector<int> findSubtreeSizes(vector<int>& parent, string s) {
int n = parent.size();
vector<vector<int>> g(n);
vector<vector<int>> last(26);
for (int i = 1; i < n; i++) {
g[parent[i]].push_back(i);
}
vector<int> ans(n, 0);
vector<vector<int>> ng(n);
auto dfs = [&](auto &dfs, int u) -> void {
last[s[u] - 'a'].push_back(u);
for (auto &v: g[u]) {
int p = s[v] - 'a';
if (last[p].empty()) {
ng[u].push_back(v);
} else {
ng[last[p].back()].push_back(v);
}
dfs(dfs, v);
}
last[s[u] - 'a'].pop_back();
};
dfs(dfs, 0);
auto dfs2 = [&](auto &dfs2, int u) -> void {
ans[u] = 1;
for (auto &v: ng[u]) {
dfs2(dfs2, v);
ans[u] += ans[v];
}
};
dfs2(dfs2, 0);
return ans;
}
};