Problem:
Score : 300 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Another string T is initially empty.
Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:

Append one of the following at the end of T: dream, dreamer, erase and eraser.

Constraints

1≦|S|≦10^5

S consists of lowercase English letters.

Input

The input is given from Standard Input in the following format:

S

Output

If it is possible to obtain S = T, print YES. Otherwise, print NO.

Sample Input 1

erasedream

Sample Output 1

YES

Append erase and dream at the end of T in this order, to obtain S = T.

Sample Input 2

dreameraser

Sample Output 2

YES

Append dream and eraser at the end of T in this order, to obtain S = T.

Sample Input 3

dreamerer

Sample Output 3

NO

Solution in OCaml (4.02.3) (judge verdict: Time Limit Exceeded)

module RegExp : sig
  type t
  val empty_set : t
  val empty_str : t
  val char : char -> t
  val app : t -> t -> t
  val union : t -> t -> t
  val star : t -> t
  val regex_match : char list -> t -> bool
end = struct
  type t = { match_eps : bool; derive : char -> t }

  let rec empty_set =
    { match_eps = false;
      derive = fun _ -> empty_set }

  let empty_str =
    { match_eps = true;
      derive = fun _ -> empty_set }

  let char c =
    { match_eps = false;
      derive = fun c' -> if c = c' then empty_str else empty_set }

  let rec union re1 re2 =
    { match_eps = re1.match_eps || re2.match_eps;
      derive = fun c -> union (re1.derive c) (re2.derive c) }

  let rec app re1 re2 =
    { match_eps = re1.match_eps && re2.match_eps;
      derive = fun c ->
        union
          (app (re1.derive c) re2)
          (if re1.match_eps then re2.derive c else empty_set) }

  let star re0 =
    let rec re =
      { match_eps = true;
        derive = fun c -> app (re0.derive c) re } in re

  let regex_match s re =
    (List.fold_left (fun re -> re.derive) re s).match_eps
end

let () =
  let s = read_line () in
  print_endline @@
  if
    let open RegExp in
    regex_match
      (Array.to_list @@ Array.init (String.length s) @@ String.get s) @@
      (* ((dream(er)?)|(erase(r)?))* *)
      star @@
        union
          (app (char 'd') @@ app (char 'r') @@ app (char 'e') @@ app (char 'a') @@ app (char 'm') @@
            union empty_str @@ app (char 'e') @@ char 'r')
          (app (char 'e') @@ app (char 'r') @@ app (char 'a') @@ app (char 's') @@ app (char 'e') @@
            (union empty_str @@ char 'r'))
  then "YES"
  else "NO"