import scala.collection.mutable
object Main extends App {
  import scala.io.StdIn._
  val str = readLine.trim
  val m = readInt()
  val words = Array.fill(m){
    val Array(x, y) =readLine.trim.split(' ')
    (x, y)
  }
  val leftPos = Array.fill(m){-1}
  var forward = Automaton.make(words.map(_._1))
  for (i ← str.indices) {
    forward = forward.move(str(i))
    forward.popMatches.foreach(id ⇒
      leftPos(id) = i)
  }
  val rightPos = Array.fill(m){-1}
  var backward = Automaton.make(words.map(_._2.reverse))
  for (i ← str.indices.reverse) {
    backward = backward.move(str(i))
    backward.popMatches.foreach(id ⇒ rightPos(id) = i)
  }
  //println(words.indices.map(id ⇒ (leftPos(id), rightPos(id))).mkString(", "))
  println(
    words.indices.map{id ⇒
      if (leftPos(id) == -1 || rightPos(id) == -1 || leftPos(id) - words(id)._1.length >= rightPos(id) || leftPos(id) >= rightPos(id) + words(id)._2.length) 0
      else rightPos(id) - leftPos(id) + words(id)._1.length + words(id)._2.length - 1
    }.mkString("\n")
  )
}
sealed trait Automaton {
  protected var matches: List[Int]
  def popMatches: List[Int]
  def move(c: Char): Automaton
  val children: mutable.HashMap[Char, Automaton]
  protected def failure: Automaton
}
object Automaton {
  def make(words: Array[String]): Automaton = {
    val trieRoot = new Trie
    for (i ← words.indices) {
      var trie = trieRoot
      for (c ← words(i)) {
        trie = trie.children.getOrElseUpdate(c, new Trie)
      }
      trie.ids ::= i
    }
    val root = new Root
    val queue = mutable.Queue[(Automaton, Trie)]((root, trieRoot))
    while (queue.nonEmpty) {
      val (auto, trie) = queue.dequeue()
      for ((c, t) ← trie.children) {
        val child = new Child(auto.failure.move(c))
        child.matches = t.ids
        auto.children.update(c, child)
        queue.enqueue((child, t))
      }
    }
    root
  }
  class Trie {
    var ids: List[Int] = Nil
    val children: mutable.HashMap[Char, Trie] = mutable.HashMap()
  }
  class Root extends Automaton {
    override protected var matches: List[Int] = Nil
    override def popMatches: List[Int] = Nil
    override def move(c: Char): Automaton = children.getOrElse(c, this)
    override val children: mutable.HashMap[Char, Automaton] = mutable.HashMap()
    override protected def failure: Automaton = this
  }
  class Child(override val failure: Automaton) extends Automaton {
    var matches: List[Int] = Nil
    private var poped: Boolean = false
    override def popMatches: List[Int] = {
      if (poped) Nil
      else {
        poped = true
        val res = matches ::: failure.popMatches
        matches = Nil
        res
      }
    }
    override def move(c: Char): Automaton = children.getOrElseUpdate(c, failure.move(c))
    override val children: mutable.HashMap[Char, Automaton] = mutable.HashMap()
  }
}
