import scala.annotation.tailrec
import scala.io.StdIn._
object Main extends App {
  loop()
  @tailrec def loop(count: Int = 1): Unit = {
    val n = readInt()
    if (n == 0) return
    val words = Array.tabulate(n){_ ⇒
      val Array(w, l) = readLine.trim.split(' ')
      (w, l.toInt)
    }
    val target = readLine.trim
    val memo = Array.fill(target.length){Int.MinValue}
    val length = maxLength(ParseTarget(target, 0), words)(memo)
    val shortestWord = Array.fill(length + 1){Int.MaxValue}
    shortestWord(0) = 0
    for ((w, l) ← words) {
      for (i ← 0 to length - l) {
        if (shortestWord(i) != Int.MaxValue && shortestWord(i) + w.length < shortestWord(i + l)) {
          shortestWord(i + l) = shortestWord(i) + w.length
        }
      }
    }
    println(s"Case $count: ${shortestWord.last}")
    loop(count + 1)
  }
  case class ParseTarget(str: String, position: Int) {
    def isMatch(prefix: String): Option[ParseTarget] = Some(ParseTarget(str, position + prefix.length)).filter(_ ⇒ str.startsWith(prefix, position))
    def isEnd = str.length == position
  }
  def maxLength(target: ParseTarget, words: Array[(String, Int)])(implicit memo: Array[Int]): Int = {
    if (target.isEnd) 0
    else if (memo(target.position) >= 0) memo(target.position)
    else {
      for ((prefix, length) ← words) {
        target.isMatch(prefix) match {
          case Some(t) ⇒
            val temp = maxLength(t, words) + length
            if (memo(target.position) < temp)  memo(target.position) = temp
          case None ⇒
        }
      }
      memo(target.position)
    }
  }
}
