Binary path queries

3.2

4 votes
Dynamic Programming, Modular arithmetic, Implementation, Trees, Data Structures, C++, Lowest Common Ancestor, Bit manipulation
Problem

You are given a tree consisting of  nodes. The () node of the tree has been assigned a binary value , that is . You are also given queries.

In each query, you are given 2 nodes and . Initialize an empty string. Now, consider the simple path between these 2 nodes(from to ) and append the binary values obtained on this path to the string. Your task is to find the decimal representation of this binary string. Note that the bit at corresponds to LSB.

Since the output can be very large, you need to calculate the decimal representation modulo

You are given test cases.

Warning: Use FAST I/O Methods. 

Input format

  • The first line contains a single integer denoting number of test cases.
  • For each test case:
    • The first line contains an integer denoting the number of nodes in tree.
    • Second line contains space separated integers denoting the values of the nodes.
    • Next lines follow. For each line:
      • Two space-separated integers and denoting the nodes of the tree. This means there is an edge between node and .
    • Next line contains denoting the number of queries.
    • lines follow. Each line contains 2 space separated integers and .

Output format

For each test case(in a separate line), output(in a separate line) space separated integers where the integer denotes the decimal representation of the binary string obtained on the simple path between the two vertices in the query. Don't forget to take modulo

Constraints

Sample Input
2
6
1 0 1 0 1 1
1 2
1 5
5 6
2 4
2 3
3
3 6
4 5
1 6
2
1 1
1 2
2
1 2
2 2
Sample Output
23 3 7
3 1
Time Limit: 4
Memory Limit: 256
Source Limit:
Explanation

In the first test case, we have . The tree is shown below:

                                                               

We now answer the queries:

  • First query: . The path is , the binary string is . The decimal representation is .
  • Second query: . The path is , the binary string is . The decimal representation is .
  • Third query: . The path is , the binary string is . The decimal representation is .
  • Note that we output answers in a single line.

 

In the second test case, we have . The tree is shown below:

                                                                        

We now answer the queries:

  • First query: . The path is , the binary string is . The decimal representation is .
  • Second query: . The path is , the binary string is . The decimal representation is .
  • Note that we output answers in a single line.
Editor Image

?