class Node
  attr_accessor :child, :parent
  def initialize
    @child = []
  end
end

def dfs(root, g)
  stack = [root]
  path = []
  done = {}
  while stack.size > 0
    s = stack[-1]
    flag = true
    g[s].child.each{|t|
      next if done[t]
      stack << t
      done[t] = true
      flag = false
      break
    }
    if flag
      path[s] = stack.clone
      stack.pop
    end
  end
  return path
end

$checked = {}
n = gets.to_i
g = Array.new(n){Node.new}
n.times{|i|
  g[i].child = gets.split.map(&:to_i)
  g[i].child.shift
}

chked = Hash.new{|h,k| h[k] = {}}
path = dfs(0, g)
q = gets.to_i
q.times{
  u, v = gets.split.map(&:to_i)
  u, v = v, u if u > v
  unless chked[u][v]
    common = path[u] & path[v]
    chked[u][v] = common[-1]
  end
  puts chked[u][v]
}