import io.StdIn.readLine


object Main {

  case class Order(str: String) {
    val order: Map[Char, Int] = str.zip(1 to 26).toMap ++ Map('0' -> 0)
    def compare(c1: Char, c2: Char): Int = order(c1) compare order(c2)
  }

  def toQuery(str: String): (Int, Order) = {
    val sub = str.split(' ')
    (sub(0).toInt, Order(sub(1)))
  }

  def sort(ss: Vector[String], offset: Int, o: Order): Vector[String] = {
    ss.groupBy(_(offset)).toVector.sortWith((p1, p2) => o.compare(p1._1, p2._1) < 0).flatMap(_ match {
      case (c, Vector(s)) => Vector(s)
      case (c, v) => sort(v, offset + 1, o)
    })
  }

  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    val sss = (for (i <- 1 to n) yield (readLine())).asInstanceOf[Vector[String]]
    val maxlen = sss.map(_.length).max
    val ss = sss.map(s => s + List.fill(maxlen - s.length)('0').mkString)
    val m = readLine().toInt
    val qq = for (i <- 1 to m) yield (toQuery(readLine()))

    for (i <- 1 to m) {
      val (k, o) = qq(i - 1)
      val s = sort(ss, 0, o).zip(1 to n).toMap
      println(s(ss(k - 1)))
    }
  }

}
