import io.StdIn.readLine


object Main {

  case class Order(str: String) {
    val order: Map[Char, Int] = str.zip(1 to 26).toMap
    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 compare(s1: String, s2: String, o: Order): Int = {
    var res = 0
    for (i <- 0 to (Math.min(s1.length, s2.length) - 1)) {
      o.compare(s1(i), s2(i)) match {
        case  1 => if (res == 0) res =  1
        case -1 => if (res == 0) res = -1
        case  _ => res = res
      }
    }
    if (res == 0) s1.length compare s2.length
    else res
  }

  def main(args: Array[String]): Unit = {
    val n = readLine().toInt
    val ss = for (i <- 1 to n) yield (readLine())
    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 = ss.sortWith((s1, s2) => compare(s1, s2, o) < 0).zip(1 to n).toMap
      println(s(ss(k - 1)))
    }
  }

}
