module Cp : sig val string_1_list_of_string: string -> string list val split_on_char: char -> string -> string list val read_int_list: unit -> int list end = struct let string_1_list_of_string x = String.to_seq x |> List.of_seq |> List.map (String.make 1);; let split_on_char sep s = (* from OCaml Standard Library 4.12 *) let r = ref [] in let j = ref (String.length s) in for i = String.length s - 1 downto 0 do if String.unsafe_get s i = sep then begin r := String.sub s (i + 1) (!j - i - 1) :: !r; j := i end done; String.sub s 0 !j :: !r;; let read_int_list () = read_line () |> split_on_char ' ' |> List.map int_of_string;; end module BTS = struct let make_task work task_f = let (value ,rest) = work in match rest with | [] -> [] | _ -> task_f value rest;; let rec start start_work task_f calc_f = let rec acc task result = match task with | [] -> result | work::rest -> let new_task = make_task work task_f in let result = calc_f work result in acc (new_task @ rest) result in let (value, rest) = start_work in acc (task_f value rest) 0;; end (* define task_f function task_f 'a -> 'b list -> 'c list *) let value_calc value workhd = match value with | "" when workhd = "U" -> "U" | "U" when workhd = "M" -> "M" | "M" when workhd = "G" -> "G" | _ -> value;; let task_f value rest = let rec acc work rest result = match work with | [] -> result | _ when value = "G" -> result | hd::tl -> let next_value = value_calc value hd in let rest = if ((value = next_value) || (value = "G")) then [] else tl in acc tl rest ((next_value, rest)::result) in acc rest [] [];; (* define calc function calc 'a * 'b list -> 'a -> 'a *) let calc_f work result = let (value, rest) = work in match rest with | [] -> if value = "G" then result + 1 else result | _ -> result;; (* define init_f *) let init_f str = ("", Cp.string_1_list_of_string str);; let task_f_call task = let (task_v, task_r) = task in task_f task_v task_r;; (* Enjoy BTS CORE! BTS.start (init_f "UUMGG") task_f calc_f;; *) let () = read_line () |> ignore; let start_string = read_line () in BTS.start (init_f "UUMGG") task_f calc_f |> print_int; print_newline ();;