forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
smallest-missing-genetic-value-in-each-subtree.cpp
43 lines (40 loc) · 1.22 KB
/
smallest-missing-genetic-value-in-each-subtree.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
// Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums) {
vector<int> result(size(parents), 1);
int i = distance(cbegin(nums), find(cbegin(nums), cend(nums), 1));
if (i == size(nums)) {
return result;
}
vector<vector<int>> adj(size(parents));
for (int j = 1; j < size(parents); ++j) {
adj[parents[j]].emplace_back(j);
}
unordered_set<int> lookup;
for (int miss = 1; i >= 0; i = parents[i]) {
iter_dfs(adj, nums, i, &lookup);
for (; lookup.count(miss); ++miss);
result[i] = miss;
}
return result;
}
private:
void iter_dfs(const vector<vector<int>>& adj,
const vector<int>& nums,
int i,
unordered_set<int> *lookup) {
vector<int> stk = {i};
while (!empty(stk)) {
i = stk.back(); stk.pop_back();
if (lookup->count(nums[i])) {
continue;
}
lookup->emplace(nums[i]);
for (const auto& j : adj[i]) {
stk.emplace_back(j);
}
}
}
};