Subtree Center Solution Codechef -
SOLUTION
” CLICK HERE “
You are given a tree with nodes (numbered through ) and queries (numbered through ). For each valid , in the -th query, you are given nodes . Consider the smallest subtree which contains all of these nodes; you should find all centers of this subtree.
A node is called a center of a tree if it lies in the middle of at least one longest path in that tree. Note that there may be multiple longest paths (paths with the same maximum length) and for a longest path which contains an even number of nodes, there are two nodes lying in the middle of this path.
Input
- The first line of the input contains a single integer denoting the number of test cases. The description of test cases follows.
- The first line of each test case contains two space-separated integers and .
- lines follow. For each valid , the -th of these lines contains two space-separated integers and denoting that there is an edge between nodes and in the tree.
- more lines follow. For each valid , the -th of these lines contains an integer , followed by a space and space-separated integers .
Note: The input and output of this problem are large, so prefer using fast input/output methods.
Output
For each query, print a single line containing an integer denoting the number of centers, followed by a space and space-separated integers — the nodes which are centers of the given subtree, sorted in increasing order.
Constraints
- the graph described on the input is a tree
- for each valid
- for each query, are pairwise distinct
- the sum of over all test cases does not exceed
- the sum of over all queries in all test cases does not exceed
Example Input
2
3 2
1 2
2 3
2 1 3
2 1 2
5 2
1 2
2 3
2 4
3 5
1 2
2 4 5
Example Output
1 2
2 1 2
1 2
2 2 3
Explanation
Example case 1: The figure below describes the second query. The smallest subtree containing the given nodes is coloured red and the nodes which are its centers are coloured blue.

Example case 2: The figure below describes the second query with subtree and centers coloured in the same way.


Social Plugin