let word_break s words =
  let n = String.length s in
  let dp = Array.make (n + 1) false in
  dp.(0) <- true;
  for i = 1 to n do
    List.iter (fun w ->
      let wl = String.length w in
      if i >= wl && dp.(i - wl) then begin
        let prefix = String.sub s (i - wl) wl in
        if prefix = w then dp.(i) <- true
      end
    ) words
  done;
  if dp.(n) then 1 else 0

let count_ok strings words =
  let count = ref 0 in
  List.iter (fun s ->
    count := !count + word_break s words
  ) strings;
  !count

;;

let dict = ["apple"; "pen"; "pine"; "pineapple"; "cats"; "cat"; "and"; "sand"; "dog"] in
let inputs = ["applepenapple"; "pineapplepenapple"; "catsanddog"; "catsandog"; "applesand"] in
count_ok inputs dict
