<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 Tril:
    class Node:
        def __init__(self, par: "Node" = None):
            self.nexts = [None, None]
            self.par = par
            self.count = 0
            self.val = None
        
        def add_val(self, val: int) -> None:
            assert not self.val, f"{self.val}"
            self.val = val
            while self:
                self.count += 1
                self = self.par
        
        def remove_val(self) -> None:
            assert self.val is not None and self.count > 0
            if self.val == 82577:
                print("remove")
            self.val = None
            while self:
                self.count -= 1
                self = self.par
        
    def __init__(self, max_depth: int = 10):
        self.max_depth = max_depth
        self.root = self.Node()

    def get(self, val: int, force: bool = False) -> Optional[Node]:
        p = self.root
        i = self.max_depth
        while p and i >= 0:
            pos = bool(val & 1 << i)
            if not p.nexts[pos]:
                if force:
                    p.nexts[pos] = self.Node(par = p)
                else:
                    pos = 1 - pos
            elif not force and p.nexts[pos].count == 0:
                pos = 1 - pos
            
            p = p.nexts[pos]
            i -= 1
        
        return p

    def get_maximal(self, val: int) -> int:
        if val == 82577:
            print("max")
        p = self.get(~val, False)
        assert p
        return p.val

    def add_val(self, val: int) -> Node:
        p = self.get(val, True)
        p.add_val(val)
        return p
    
class Solution:
    def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]:
        graph = [[] for _ in parents]
        querylist = collections.defaultdict(list)
        answers = [0] * len(queries)
        rootNum = -1
        
        for i, p in enumerate(parents):
            if p < 0:
                rootNum = i
            else:
                graph[p].append(i)
        
        for i, p in enumerate(queries):
            querylist[p[0]].append(i)
        
        tril = Tril(16)
        def visit(node: int):
            p = tril.add_val(node)
            for q in querylist[node]:
                answers[q] = queries[q][1] ^ tril.get_maximal(queries[q][1])
            for n in graph[node]:
                visit(n)
            p.remove_val()
        
        visit(rootNum)
        return answers
                


4321