forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-nodes-with-value-one.cpp
82 lines (76 loc) · 2.1 KB
/
number-of-nodes-with-value-one.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
// Time: O(q + n)
// Space: O(n)
// bfs
class Solution {
public:
int numberOfNodes(int n, vector<int>& queries) {
vector<int> cnt(n);
const auto& bfs = [&]() {
int result = 0;
vector<pair<int, int>> q = {{1, 0}};
while (!empty(q)) {
vector<pair<int, int>> new_q;
for (auto [u, curr] : q) {
curr ^= cnt[u - 1] % 2;
result += curr;
for (int v = 2 * u; v <= min(2 * u + 1, n); ++v) {
new_q.emplace_back(v, curr);
}
}
q = move(new_q);
}
return result;
};
for (const auto& q : queries) {
++cnt[q - 1];
}
return bfs();
}
};
// Time: O(q + n)
// Space: O(q + h)
// iterative dfs
class Solution2 {
public:
int numberOfNodes(int n, vector<int>& queries) {
vector<int> cnt(n);
const auto& iter_dfs = [&]() {
int result = 0;
vector<pair<int, int>> stk = {{1, 0}};
while (!empty(stk)) {
auto [u, curr] = stk.back(); stk.pop_back();
curr ^= cnt[u - 1] % 2;
result += curr;
for (int v = 2 * u; v <= min(2 * u + 1, n); ++v) {
stk.emplace_back(v, curr);
}
}
return result;
};
for (const auto& q : queries) {
++cnt[q - 1];
}
return iter_dfs();
}
};
// Time: O(q + n)
// Space: O(q + h)
// dfs
class Solution3 {
public:
int numberOfNodes(int n, vector<int>& queries) {
vector<int> cnt(n);
const function<int(int, int)> dfs = [&](int u, int curr) {
curr ^= cnt[u - 1] % 2;
int result = curr;
for (int v = 2 * u; v <= min(2 * u + 1, n); ++v) {
result += dfs(v, curr);
}
return result;
};
for (const auto& q : queries) {
++cnt[q - 1];
}
return dfs(1, 0);
}
};