
The first line contains 'T', denoting the number of test cases.
For each Test :
The first line contains two space separated integers 'N' and ‘Q’, denoting the number of cities and the number of queries respectively.
The next N-1 lines contain a pair of cities ‘X’ and ‘Y’, indicating that there is a road between ‘X’ and ‘Y’.
The next line contains an array ‘P’ of ‘N’ integers, representing the type of Pokemon found in each city.
The next ‘Q’ lines contain a pair of cities ‘U’ and ‘V’, indicating each query.
Print Q lines, i.e, for each query print the number of Pokemon Ash catches in that travel.
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= 'T' <= 10
2 <= 'N' <= 10^4
1 <= ‘Q’ <= 10^5
1 <= X,Y,U,V <= N
1<= A[i] <= 10^9, i ∈ (1,N)
Note - The sum of 'N' over all test cases does not exceed 10^4 and the sum of ‘Q’ does not exceed 10^5.
Time Limit: 1 sec
To efficiently be able to find the path between any two cities, say ‘A’ and ‘B’, we need to find their Lowest Common Ancestor (LCA). We can compute the LCA in multiple ways, including binary lifting and segment trees.
Once the LCA is computed, we can divide the journey into two paths, namely A to LCA and LCA to B (Corner case is when A or B itself is the LCA). We can traverse both these paths while using a set or a hashmap to keep track of the number of unique values.
Algorithm:
Splits the array into blocks of size √N and sorts the queries according to which block the start point lies in. If both start points belong in the same block, it sorts them according to their endpoints.
We can flatten the tree into an array using DFS such that each query becomes a query on a range in the array instead of a path on the tree.
We can now maintain a frequency array or a map to count the occurrences of each value in our range.
Algorithm: