n = gets.to_i
$c = Array.new(n){ Array.new }
n.times do |i|
  a = gets.split.map(&:to_i)[1..-1]
  a.each{ |j| $c[i] << j }
end
$depth = Array.new(n)
$parent = Array.new(n)
$max = (Math.log(n) / Math.log(2)).ceil
$dp = Array.new(n){ Array.new($max) }

def dfs(a, pre, dep)
  $depth[a] = dep
  $parent[a] = pre
  $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
    dfs(i, a, dep+1)
  end
end

def lca(a, b)
  if $depth[a] > $depth[b] then a, b = b, a 
  end
  dh = $depth[b] - $depth[a]
  i = 0
  while (1 << i) <= dh
    if (dh>>i) % 2 == 1 then b = $dp[b][i]
    end
    i += 1
  end
  return a if a == b
  ret = -1
  ($max-1).downto(0) do |i|
    if $dp[a][i] == $dp[b][i] then ret = $dp[a][i]
    else
      a = $dp[a][i]
      b = $dp[b][i]
    end
  end
  return ret
end

dfs(0,-1,0)
q = gets.to_i
q.times do
  a, b = gets.split.map(&:to_i)
  p lca(a,b)
end