#Doubling lca
class Node
  attr_accessor :child, :depth, :parent
  def initialize
    @child = []
    @depth = 0
    @parent = []
  end
end

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

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
}

dfs(0, g)

k = 0
while k < Math.log2(n)
  v = 0
  while v < n
    if g[v].parent[k] < 0
      g[v].parent[k+1] = -1
    else
      g[v].parent[k+1] = g[g[v].parent[k]].parent[k]
    end
    v += 1
  end
  k += 1
end

q = gets.to_i
q.times{
  u, v = gets.split.map(&:to_i)
  u, v = v, u if g[u].depth > g[v].depth
  k = 0
  while k < Math.log2(n) + 1
    if (g[v].depth - g[u].depth) >> k & 1 == 1
      v = g[v].parent[k]
    end
    k += 1
  end
  if u == v
    puts u
    next
  end
  k = (Math.log2(n) - 1).to_i
  while k >= 0
    if g[u].parent[k] != g[v].parent[k]
      u = g[u].parent[k]
      v = g[v].parent[k]
    end
    k -= 1
  end
  puts g[u].parent[0]
}