Prefix queries
63% Success1382 Attempts50 Points5s Time Limit256MB Memory1024 KB Max Code

You are given an undirected tree with $$N$$ nodes rooted at node 1. Every node has a value $$A[i]$$ assigned to it. You are required to answer $$Q$$ queries of the following type:

  • $$V X$$: Find the longest length prefix that is common in the binary representation of $$V$$ and the binary representation of node value of any of the ancestors of node $$X$$ including node $$X$$ itself. Also, the binary representation should be of length $$62$$ and of the order from Most Significant Bit to Least Significant Bit.

Find the required answer for $$Q$$ queries.

Note:

  • Assume 1-based indexing.
  • A node $$u$$ is said to be an ancestor of node $$v$$, if node $$u$$ lies on a simple path between the root and node $$v$$.
  • The prefix of a binary representation is defined as a contiguous set of bits from the starting of the representation. 

Input format

  • The first line contains a single integer $$T$$ that denotes the number of test cases.
  • For each test case:
    • The first line contains an integer $$N$$.
    • The second line contains $$N$$ space-separated integers denoting array $$A$$.
    • Next $$N - 1$$ lines contain two space-separated integers $$u v$$ denoting an edge between node $$u$$ and $$v$$.
    • The next line contains an integer $$Q$$.
    • Next $$Q$$ lines contain two space-separated integers $$V X$$ denoting the query.

Output format

For each test case, print $$Q$$ space-separated integers denoting the longest length common prefix for $$Q$$ queries. Print the output for each test case in a new line.

Constraints

\(1 \le T \le 5\)
\(1 \le N, Q \le 10^5\)
\(1 \le A[i], V \le 10^9\)
\(1 \le X \le N\)

 

Examples
Input
1
5
6 2 1 5 3
1 2
2 3
2 4
1 5
2
4 2
6 5
Output
60 62
Explanation
  • For query 1V = 4, X  = 2
    • Nodes which are ancestors of node 2 are and 1.
    • Binary Representation of V is 00000000000000000000000000000000000000000000000000000000000100. If we consider binary representation of node value of node 1, i.e. A[1] = 6, it is 00000000000000000000000000000000000000000000000000000000000110. Both the binary representation have 60 length common prefix which is the longest we can achieve.
    • Hence, the answer is 60.
  • For query 2, V = 6, X  = 5
    • Nodes which are ancestors of node 5 are and 1.
    • Since, V is equal to node value of node i.e. 6. Thus, the binary representation of V and node value of 1 will be exactly same.
    • Hence, the answer is 62.
  • Thus, required answer is [60, 62].

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading Editor...
Results