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

<p>You are also given the array <code>queries</code> where <code>queries[i] = [node<sub>i</sub>, val<sub>i</sub>]</code>. For each query <code>i</code>, find the <strong>maximum genetic difference</strong> between <code>val<sub>i</sub></code> and <code>p<sub>i</sub></code>, where <code>p<sub>i</sub></code> is the genetic value of any node that is on the path between <code>node<sub>i</sub></code> and the root (including <code>node<sub>i</sub></code> and the root). More formally, you want to maximize <code>val<sub>i</sub> XOR p<sub>i</sub></code>.</p>

<p>Return <em>an array </em><code>ans</code><em> where </em><code>ans[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/29/c1.png" style="width: 118px; height: 163px;" />
<pre>
<strong>Input:</strong> parents = [-1,0,1,1], queries = [[0,2],[3,2],[2,5]]
<strong>Output:</strong> [2,3,7]
<strong>Explanation: </strong>The queries are processed as follows:
- [0,2]: The node with the maximum genetic difference is 0, with a difference of 2 XOR 0 = 2.
- [3,2]: The node with the maximum genetic difference is 1, with a difference of 2 XOR 1 = 3.
- [2,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
</pre>

<p><strong class="example">Example 2:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/06/29/c2.png" style="width: 256px; height: 221px;" />
<pre>
<strong>Input:</strong> parents = [3,7,-1,2,0,7,0,2], queries = [[4,6],[1,15],[0,5]]
<strong>Output:</strong> [6,14,7]
<strong>Explanation: </strong>The queries are processed as follows:
- [4,6]: The node with the maximum genetic difference is 0, with a difference of 6 XOR 0 = 6.
- [1,15]: The node with the maximum genetic difference is 1, with a difference of 15 XOR 1 = 14.
- [0,5]: The node with the maximum genetic difference is 2, with a difference of 5 XOR 2 = 7.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= parents.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= parents[i] &lt;= parents.length - 1</code> for every node <code>i</code> that is <strong>not</strong> the root.</li>
	<li><code>parents[root] == -1</code></li>
	<li><code>1 &lt;= queries.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>0 &lt;= node<sub>i</sub> &lt;= parents.length - 1</code></li>
	<li><code>0 &lt;= val<sub>i</sub> &lt;= 2 * 10<sup>5</sup></code></li>
</ul>

class Solution:
    def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:

        # overall idea:
        #   > to maximize xor on a bunch of numbers there's a well known algorithm:
        #      > build a bit trie with those numbers
        #      > then run DFS on that trie, greedily setting the highest remaining bit
        #      > greedy works because each bit b is more than the sum of remaining bits
        #           (in particular it's 1 + sum of remaining bits: 2**b = 2**(b-1) + ... + 2**0 + 1)
        #   > build trie: obviously we can *add* values x to a trie
        #   > insight: we can also REMOVE values x from a trie just as easily
        #   > insight 2: we don't have to answer the queries online, we can answer
        #                them in any order. We can answer queries in any order, e.g.
        #                the order in which we encounter the nodes
        #   > therefore we can do this:
        #      > explore the tree DFS
        #      > on entry, add each node x to the trie; the trie will have all values in the root to x path
        #      > answer all queries for x now that we have the requisite trie
        #      > descend to to x's children y
        #      > finally as we unwind the DFS stack, remove x from the trie b/c it's no longer on the path
        #
        # So we take the usual "build a bit trie" algorithm, and bolt on one change:
        #    > when we enounter a node in the tree, add to the trie
        #    > then on DFS exit we remove it from the trie
        #
        # so each node in the tree (not trie!) does O(bits) work to update the trie, once on entry and once on exit

        # find the max bit in the trie
        n = len(parents) # largest x value/"genetic info" is n-1
        max_val = max(q for _, q in queries)
        M = max(n-1, max_val)

        # FIXED: we must descend the trie for all bits in x and val
        #   > so there must be a trie level for all of them -> use the max
        #   > TODO: can just form the trie on 0..n-1 and use masking to handle the rest;
        #         we know very high `val` bits will only see 0's in corresp. x positions
        #         and thus we know the xor of those bits are the bits of val
        B = 1 << int(log2(M)+1) # 1 higher than max bit

        # define trie, esp. the add and remove code
        class Trie:
            def __init__(self):
                self.count = 0
                self.children = [None, None] # next bit unset, set

            def add(self, x, b) -> None:
                self.count += 1
                b >>= 1
                if b:
                    is_set = b&x > 0
                    if not self.children[is_set]: self.children[is_set] = Trie()
                    self.children[is_set].add(x, b)

            def remove(self, x, b) -> None:
                self.count -= 1
                b >>= 1
                if b:
                    is_set = 1 if b&x else 0
                    self.children[is_set].remove(x, b)
                    if self.children[is_set].count == 0: self.children[is_set] = None

            def maxXor(self, val, b) -> int:
                # assume b has already been handled by parent
                b >>= 1
                if b:
                    if val&b:
                        if self.children[0]:
                            # val doesn't have b set, there's a child that does: we get a contribution of b
                            return b + self.children[0].maxXor(val, b)
                        else:
                            # otherwise all children don't have it set, xor will have a zero here
                            return self.children[1].maxXor(val, b)
                    else:
                        # same idea, but b is set in val so we hope for a child without it set to get +b, else +0
                        if self.children[1]:
                            return b + self.children[1].maxXor(val, b)
                        else:
                            return self.children[0].maxXor(val, b)
                else:
                    return 0 # no more bits -> xor contribution of 0

        trie_root = Trie()

        adj = [[] for _ in range(n)]
        root = None
        for u, p in enumerate(parents):
            if p == -1:
                root = u
            else:
                adj[p].append(u)

        node_to_queries = [[] for _ in range(n)]
        for q, (x, _) in enumerate(queries):
            node_to_queries[x].append(q)

        ans = [0]*len(queries)

        def answerQueries(x: int) -> None:
            # x is on the root .. x path
            trie_root.add(x, B)

            for q in node_to_queries[x]:
                ans[q] = trie_root.maxXor(queries[q][1], B)

            for y in adj[x]:
                answerQueries(y)

            trie_root.remove(x, B)

        answerQueries(root)

        return ans
4470