

For the test case:
N = 3, Q = 2
Edge 1 connects 0 and 1
Edge 2 connects 0 and 2
battles = [1, 2]
The king has to visit first city 1 and then city 2. To visit city 1, he has to travel 1 unit, and now he is in city 1. To visit city 2 from city 1, he has to travel another 2 units. So overall, he has to travel 3 units of distance.
The first line will contain a single integer ‘T’ denoting the number of test cases. Then ‘T’ test cases follow.
The first line of each test case will contain two space-separated integers, ‘N’ and ‘Q’, denoting the total number of cities and the number of cities the king has to visit, respectively.
The next ‘N - 1’ line of each test case will contain two space-separated integers U[i] and V[i] denoting the two cities each road connects.
The next line of each test case will contain ‘Q’ space-separated integers denoting the cities where the king has to visit.
For each test case, print a single integer denoting the total length of the road the king has to travel to restore peace in all the cities.
You are not required to print anything; it has already been taken care of. Just implement the function.
1 <= T <= 10
1 <= Q <= N <= 10^5
0 <= U[i], V[i] <= N - 1
It is guaranteed that the sum of ‘N’ and sum of ‘Q’ over all test cases doesn’t exceed 10^5.
Time Limit: 1 sec.
We will iterate over the battle cities in the given order and calculate the distance between the current position of the king and his next position each time separately.
To calculate the distance between two cities, we will use the breadth-first search algorithm.
Algorithm:
We will use Lowest Common Ancestor(LCA) to find the distance between two cities in logarithmic time. After knowing the LCA of the two cities we can easily calculate the distance between them. Now to calculate the LCA we have to precalculate two arrays - “level” and “LCA” array. “Level” array will store the “level” of each node from the 0th node(root node), and the “LCA” array will store the ancestors of each node in the power of 2. For example, for each node “LCA” will store the 2^0th, 2^1th, 2^2th ancestors, and so on till it exists.
The distance between two nodes A and B will be “level[A]” + “level[B]” - 2 * “level[LCA of A and B]”.
For more information about LCA, follow the given link below:
https://cp-algorithms.com/graph/lca_binary_lifting.html
Algorithm: