#P6031. Innumerable Ancestors
Innumerable Ancestors
Problem Description
There is a tree having $n$ nodes, labeled from 1 to $n$. The root of the tree is always 1, and the depth of a node $p$ is the number of nodes on the shortest path between node $p$ and the root.
In computer science, the Lowest Common Ancestor (LCA) of two nodes $v$ and $w$ in a tree is the lowest (i.e. deepest) node that has both $v$ and $w$ as descendants, where we define each node to be a descendant of itself (so if $v$ has a direct connection from $w$, $w$ is the lowest common ancestor).
You have to answer $m$ queries. Each query gives two non-empty node sets $A$ and $B$, there might be some nodes in both sets.
You should select one node $x$ from set $A$, and one node $y$ from set $B$, $x$ and $y$ can be the same node. Your goal is to maximize the depth of the LCA of $x$ and $y$.
Please write a program to answer these queries.
Input
The input contains several test cases, no more than 5 test cases.
In each test case, the first line contains two integers $n(1\leq n\leq 100000)$ and $m(1\leq m\leq 100000)$, denoting the number of nodes and queries.
For the next $n-1$ lines,each line contians two integers $a$ and $b$, denoting a bi-directional edge between node $a$ and $b$.
Then there are $2m$ lines, every two lines describes one query.
For each query, the first line describes the set A.
The first integer $k(1\leq k\leq n)$ denotes the number of nodes in set $A$, and the next $k$ integers describing the nodes in set $A$. There might be some nodes appear multiple times in the set.
The second line describes the set $B$ in the same format of set $A$.
It is guaranteed that $\sum k\leq 100000$ in each test case.
Output
For every query, print a number denoting the answer, which means the maximum depth of the LCA.
7 3
1 2
1 3
3 4
3 5
4 6
4 7
1 6
1 7
2 6 7
1 7
2 5 4
2 3 2
3
4
2