-
Notifications
You must be signed in to change notification settings - Fork 111
/
smallest-missing-genetic-value-in-each-subtree.cc
74 lines (68 loc) · 1.75 KB
/
smallest-missing-genetic-value-in-each-subtree.cc
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
// Smallest Missing Genetic Value in Each Subtree
#define FOR(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)
class Solution {
vector<vector<int>> es;
vector<int> pre, post;
int tick = 0;
void dfs(int u) {
pre[u] = tick++;
for (int v : es[u])
dfs(v);
post[u] = tick;
}
public:
vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums) {
int n = parents.size();
es.resize(n);
REP(i, n)
if (~parents[i])
es[parents[i]].push_back(i);
pre.resize(n);
post.resize(n);
dfs(0);
vector<int> pos(100002, -1), ans(n, 1);
REP(i, n)
pos[nums[i]] = i;
int u = pos[1], v = 2;
for (; ~u; u = parents[u]) {
for (; ~pos[v] && pre[u] <= pre[pos[v]] && post[pos[v]] <= post[u]; v++);
ans[u] = v;
}
return ans;
}
};
/// Euler-tour technique
#define FOR(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (a); i < (b); i++)
#define REP(i, n) FOR(i, 0, n)
class Solution {
vector<vector<int>> es;
vector<int> pre, post;
int tick = 0;
void dfs(int u) {
pre[u] = tick++;
for (int v : es[u])
dfs(v);
post[u] = tick;
}
public:
vector<int> smallestMissingValueSubtree(vector<int>& parents, vector<int>& nums) {
int n = parents.size();
es.resize(n);
REP(i, n)
if (~parents[i])
es[parents[i]].push_back(i);
pre.resize(n);
post.resize(n);
dfs(0);
vector<int> pos(100002, -1), ans(n, 1);
REP(i, n)
pos[nums[i]] = i;
int u = pos[1], v = 2;
for (; ~u; u = parents[u]) {
for (; ~pos[v] && pre[u] <= pre[pos[v]] && post[pos[v]] <= post[u]; v++);
ans[u] = v;
}
return ans;
}
};