[LeetCode] Maximum Genetic Difference Query

1938. Maximum Genetic Difference Query

There is a rooted tree consisting of n nodes numbered 0 to n - 1. Each node’s number denotes its unique genetic value (i.e. the genetic value of node x is x). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array parents, where parents[i] is the parent for node i. If node x is the root of the tree, then parents[x] == -1.

You are also given the array queries where queries[i] = [nodei, vali]. For each query i, find the maximum genetic difference between vali and pi, where pi is the genetic value of any node that is on the path between nodei and the root (including nodei and the root). More formally, you want to maximize vali XOR pi.

Return an array ans where ans[i] is the answer to the ith query.

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
struct Trie {
Trie* next[26];
int count = 0;
Trie() {memset(next, 0, sizeof next);}
void insert(int& n, int p = 18) {
count++;
if(p < 0) return;
else {
bool bit = n & (1<<p);
if(!next[bit]) next[bit] = new Trie();
next[bit]->insert(n, p - 1);
}
}
void remove(int& n, int p = 18) {
count--;
if(p < 0) return;
else {
bool bit = n & (1<<p);
next[bit]->remove(n, p - 1);
}
}
int query(int& n, int p = 18) {
if(p < 0) return 0;
else {
bool bit = n & (1<<p);
if(next[!bit] and next[!bit]->count) return (1<<p) + next[!bit]->query(n, p - 1);
return next[bit]->query(n, p - 1);
}
}
};
class Solution {
unordered_map<int, vector<int>> adj;
unordered_map<int, vector<pair<int, int>>> q;
vector<int> res;
void dfs(int& u, Trie* trie) {
trie->insert(u);
if(q.count(u)) {
for(auto& [id, n] : q[u]) {
res[id] = trie->query(n);
}
}

for(auto& v : adj[u]) {
dfs(v, trie);
}
trie->remove(u);
}
public:
vector<int> maxGeneticDifference(vector<int>& parents, vector<vector<int>>& queries) {
int n = parents.size(), root = -1, m = queries.size();
res = vector<int>(m);
for(int i = 0; i < n; i++) {
if(parents[i] == -1) root = i;
else adj[parents[i]].push_back(i);
}
for(int i = 0; i < m; i++) {
int u = queries[i][0], n = queries[i][1];
q[u].push_back({i, n});
}
dfs(root, new Trie());

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/03/PS/LeetCode/maximum-genetic-difference-query/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.