Problem:
LCA: Lowest Common Ancestor

For a rooted tree, find the lowest common ancestor of two nodes u and v.

The given tree consists of n nodes and every node has a unique ID from 0 to n-1 where 0 is the root.

Input

n
k0 c1 c2 ... ck0
k1 c1 c2 ... ck1
:
kn-1 c1 c2 ... ckn-1
q
u1 v1
u2 v2
:
uq vq

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of node i is given. ki is the number of children of node i, and c1, ... cki are node IDs of 1st, ... kth child of node i.

In the next line, the number of queryies q is given. In the next q lines, pairs of u and v are given as the queries.

Output

For each query, print the LCA of u and v in a line.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

Sample Input 1

8
3 1 2 3
2 4 5
0
0
0
2 6 7
0
0
4
4 6
4 7
4 3
5 2

Sample Output 1

1
1
0
0

Solution in Ruby (judge verdict: Accepted)

n = gets.to_i
tree = Hash[(0..n-1).map {|i| [i, {}] }]
parent = Hash[(0..n-1).map {|i| [i, nil] }]
n.times do |i|
  k, *neighbours = gets.split.map(&:to_i)
  neighbours.each do |j|
    tree[i][j] = 0
    parent[j] = i
  end
end

subtree_size = Hash[(0..n-1).map {|i| [i, 1] }]
out_degree = (0..n-1).map {|i| tree[i].size }
queue = (0..n-1).select {|i| out_degree[i] == 0 }
paths = []
until queue.empty?
  i = queue.shift
  tree[i].each_key do |j|
    subtree_size[i] += subtree_size[j]
  end
  j = parent[i]
  if j
    out_degree[j] -= 1
    queue << j if out_degree[j] == 0
  end
end

# Heavy-Light Decomposition
queue = [0]
position = {}
ord = 0
until queue.empty?
  i = queue.shift
  path = [i]
  loop do
    heavy = true
    tree[i].each_key.sort_by {|j| -subtree_size[j]}.each do |j|
      if heavy
        path << j
        i = j
        heavy = false
      else
        queue << j
      end
    end
    break if heavy
  end
  path.unshift parent[path[0]] if parent[path[0]]
  (1..path.size - 1).each do |i|
    position[path[i]] = [path, i, ord]
  end
  paths << path
  ord += 1
end

position[0] = [paths[0], 0, 0]

q = gets.to_i
q.times do
  u, v = gets.split.map(&:to_i)
  path1, i, o1  = position[u]
  path2, j, o2  = position[v]
  until o1 == o2
    if o1 > o2
      path1, i, o1  = position[u = path1[0]]
    else
      path2, j, o2  = position[v = path2[0]]
    end
  end
  puts i < j ? path1[i] : path1[j]
end