Meet people
Practice
4.4 (11 votes)
Graphs
Algorithms
Breadth First search
Tree
Problem
40% Success 676 Attempts 50 Points 2s Time Limit 256MB Memory 1024 KB Max Code

You are given a tree of \(N \) nodes and \(K\) people located on the tree. You are also given an array \(A\) of size \(K\) where \(A[i]  \) indicate the location of the \(i^{th}\) person.
Now, there is an emergency meeting so all \(K\) people want to meet as soon as possible at the same node. In one second, a person who is standing at the \(i^{th}\) node can go to any adjacent node of the \(i^{th}\) node (the person cannot stand at the \(i^{th}\) node and he or she has to move).
You are required to print the minimum time to meet all \(K\) people at the same node. If it is impossible to meet all \(K\) people at one node, then print -1.

Input format

  • The first line contains \(T\) denoting the number of test cases.
  • The first line of each test case contains integers \(N \) and \(K\) denoting the total node of tree and total number of people.
  • Next \(N-1\) lines of each test case contain two integers \(x\) and \(y\) (\(1 \le x,\ y \le N\)). It means that there exists an edge connecting vertices \(x\) and \(y\). It is guaranteed that using these edges always forms a tree.
  • The next line of each test case contains \(K\) distinct integers \(A[1], A[2],\ ..., \ A[K]\) where \(A[i] \) is the location of the \(i^{th}\) person.

Output format

For each test case, print the minimum time to meet all \(K\) people at the same node. If it is impossible to meet all \(K\) people at one node, then print -1 in new line.

Constraints

\(1 \le T \le 10\)

\(1 \le N \le 10^5\)
\(1 \le K \le N\)

\(1 \le A[i] \le N\)

 

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...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:50
8 votes
Tags:
GraphsAlgorithmsBreadth-first searchC++
Points:50
35 votes
Tags:
MediumShortest Path Algorithm
Points:50
33 votes
Tags:
Breadth First SearchGraphsMedium