n = gets.to_i
$c = Array.new(n)
n.times{ |i| $c[i] = gets.split.map(&:to_i)[1..-1] }
$depth = Array.new(n)
$max = (Math.log(n) / Math.log(2)).ceil
$dp = Array.new(n){ Array.new($max) }
 
def bfs
  arr = []
  arr << [0,-1,0]
  until arr.empty?
    a,pre,dep = arr.shift
    $depth[a] = dep
    $dp[a][0] = pre
    (1...$max).each do |i|
      if $dp[a][i-1] != -1 then $dp[a][i] = $dp[$dp[a][i-1]][i-1]
      else $dp[a][i] = -1
      end
    end
    $c[a].each do |i|
      next if i == pre
      arr << [i, a, dep+1]
    end
  end
end
 
def lca(a, b)
  a, b = b, a if $depth[a] > $depth[b]
  dh = $depth[b] - $depth[a]
  i = 0
  while (1<<i) <= dh
    b = $dp[b][i] if dh&(1<<i) == 1
    i += 1
  end
  return a if a == b
  ($max-1).downto(0) do |i|
    if $dp[a][i] != $dp[b][i]
      a = $dp[a][i]; b = $dp[b][i] 
    end
  end
  $dp[a][0]
end
 
bfs
gets.to_i.times do
  a, b = gets.split.map(&:to_i)
  p lca a, b
end