import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

object Main extends App {
  val n = readInt
  val nodes = Array.fill(n){Nil: List[Int]}
  for (i ← 0 until n) {
    val _::t = readLine.trim.split(' ').map(_.toInt).toList
    nodes(i) = t
  }
  val parents = Array.fill(n){ArrayBuffer[Int]()}
  val height = Array.fill(n){0}
  val queue = mutable.Queue(0)
  while (queue.nonEmpty) {
    val current = queue.dequeue()
    for (next ← nodes(current)) {
      height(next) = height(current) + 1
      parents(next).append(current)
      while (parents(parents(next).last).length >= parents(next).length){
        parents(next).append(parents(parents(next).last)(parents(next).length - 1))
      }
      queue.enqueue(next)
    }
  }
  val q = readInt
  for (_ ← 0 until q) {
    val Array(u, v) = readLine.trim.split(' ').map(_.toInt)
    var ua = u
    var uv = v
    while (ua != uv) {
      if (height(ua) == height(uv)){
        var left = 0
        var right = parents(ua).length
        while (left < right) {
          val mid = (left + right) / 2
          if (parents(ua)(mid) != parents(uv)(mid)) left = mid + 1
          else right = mid
        }
        if (right != 0) right -= 1
        ua = parents(ua)(right)
        uv = parents(uv)(right)
      }else if (height(ua) < height(uv)) {
        var left = 0
        var right = parents(uv).length
        while (left < right) {
          val mid = (left + right) / 2
          if (height(parents(uv)(mid)) >= height(ua)) left = mid + 1
          else right = mid
        }
        uv = parents(uv)(right - 1)
      }else {
        var left = 0
        var right = parents(ua).length
        while (left < right) {
          val mid = (left + right) / 2
          if (height(parents(ua)(mid)) >= height(uv)) left = mid + 1
          else right = mid
        }
        ua = parents(ua)(right - 1)
      }
    }
    println(ua)
  }
}

