Problem:
String Search

Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i.

Input

In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively.

Output

For each question, print 1 if the text includes P_i, or print 0 otherwise.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P_i ≤ 1000

1 ≤ Q ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
4
aa
ba
bb
xyz

Sample Output 1

1
1
0
0

Solution in Scala (judge verdict: Time Limit Exceeded)

import scala.io.StdIn.{readLine,readInt}
import scala.collection.mutable.ArrayBuffer

object Main {
  def prefix(p:String) = {
    val m = p.length
    val a = new Array[Int](m)
    var k=0

    a(0) = 0
    for(q<-1 until m) {
      while(k>0 && p(k)!=p(q)) k = a(k-1)
      if(p(k) == p(q)) k = k+1
      a(q) = k
    }
    a
  }

  def main(args:Array[String]) = {
    val t = readLine.trim
    val n = readInt
    val f = new Array[Array[Int]](n)
    val q = new Array[Int](n)
    val p = for(i<-0 until n) yield {
      val s = readLine.trim
      f(i) = prefix(s)
      s
    }
    val r = new Array[Int](n)

    for(i<-0 until t.length) {
      for(j<-0 until n if r(j)==0) {
        while(q(j)>0 && p(j)(q(j))!=t(i)) q(j) = f(j)(q(j)-1)
        if(p(j)(q(j))==t(i)) q(j) = q(j)+1
        if(q(j)==p(j).length) {
          r(j)=1
          q(j) = f(j)(q(j)-1)
        }
      }
    }

    println(r.mkString("\n"))
  }
}