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 OCaml (judge verdict: Time Limit Exceeded)

let pn = 1000000007

let make_suffix_array t n =
  let ord = Array.make (n + 1) (-1) in
  String.iteri (fun i e -> ord.(i) <- Char.code e) t;
  let sa = Array.init (n + 1) (fun i -> i) in
  let rec doit k =
    if k > n then sa
    else begin
      let cmp a b =
        if ord.(a) <> ord.(b) then ord.(a) - ord.(b)
        else (if a + k <= n then ord.(a+k) else 0) - (if b + k <= n then ord.(b+k) else 0) in
      Array.sort cmp sa;
      let tmp = Array.make (n + 1) 0 in
      let rec aux i =
        if i <= n then begin
          tmp.(sa.(i)) <- tmp.(sa.(i-1)) + (if cmp sa.(i-1) sa.(i) < 0 then 1 else 0);
          aux (i + 1)
        end in
      aux 1;
      Array.iteri (fun i e -> ord.(i) <- e) tmp;
      doit (k * 2)
    end in
  doit 1

let pow x n =
  let rec doit i acc =
    if i = n then acc
    else doit (i + 1) (acc*x) in
  doit 0 1

let str_fold_left f init s =
  let n = String.length s in
  let rec doit i acc =
    if i = n then acc
    else doit (i + 1) (f acc s.[i]) in
  doit 0 init

let contain_p x y =
  let n = String.length x in
  let m = String.length y in
  let h = Array.make (n + 1) 0 in
  String.iteri (fun i c -> h.(i+1) <- h.(i)*pn + Char.code c) x;
  let ht = str_fold_left (fun acc c -> acc*pn + Char.code c) 0 y in
  let x = pow pn m in
  let rec doit i =
    if i > n then false
    else if h.(i) - h.(i-m)*x = ht then true
    else doit (i + 1) in
  doit m

let () =
  let t = read_line () in
  let n = String.length t in
  let sa = make_suffix_array t n in
  let q = read_int () in
  let rec doit i =
    if i < q then begin
      let p = read_line () in
      let rec aux l r =
        if l >= r then r
        else begin
          let m = (l + r) / 2 in
          if compare (String.sub t sa.(m) (n - sa.(m))) p < 0 then aux (m + 1) r
          else aux l m
        end in
      let r = aux 0 n in
      Printf.printf "%d\n" (if contain_p (String.sub t sa.(r) (if n - sa.(r) - (String.length p) >= 0 then String.length p else n - sa.(r))) p then 1 else 0);
      doit (i + 1)
    end in
  doit 0