-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path3249.cpp
More file actions
55 lines (45 loc) · 1.43 KB
/
Copy path3249.cpp
File metadata and controls
55 lines (45 loc) · 1.43 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
class Solution {
public:
int countGoodNodes(const vector<vector<int>> &edges) const {
static int count[100001];
const int n = size(edges) + 1;
vector<vector<int>> adj(n);
stack<pair<int, int>> st;
int res = 0;
for (const auto &edge : edges) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
st.emplace(0, -1);
memset(count, 0x00, sizeof(count));
while (!st.empty()) {
if (st.top().first != -1) {
const auto [root, parent] = st.top();
st.emplace(-1, -1);
for (const int next : adj[root]) {
if (next == parent) continue;
st.emplace(next, root);
}
continue;
}
st.pop();
const auto [root, parent] = st.top();
st.pop();
int cnt = 1;
int goal = -1;
bool good = true;
for (int i = 0; i < size(adj[root]); i++) {
const int next = adj[root][i];
if (next == parent) continue;
if (goal == -1)
goal = count[next];
else if (count[next] != goal)
good = false;
cnt += count[next];
}
if (good) res++;
count[root] = cnt;
}
return res;
}
};