-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1519.cpp
More file actions
39 lines (34 loc) · 1.07 KB
/
Copy path1519.cpp
File metadata and controls
39 lines (34 loc) · 1.07 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
class Solution {
public:
vector<int> countSubTrees(int n, vector<vector<int>> &edges, string labels) {
vector<vector<int>> adj(n, vector<int>()), count(n, vector<int>(26, 0));
vector<bool> visited(n, false);
vector<int> res(n);
for (auto &e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
stack<int> st;
st.push(0);
while (!st.empty()) {
int crnt = st.top();
if (visited[crnt]) {
st.pop();
for (int c : adj[crnt]) {
if (visited[c]) continue;
for (int i = 0; i < 26; i++)
count[crnt][i] += count[c][i];
}
res[crnt] = ++count[crnt][labels[crnt] - 'a'];
visited[crnt] = false;
continue;
}
visited[crnt] = true;
for (int c : adj[crnt]) {
if (visited[c]) continue;
st.push(c);
}
}
return res;
}
};