jiahuimbzuai/CoQuIR huggingface dataset:
//  [javascript]
function extractVal(input) {
  input = input.split("\n");
  const [h,w,k] = input.shift().trim().split(" ").map(v => parseInt(v, 10));
  const rows = new Array(h);
  for (let i=0;i<h;i++) {
  	rows[i] = input[i].trim().split("");
  }
  
  let blacks = 0;
  for (let i=0;i<rows.length;i++) {
  	for (let j=0;j<rows[0].length;j++) {
    	blacks += rows[i][j] === "#" ? 1 : 0;
    }
  }

  return {
    h, w, k, rows, blacks
  }
}

const copy = (arr) => {
  const rows = new Array(arr.length);
  for (let i=0;i<rows.length;i++) {
    rows[i] = [...arr[i]];
  }
  return rows;
}

function Main(input) {
  const {
    h, w, k, rows, blacks
  } = extractVal(input);
  
  if (blacks === k) {
  	console.log(1);
    return
  }
  
  if (blacks < k) {
  	console.log(0);
    return
  }
  
  let total = 0;
  const paintRow = (arr, r) => {
    let black = 0;
    for (let i=0;i<arr[0].length;i++) {
      if (arr[r][i] === "#") {
        black += 1;
      }
      arr[r][i] = "r";
    }
    return black;
  }

  const paintColumn = (arr, c) => {
    let black = 0;
    for (let i=0;i<arr.length;i++) {
      if (arr[i][c] === "#") {
        black += 1;
      }
      arr[i][c] = "r";
    }
    return black;
  }

  const traverse = (arr, r, c, left) => {    
      if (r < arr.length) {
        const new1 = copy(arr);
        traverse(new1, r+1, c, left - paintRow(new1, r));
        traverse(arr, r+1, c, left);
      } else if (c < arr[0].length) {
        const new3 = copy(arr);
        traverse(new3, r, c+1, left - paintColumn(new3, c));
        traverse(arr, r, c+1, left);
      } else {
      	if (left == k) total++
      }
  }

  traverse(rows, 0, 0, blacks);
  
  console.log(total);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import "fmt"

func main() {
	var h, w, k int
	count := 0
	fmt.Scan(&h, &w, &k)
	c := make([]string, h, h)
	for i := range c {
		fmt.Scan(&c[i])
	}
	for i := 0; i < 1<<h; i++ {
		for l := 0; l < 1<<w; l++ {
			sharpNum := countSharp(c, i, l)
			if sharpNum == k {
				count++
			}
		}
	}
	fmt.Println(count)
}

func countSharp(c []string, h, w int) int {
	count := 0
	for i := 0; i < len(c); i++ {
		if (h >> i & 1) == 1 {
			continue
		}
		for k := 0; k < len(c[0]); k++ {
			if (w >> k & 1) == 1 {
				continue
			}
			if c[i][k] == '#' {
				count++
			}
		}
	}
	return count
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)
var out = bufio.NewWriter(os.Stdout)

func pow(a int, p int) int {
	if p == 0 {
		return 1
	} else if p%2 == 1 {
		return a * pow(a, p-1)
	} else {
		b := pow(a, p/2)
		return b * b
	}
}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}

func main() {
	buf := make([]byte, 1024*1024)
	sc.Buffer(buf, bufio.MaxScanTokenSize)
	sc.Split(bufio.ScanWords)
	defer out.Flush()

	H, W, K := nextInt(), nextInt(), nextInt()
	black := make([][]bool, H)
	for i := 0; i < H; i++ {
		black[i] = make([]bool, W)
		s := next()
		for j := 0; j < W; j++ {
			if s[j] == '#' {
				black[i][j] = true
			}
		}
	}

	H_KOUHO := pow(2, H)
	W_KOUHO := pow(2, W)
	col_sum_each := make([][]int, H_KOUHO)

	for n := 0; n < H_KOUHO; n++ {
		r := n
		col_sum_each[n] = make([]int, W)
		for i := 0; i < H; i++ {
			if r%2 == 0 {
				for j := 0; j < W; j++ {
					if black[i][j] {
						col_sum_each[n][j]++
					}
				}
			}
			r = r / 2
		}
	}

	count := 0
	for n := 0; n < H_KOUHO; n++ {
		for m := 0; m < W_KOUHO; m++ {
			r := m
			sum := 0
			for j := 0; j < W; j++ {
				if r%2 == 0 {
					sum += col_sum_each[n][j]
				}
				r = r / 2
			}
			if sum == K {
				count++
			}
		}
	}

	fmt.Fprintf(out, "%d\n", count)
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

func main() {
	// Code for C - H and V
	var H, W, K int
	fmt.Scanf("%d %d %d", &H, &W, &K)

	c := make([]string, H)
	for i := 0; i < H; i++ {
		fmt.Scanf("%s", &c[i])
	}

	s := make([]string, H)
	var n1 int = H
	var n2 int = W
	fmt.Println(c)
	for i := 0; i < (1 << n1); i++ {
		for j := 0; j < (1 << n2); j++ {
			copy(s, c)
			for l := 0; l < n1; l++ {
				if i>>l&1 == 1 {
					s[l] = strings.Repeat(string('.'), W)
				}
				for m := 0; m < n2; m++ {
					if j>>m&1 == 1 {
						//for k := 0; k < H; k++ {
						//s[k][m : m+1] = string('.')
						//}
					}
				}
			}
		}
	}
}
//  [go]
package main

import "fmt"

func main() {

	var h, w, k int

	fmt.Scanf("%d %d %d", &h, &w, &k)

	val := make([][]bool, h)
	for i := 0; i < h; i++ {
		val[i] = make([]bool, w)

		var v string
		fmt.Scanf("%s", &v)
		for j, v := range v {
			if v == 35 {
				val[i][j] = true
			} else {
				val[i][j] = false
			}
		}
	}

	var ans int = 0
	for m := 0; m <= 1<<h; m++ {
		for n := 0; n <= 1<<w; n++ {

			cnt := 0
			for i := 0; i < h; i++ {
				for j := 0; j < w; j++ {
					if m>>i&1 == 0 {
						continue
					}
					if n>>j&1 == 0 {
						continue
					}
					if n != (j+1) && val[i][j] {
						cnt++
					}
				}
			}
			if cnt == k {
				ans++
			}
		}
	}

	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
)

// bit全探索

func main(){
	var h, w, k int
	fmt.Scan(&h, &w, &k )
	js := make([][]byte, h)
	for i := range js {
		fmt.Scan(&js[i])
	}

	var ans int

	for i := 0; i < 1 <<uint(h+w); i++ {
		cnt := 0
		for s := 0; s < h; s++ {
			for t := 0; t < w; t++ {
				fmt.Println(i&(1<<uint(s)))
				if i&(1<<uint(s)) > 0 {
						continue
				}
				if i&(1<<uint(h+t)) > 0 {
					continue
				}
				if js[s][t] == '#' {
					cnt++
				}
			}
		}
		if cnt == k {
			ans++
		}
	}
	fmt.Println(ans)
}
//  [ruby]
H, W, K = gets.split.map(&:to_i)
c = Array.new H
total = 0
h_count = Array.new H
H.times do |i|
    c[i] = gets.split('')
    h_count = c[i].count('#')
    total += h_count
end

result = 0
hlist = (0..H-1).to_a
wlist = (0..W-1).to_a
0.upto(H) do |hc|
    hlist.combination(hc) do |delhlist|
        dels = 0
        delhlist.each do |dh|
            dels += h_count[dh]
        end
        next if total - dels < K
        map = c.reject.with_index do |_, i|
            delhlist.include?(i)
        end
        w_count = Array.new W
        W.times do |w|
            cx = 0
            map.each do |line|
                cx += 1 if line[w] == "#"
            end
            w_count[w] = cx
        end
        0.upto(W) do |wc|
            wlist.combination(wc) do |cntlist|
                cnt = 0
                cntlist.each do |cl|
                    cnt += w_count[cl]
                end
                if cnt == K
                    result += 1
                end
            end
        end
    end
end

puts result
//  [ruby]
def check(bc,hw)
  if hw == $h + $w
    return
  elsif hw == $h
    $d = $c.map{|e| e.chars}.transpose.map{|e| e.join("")}
  end
  if hw < $h
    cc = $c[hw].count('#')
  else
    cc = $d[hw-$h].count('#')
  end
  if bc - cc >= $k
    if bc - cc == $k
      $ans += 1
    end
    if hw < $h
      $c[hw].tr!('#','*')
    else
      $d[hw-$h].tr!('#','&')
    end
    check(bc-cc,hw+1)
    if hw < $h
      $c[hw].tr!('*','#')
    else
      $d[hw-$h].tr!('&','#')
    end
  end
  check(bc,hw+1)
end

$h, $w, $k = gets.strip.split.map(&:to_i)
$c = []
bmax = 0
$h.times do
  t = gets.strip
  $c.push t
  bmax += t.count('#')
end

if bmax == $k
  $ans = 1
else
  $ans = 0
end
if bmax >= $k
  check(bmax,0)
end
p $ans
//  [ruby]
h, w, k = gets.split.map(&:to_i)
field = h.times.map {gets.chomp.chars}

num = 0

(1..h).each do |y_num|
  field.combination(y_num) do |rows|
    tmp = rows.transpose.map(&:join)
    (0..tmp.size).each do |x_num|
      tmp.combination(x_num) do |cols|
        co = 0
        cols.map {co += _1.count("#")}
        num += 1 if co == k
      end
    end
  end
end

puts num
//  [ruby]
H, W, K = gets.split(" ").map(&:to_i)
mtr = Array.new(H, [])

H.times do |i|
    mtr[i] = gets.chomp.split("").map{|c| c == "#"}
end

ans = 0
(0...(1 << H)).each do |hi|
    (0...(1 << W)).each do |wi|
        count = 0
        hi.each do |i|
            wi.each do |j|
                if mtr[i][j] && hi[i] != 0 && wi[j] != 0
                    count += 1
                end
            end
        end
        ans +=1 if count == K 
    end
end

puts ans
//  [ruby]
def comb(n,k); k.times.inject(1) {|s,i| s * (n - i) / (i + 1) }; end

H, W, K = gets.split.map(&:to_i)
MAP = H.times.map{ gets.chomp }

def black(h,w)
  bc = 0
  H.times do |y|
    W.times do |x|
      bc += 1 if (h[y] > 0 || w[x] > 0) && MAP[y][x] == '#'
    end
  end
  bc
end

count = 0
(1 << H).times do |h|
  (1 << W).times do |w|
    count += 1 if black(h,w) == K
  end
end
puts count
//  [ruby]
H, W, K = gets.split.map(&:to_i)

bc = 0 # 黒の数
tmpc = []
$c = []
# col = []
# col = col.fill(0, 0..H-1)
# row = []
# row = row.fill(0, 0..W-1)

H.times do |i|
  tmpc[i] = gets.chomp.split("")
  $c[i] = tmpc[i].map{ |x| (x=='#') ? 1 :0 }
  bc +=  $c[i].inject(:+)
end

# puts "#{$c}"
# tc = $c.transpose
# W.times do |j|
#   row[j] = tc[j].inject(:+)
# end

# bit全探索
n = H+W
ans = 0
(1 << n).times do |i|
  cnt = bc
  n.times do |j|
    cc = Marshal.load(Marshal.dump($c))
    if i[j] == 1 and j < H
      W.times do |k|
        if cc[j][k] == 1
          cc[j][k] = 0
          cnt -= 1
        end
      end
    elsif i[j] == 1 and j >= H
      H.times do |k|
        if cc[k][j-H] == 1
          cc[k][j-H] = 1
          cnt -= 1
        end
      end
    end
  end

  if cnt == K
    ans += 1
  end 
  
end

puts ans
//  [rust]
use proconio::input;
use proconio::marker::*;
use proconio::fastout;

#[fastout]
fn main() {
  input! {
    h : usize, w : usize, k : usize,
  };
  input! {
    c : [Chars; h],
  };

  let mut res = 0usize;
  for rows in 0..(1 << h) {
    for cols in 0..(1 << w) {
      let mut cnt = 0;
      for i in 0..h {
        if rows & (1 << i) != 0 {
          for j in 0..w {
            if cols & (1 << j) != 0 {
              if c[i][j] == '#' {
                cnt += 1;
              }
            }
          }
        }
      }
      if cnt == k {
        res += 1;
      }
    }
  }
  
  println!("{}", res);
}
//  [rust]
use itertools::iproduct;
use proconio::{input, marker::Chars};

fn main() {
    input!(h: usize, w: usize, k: usize, g: [Chars; h]);
    println!(
        "{}",
        iproduct!(0..1 << h, 0..1 << w)
            .filter(|&(bs, cs)| {
                iproduct!(
                    (0..h).filter(|&i| bs >> i & 1 == 1),
                    (0..w).filter(|&j| cs >> j & 1 == 1)
                )
                .filter(|&(i, j)| g[i][j] == '#')
                .count()
                    == k
            })
            .count()
    );
}
//  [rust]
use proconio::input;
use proconio::marker::Chars;
fn main() {
    input!{
        h: usize,
        w: usize,
        k: usize,
        c: [Chars; h],
    };
    let mut cnt = 0;
    let mut ans = 0;
    for hi in 0..h*2 {
        for wi in 0..w*2 {
            for i in 0..h {
                for j in 0..w {
                    if hi >> i & 1 == 1 {
                        continue;
                    }
                    if wi >> j & 1 == 1 {
                        continue;
                    }
                    if c[i][j] == '#' {
                        cnt += 1;
                    }
                }
            }
            eprintln!("hi = {:#010b} wi = {:#010b} cnt = {}", hi, wi, cnt);
            if cnt == k {
                ans += 1;
            }
            cnt = 0;
        }
    }
    println!("{}", ans);
}
//  [rust]
use proconio::input;

fn main() {
    input! {
        h: usize, w: usize, k: usize,
    }
    let mut grid: Vec<Vec<char>> = Vec::new();
    for _ in 0..h {
        let row = read::<String>();
        let row = row.chars().collect::<Vec<_>>();
        grid.push(row);
    }

    let mut ret = 0;
    for hbit in 0..1 << h {
        for wbit in 0..1 << w {
            let mut cnt = 0;
            for i in 0..h {
                for j in 0..w {
                    if (hbit & (1 << i) == 0) && (wbit & (1 << j) == 0) {
                        if grid[i][j] == '#' {
                            cnt += 1;
                        }
                    }
                }
            }
            if cnt == k {
                ret += 1;
            }
        }
    }
    println!("{}", ret);
}

fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    s.trim().parse().ok().unwrap()
}
//  [rust]
use proconio::{input,fastout};

fn main() {
  input! {
    h : usize, w : usize, k : usize,
  };
  input! {
    c : [Chars; h],
  };

  let mut res = 0usize;
  for rows in 0..(1 << h) {
    for cols in 0..(1 << w) {
      let mut cnt = 0;
      for i in 0..h {
        if rows & (1 << i) != 0 {
          for j in 0..w {
            if cols & (1 << j) != 0 {
              if c[i][j] == '#' {
                cnt += 1;
              }
            }
          }
        }
      }
      if cnt == k {
        res += 1;
      }
    }
  }
  
  println!("{}", res);
}
//  [swift]
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func power(_ a: Int, _ b: Int) -> Int {
    var ans = 1
    for _ in 1...b {
        ans *= a
    }
    return ans
}

func main() {
    let patterns = [
        [0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 0, 0],
        [0, 1, 0, 0, 0, 0],
        [1, 1, 0, 0, 0, 0],
        [0, 0, 1, 0, 0, 0],
        [1, 0, 1, 0, 0, 0],
        [0, 1, 1, 0, 0, 0],
        [1, 1, 1, 0, 0, 0],
        [0, 0, 0, 1, 0, 0],
        [1, 0, 0, 1, 0, 0],
        [0, 1, 0, 1, 0, 0],
        [1, 1, 0, 1, 0, 0],
        [0, 0, 1, 1, 0, 0],
        [1, 0, 1, 1, 0, 0],
        [0, 1, 1, 1, 0, 0],
        [1, 1, 1, 1, 0, 0],
        [0, 0, 0, 0, 1, 0],
        [1, 0, 0, 0, 1, 0],
        [0, 1, 0, 0, 1, 0],
        [1, 1, 0, 0, 1, 0],
        [0, 0, 1, 0, 1, 0],
        [1, 0, 1, 0, 1, 0],
        [0, 1, 1, 0, 1, 0],
        [1, 1, 1, 0, 1, 0],
        [0, 0, 0, 1, 1, 0],
        [1, 0, 0, 1, 1, 0],
        [0, 1, 0, 1, 1, 0],
        [1, 1, 0, 1, 1, 0],
        [0, 0, 1, 1, 1, 0],
        [1, 0, 1, 1, 1, 0],
        [0, 1, 1, 1, 1, 0],
        [1, 1, 1, 1, 1, 0],
        [0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 1],
        [0, 1, 0, 0, 0, 1],
        [1, 1, 0, 0, 0, 1],
        [0, 0, 1, 0, 0, 1],
        [1, 0, 1, 0, 0, 1],
        [0, 1, 1, 0, 0, 1],
        [1, 1, 1, 0, 0, 1],
        [0, 0, 0, 1, 0, 1],
        [1, 0, 0, 1, 0, 1],
        [0, 1, 0, 1, 0, 1],
        [1, 1, 0, 1, 0, 1],
        [0, 0, 1, 1, 0, 1],
        [1, 0, 1, 1, 0, 1],
        [0, 1, 1, 1, 0, 1],
        [1, 1, 1, 1, 0, 1],
        [0, 0, 0, 0, 1, 1],
        [1, 0, 0, 0, 1, 1],
        [0, 1, 0, 0, 1, 1],
        [1, 1, 0, 0, 1, 1],
        [0, 0, 1, 0, 1, 1],
        [1, 0, 1, 0, 1, 1],
        [0, 1, 1, 0, 1, 1],
        [1, 1, 1, 0, 1, 1],
        [0, 0, 0, 1, 1, 1],
        [1, 0, 0, 1, 1, 1],
        [0, 1, 0, 1, 1, 1],
        [1, 1, 0, 1, 1, 1],
        [0, 0, 1, 1, 1, 1],
        [1, 0, 1, 1, 1, 1],
        [0, 1, 1, 1, 1, 1],
        [1, 1, 1, 1, 1, 1],
    ]
    
    let line = readInts()
    let h = line[0]
    let w = line[1]
    let k = line[2]
    var cs: [[String]] = []
    for _ in 1...h {
        let c = Array(readLine()!).map { String($0) }
        cs.append(c)
    }
    
    var ans = 0
    for i in 0..<power(2, h) {
        let h_pattern = patterns[i]
        for j in 0..<power(2, w) {
            let w_pattern = patterns[j]
            var black_count = 0
            for u in 0..<h {
                for v in 0..<w {
                    if h_pattern[u] == 0 && w_pattern[v] == 0 && cs[u][v] == "#" {
                        black_count += 1
                    }
                }
            }
            if black_count == k {
                ans += 1
            }
        }
    }
    
    print(ans)
}

main()
//  [swift]
let input = readLine()!.split(separator: " ").map { Int($0)! }
let H = input[0]
let W = input[1]
let K = input[2]

enum Square: Character {
    case white = "."
    case black = "#"
}

var c = [[Square]]()
let numberOfRowCombinations = 1 << H
let numberOfColumnCombinations = 1 << W
var dp = Array(repeating: Array(repeating: Optional<Int>.none, count: numberOfColumnCombinations), count: numberOfRowCombinations)
dp[0][0] = 0

for _ in stride(from: 0, to: H, by: 1) {
    let row = Array(readLine()!).map { Square(rawValue: $0)! }
    c.append(row)
    dp[0][0]! += row.filter { $0 == .black }.count
}

for i in stride(from: 0, to: H, by: 1) {
    for state in stride(from: 0, to: numberOfRowCombinations, by: 1) {
        guard state & (1 << i) == 0,
            let value = dp[state][0] else { continue }
        let nextState = state | (1 << i)
        dp[nextState][0] = value - c[i].filter { $0 == .black }.count
    }
}

for j in stride(from: 0, to: W, by: 1) {
    for rowState in stride(from: 0, to: numberOfRowCombinations, by: 1) {
        for columnState in stride(from: 0, to: numberOfColumnCombinations, by: 1) {
            guard columnState & (1 << j) == 0,
                let value = dp[rowState][columnState] else { continue }
            let nextColumnState = columnState | (1 << j)
            var numberOfBlackSquares = 0
            for i in stride(from: 0, to: H, by: 1) {
                if rowState & (1 << i) == 0, c[i][j] == .black {
                    numberOfBlackSquares += 1
                }
            }
            dp[rowState][nextColumnState] = value - numberOfBlackSquares
        }
    }
}

let result = dp.reduce(0) { sum, row in
    sum + row.filter { $0 == K }.count
}
print(result)
//  [swift]
let inputs = readLine()!.split(separator: " ").map { Int($0)! }
let H = inputs[0] 
let W = inputs[1]
let K = inputs[2]
var grid: [[Character]] = .init(repeating: .init(repeating: Character("@"), count: W), count: H)

for row in 0..<H {
  grid[row] = Array(readLine()!)
}

var ans = 0
for h in 0..<1<<H {
  for w in 0..<1<<W {
    var black = 0
    for i in 0..<H {
      for j in 0..<W {
        if h & (1<<i) == 0 && w & (1 << j) == 0 && grid[i][j] == "#" {
          black += 1
        }
      }
    }
    ans += black == K ? 1 : 0
  }
}
print(ans)
//  [swift]
import Foundation

func readInts() -> [Int]{
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let rck = readInts()
    let (row, col, k) = (rck[0], rck[1], rck[2])
    var tableC = [[String]]()
    for _ in 0..<row {
        tableC.append(readLine()!.map { String($0) })
    }
    
    // ≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈≈ここまで入力
    // bit全探索で処理する
    print(1 << row)
    var ans = 0
    for r in 1..<1<<row {
        for c in 1..<1<<col {
            var countBlack = 0
            for i in 0..<row {
                for j in 0..<col {
                    if r >> i & 1 == 1 && c >> j & 1 == 1 && tableC[i][j] == "#" {
                        countBlack += 1
                    }
                }
            }
            if countBlack == k {
                ans += 1
            }
        }
    }
    print(ans)
}
main()
//  [swift]

func main(){
   let split = (readLine()!).split(separator: " ").map({ Int($0)! })
   let h = split[0]
   let w = split[1]
   let k = split[2]

   var c: [[Character]] = []
   for _ in 0..<h {
      let s = Array(readLine()!)
      c.append(s)
   }
   print(c)

   var columnDict: [Int: Int] = [:]
   for i in 0..<w {
      columnDict[i] = 1
   }
   var rowDict: [Int: Int] = [:]
   for i in 0..<h {
      rowDict[i] = 1
   }

   let answer = recurse(crMap: ["col": columnDict, "row": rowDict], array: c, rowIndex: 0, colIndex: 0, k: k)
   print(answer)
}

func recurse(crMap: [String: [Int: Int]], array: [[Character]], rowIndex: Int, colIndex: Int, k: Int) -> Int {
   if rowIndex == array.count && colIndex == array[0].count {
      return good(array: array, crMap: crMap, k: k) ? 1 : 0
   }
   
   var tempMap = crMap
   var tempAns = 0
   if rowIndex < array.count {
      if colIndex < array[0].count {
         tempAns += recurse(crMap: crMap, array: array, rowIndex: rowIndex + 1, colIndex: colIndex + 1, k: k)

         var tempMap1 = crMap
         tempMap1["col"]![colIndex] = 0
         tempMap1["row"]![rowIndex] = 1
         tempAns += recurse(crMap: tempMap1, array: array, rowIndex: rowIndex + 1, colIndex: colIndex + 1, k: k)
         
         var tempMap2 = crMap
         tempMap2["col"]![colIndex] = 0
         tempMap2["row"]![rowIndex] = 0
         tempAns += recurse(crMap: tempMap2, array: array, rowIndex: rowIndex + 1, colIndex: colIndex + 1, k: k)
         
         var tempMap3 = crMap
         tempMap3["col"]![colIndex] = 1
         tempMap3["row"]![rowIndex] = 0
         tempAns += recurse(crMap: tempMap3, array: array, rowIndex: rowIndex + 1, colIndex: colIndex + 1, k: k)
      } else {
         tempMap["row"]![rowIndex] = 0
         tempAns = recurse(crMap: crMap, array: array, rowIndex: rowIndex + 1, colIndex: colIndex, k: k) +
         recurse(crMap: tempMap, array: array, rowIndex: rowIndex + 1, colIndex: colIndex, k: k)
      }
   } else if colIndex < array[0].count {
      tempMap["col"]![colIndex] = 0
      tempAns += recurse(crMap: crMap, array: array, rowIndex: rowIndex, colIndex: colIndex + 1, k: k) +
      recurse(crMap: tempMap, array: array, rowIndex: rowIndex, colIndex: colIndex + 1, k: k)
   }
   return tempAns
}

func good(array: [[Character]], crMap: [String: [Int: Int]], k: Int) -> Bool {
   var tempK = 0
   for i in 0..<array.count {
      for j in 0..<array[0].count {
         if crMap["col"]![j] == 1 && crMap["row"]![i] == 1 && array[i][j] == "#" {
            tempK += 1
         }
      }
   }
   return tempK == k
}
main()
//  [typescript]
import * as fs from 'fs';

const input = fs.readFileSync('/dev/stdin', 'utf8');

_c(input);

// 盤面はそこまで大きくない
// 列や行を入れ替えても計算に支障はない（合計なので、順番は関係ない）
// K を下回った場合はそれ以上増やしても意味がない
// よくわからん！指数オーダーだけど全部試そう！

function _c(input: string) {
  const [_HWK, ...C] = input.split('\n');
  const [H, W, K] = _HWK.split(' ').map((s) => parseInt(s));
  const Black = [] as (1 | 0)[][];
  let sum = 0;
  for (let y = 0; y < H; y++) {
    const line = C[y];
    Black[y] = [];
    for (let x = 0; x < line.length; x++) {
      const color = line[x];
      if (color === '#') {
        Black[y].push(1);
        sum++;
      } else {
        Black[y].push(0);
      }
    }
  }
  // console.log(Black, sum);

  const target = sum - K; // 消したい数

  // 全パターンマスクして、消した数を数える
  let patterns = 0;
  for (let maskY = 0; maskY < 2 ** H; maskY++) {
    for (let maskX = 0; maskX < 2 ** W; maskX++) {
      calculate: {
        let masked = 0;
        for (let y = 0; y < Black.length; y++) {
          const line = Black[y];
          const isMaskedY = ((maskY >> y) & 1) === 1;
          for (let x = 0; x < line.length; x++) {
            if (line[x] === 1) {
              // 行または列がマスクされているならば、インクリメント
              if (isMaskedY || ((maskX >> x) & 1) === 1) {
                masked++;

                // 超えてしまったら望みはない
                if (masked > target) {
                  break calculate;
                }
              }
            }
          }
        }
        if (masked === target) {
          patterns++;
        }
      }
    }
  }

  console.log(patterns);
}
//  [typescript]
import { readFileSync } from 'fs'

function main(input: string[]) {
  let [H, W, K] = input[0].split(' ').map(v=>parseInt(v, 10))
  let c : string[] = input.slice(1, input.length);

  let ans = 0
  for (let bitH = 0; bitH < 1 << H; bitH++) {
    for (let bitW = 0; bitW < 1 << W; bitW++) {
      let ansOne = 0
      for (let i = 0; i < H; i++) {
        for (let j = 0; j < W; j++) {
          if (!(bitH & 1 << i)) {
            if (!(bitW & 1 << j)) {
              if (c[i][j] == '#') {
                ansOne++
              }
            }
          }
        }
      }
      if (ansOne == K) {
        ans++
      }
    }
  }

  console.log(ans.toString())
}

let lines: string[] = [];
const reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

reader.on('line', function (line: string) {
  lines.push(line);
});
reader.on('close', function () {
  main(lines)
});
//  [typescript]
import { readFileSync } from 'fs'

const range = (length: number) =>
  [...Array(length).keys()]

function main(input: string) {
  const [header, ...lines] = input.split('\n')
  const [h, w, k] = header.split(' ').map(Number)

  // すべてのマス
  const cells = lines.flatMap((v, row) =>
    v.split('').map((color, col) => ({ color, row, col }))
  )

  // 行・列選びパターン
  const pattarn = range(1 << h << w).map(mask => {
    const rows = new Set(range(h).filter(v => (mask >> w >> v) & 1))
    const cols = new Set(range(w).filter(v => (mask >> v) & 1))

    return { rows, cols }
  })

  const result = pattarn.filter(({ rows, cols }) => {
    const blackCells = cells.filter(cell =>
      cell.color === '#' && !rows.has(cell.row) && !cols.has(cell.col)
    )

    return blackCells.length === k
  })

  console.log(result.length)
}

main(readFileSync('/dev/stdin', 'utf8').trim())
//  [typescript]
import { readFileSync } from "fs";

const { cin, nCin, biCin } = (() => {
  const inputs = readFileSync("/dev/stdin", "utf-8").split(/[\n|\s]+/);
  let count = 0;
  const cin = () => inputs[count++];
  return { cin: cin, nCin: () => Number(cin()), biCin: () => BigInt(cin()) };
})();

const range = (n: number | bigint) => [...Array(Number(n))].map((_, i) => i);

type Color = "Black" | "White";

{
  const [H, W, K] = [nCin(), nCin(), nCin()];

  const cnt = (() => {
    const css: Color[][] = range(H).map(() =>
      cin()
        .split("")
        .map((c) => (c === "#" ? "Black" : "White") as Color)
    );

    const initialBlackCnt = css
      .map((cs) => cs.reduce((acc, c) => (c === "Black" ? acc + 1 : acc), 0))
      .reduce((acc, x) => acc + x, 0);

    const hPickFn = (n: number, hPicks: [number, boolean][]): number => {
      const wPickFn = (hPicks: [number, boolean][]): number => {
        const wPickFn = (n: number, wPicks: [number, boolean][]): number =>
          n >= W
            ? initialBlackCnt -
                hPicks
                  .filter(([, b]) => b)
                  .map(([i]) =>
                    wPicks
                      .filter(([, b]) => b)
                      .map(([j]) => (css[i][j] === "Black" ? 1 : 0))
                      .reduce((acc: number, x) => acc + x, 0)
                  )
                  .reduce((acc: number, x) => acc + x, 0) ===
              K
              ? 1
              : 0
            : wPickFn(n + 1, wPicks) +
              wPickFn(
                n + 1,
                wPicks.map(([j, b]) => (j === n ? [j, true] : [j, b]))
              );

        return wPickFn(
          0,
          range(W).map((j) => [j, false] as [number, boolean])
        );
      };

      return n >= H
        ? wPickFn(hPicks)
        : hPickFn(n + 1, hPicks) +
            hPickFn(
              n + 1,
              hPicks.map(([i, b]) => (i === n ? [i, true] : [i, b]))
            );
    };

    return hPickFn(
      0,
      range(H).map((i) => [i, false] as [number, boolean])
    );
  })();

  console.log(cnt);
}
//  [typescript]
import * as fs from "fs";
const _input = fs.readFileSync("/dev/stdin", "utf8").split("\n");

result(_input);

function result(input: string[]) {
  const K = Number(input.shift().split(" ")[2]);
  const arr = input.map((item) => item.split(""));

  const m = arr.length;
  const n = arr[0].length;
  const bitM = parseInt("1".repeat(arr.length), 2) + 1;
  const bitN = parseInt("1".repeat(arr[0].length), 2) + 1;
  let ans = 0;

  for (let h = 0; h < bitM; h++) {
    for (let w = 0; w < bitN; w++) {
      let cnt = 0;
      for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
          if ((h >> i) & 1 || (w >> j) & 1) continue;
          if (arr[i][j] === "#") cnt++;
        }
      }
      if (cnt === K) ans++;
    }
  }

  console.log(ans);
}
//  [typescript]
import * as fs from "fs";
const input = fs.readFileSync("/dev/stdin", "utf8").split("\n");
const K = Number(input.shift().split(" ")[2]);
const arr = input.map((item) => item.split(""));

const m = arr.length;
const n = arr[0].length;
const bitM = parseInt("1".repeat(arr.length), 2);
const bitN = parseInt("1".repeat(arr[0].length), 2);
let ans = 0;

for (let h = 0; h < bitM; h++) {
  for (let w = 0; w < bitN; w++) {
    let cnt = 0;
    for (let i = 0; i < m; i++) {
      for (let j = 0; j < n; j++) {
        if ((h >> i) & 1 || (w >> j) & 1) continue;
        if (arr[i][j] === "#") cnt++;
      }
    }
    if (cnt === K) ans++;
  }
}

console.log(ans);
//  [python]
N = input()

if N.replace('eraser', '').replace('erase', '').replace('dreamer', '').replace('dream', '') == '':
    print('YES')
else:
    print('NO')
//  [python]
S=input()

S=S.replace("eraser","")
S=S.replace("erase","")
S=S.replace("dreamer","")
S=S.replace("dream","")

if S=="":
    print("YES")
else:
    print("NO")
//  [python]
s = input().replace("eraser", "").replace("erase", "").replace("dreamer", "").replace("dream", "")
if s:
    print("NO")
else:
    print("YES")
//  [python]
import itertools

input_moji = input()

count = 0

lis = ['dream','dreamer', 'erase','eraser']

for i, _ in enumerate(lis, 1):     
    for j in itertools.permutations(lis, r=i):  # rには1、2、3と渡される
        total = "".join([str(_) for _ in j])
        if input_moji == total:
            count += 1
            print('Yes')

if count == 0:
    print('No')
//  [python]
import itertools

input_moji = input()

count = 0

lis = ['dream','dreamer', 'erase','eraser']

for i, _ in enumerate(lis, 1):     
    for j in itertools.permutations(lis, r=i):  # rには1、2、3と渡される
        total = "".join([str(_) for _ in j])
        print(total)
        if input_moji == total:
            count += 1
            print('Yes')

if count == 0:
    print('No')
//  [python]
import itertools

input_moji = input()

count = 0

lis = ['dream','dreamer', 'erase','eraser']

origin_list = ['dream','dreamer', 'erase','eraser']
for i in itertools.product(origin_list, repeat=2):
    total = "".join([str(_) for _ in i])
    if input_moji == total:
        count += 1
        print('YES')

if count == 0:
    print('NO')
//  [java]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) {
		FastScanner sc = new FastScanner(System.in);

		String S = sc.nextLine();

		String dream = "dream";
		String erase = "erase";

		int count = 0;
		while (count != -1) {
			if (S.startsWith(dream, count)) {
				count += 5;
				if (S.startsWith("er", count)) {
					if(S.startsWith(erase, count)) {
						count += 5;
						if(S.startsWith("r", count)) {
							count++;
						}
					} else {
						count += 2;
					}
				}
			} else if (S.startsWith(erase, count)) {
				count += 5;
				if (S.startsWith("r", count)) {
					count++;
				}
			} else {
				count = -1;
			}

			if (count == S.length()) {
				break;
			}
		}


		if (count != -1 ) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}

	}


	static class FastScanner {

		private BufferedReader reader = null;
	    private StringTokenizer tokenizer = null;

	    public FastScanner(InputStream in) {
	        reader = new BufferedReader(new InputStreamReader(in));
	        tokenizer = null;
	    }

	    public String next() {
	        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
	            try {
	                tokenizer = new StringTokenizer(reader.readLine());
	            } catch (IOException e) {
	                throw new RuntimeException(e);
	            }
	        }
	        return tokenizer.nextToken();
	    }

	    public String nextLine() {
	        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
	            try {
	                return reader.readLine();
	            } catch (IOException e) {
	                throw new RuntimeException(e);
	            }
	        }

	        return tokenizer.nextToken("\n");
	    }

	    public long nextLong() {
	        return Long.parseLong(next());
	    }

	    public int nextInt() {
	        return Integer.parseInt(next());
	    }

	    public double nextDouble() {
	         return Double.parseDouble(next());
	     }

	    public int[] nextIntArray(int n) {
	        int[] a = new int[n];
	        for (int i = 0; i < n; i++)
	            a[i] = nextInt();
	        return a;
	    }

	    public long[] nextLongArray(int n) {
	        long[] a = new long[n];
	        for (int i = 0; i < n; i++)
	            a[i] = nextLong();
	        return a;
	    }

	}


}
//  [java]
import java.io.IOException;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.io.PrintWriter;

@SuppressWarnings("unchecked")
public class Main {
    static boolean f(String s, int tmp, char[] a) {
        int start = tmp - a.length;
        int end = tmp;

        boolean flg = true;

        int idx = 0;

        for (int i = start; i < end; i++) {
            if (start < 0) break;
            if (s.charAt(i) != a[idx]) {
                flg = false;
                break;
            }
            idx++;
        }

        return flg;
    }

    public static void main(String[] args) throws IOException {
        final String YES = "YES";
        final String NO = "NO";

        final char dream[] = {'d','r','e','a','m'};
        final char dreamer[] = {'d','r','e','a','m','e','r'};
        final char erase[] = {'e', 'r', 'a', 's', 'e'};
        final char eraser[] = {'e','r','a','s','e','r'};

        String s;

        try (
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(System.in))) {
            s = reader.readLine();
        }

        PrintWriter out = new PrintWriter(System.out);

        boolean flg = false;

        int tmp = s.length();

        while (0 < tmp) {
            boolean result = false;

            flg = f(s, tmp, dream);
            result = result | flg;
            if (flg) {
                tmp -= dream.length;
                if (tmp == 0) break;
            }

            flg = f(s, tmp, dreamer);
            result = result | flg;
            if (flg) {
                tmp -= dreamer.length;
                if (tmp == 0) break;
            }

            flg = f(s, tmp, erase);
            result = result | flg;
            if (flg) {
                tmp -= erase.length;
                if (tmp == 0) break;
            }

            flg = f(s, tmp, eraser);
            result = result | flg;
            if (flg) {
                tmp -= eraser.length;
                if (tmp == 0) break;
            }

            if (!result) break;
        }

        out.println(flg ? YES : NO);

        out.flush();
    }
}
//  [java]
import java.util.*;
public class Main {

 public static void main(String[] args) {
  Scanner no=new Scanner(System.in);
  String s=no.next();
  int y=s.length()-1;
  int i=y;
  for(i=y;i>=0;i--){
    if(s.charAt(i)=='m'){
      if(i-4<0){
        System.out.println("NO");
      }
      else{
       String r=s.substring(i-4,i+1);
       if(r.equals("dream")){
        i=i-4;
       }
       else{
        System.out.println("NO");
        break;
       }
      }
    }
    else if(s.charAt(i)=='e'){
     if(i-4<0){
       System.out.println("NO");
     }
     else{
      String r=s.substring(i-4,i+1);
      if(r.equals("erase")){
        i=i-4;
      }
     }
    }
    else if(s.charAt(i)=='r'){
     boolean t=false;
     boolean t1=false;
     String r="";
     String r1="";
     if(i-6>0){
      r=s.substring(i-6,i+1);
      t=true;
     }
     if(i-5>0){
      r1=s.substring(i-5,i+1);
      t1=true;
     }
      if(t==true&&r.equals("dreamer")){
        i=i-6;
      }
      else if(t1==true&&r1.equals("eraser")){
        i=i-5;
      }
      else{
        System.out.println("NO");
        break;
      }
    }
    else{
      System.out.println("NO");
      break;
    }
  }
  //System.out.println(i);
  if(i==-1){
    System.out.println("YES");
  }
 }

}
//  [java]
import java.util.*;
public class Main {

 public static void main(String[] args) {
  Scanner no=new Scanner(System.in);
  String s=no.next();
  int y=s.length()-1;
  int i=y;
  for(i=y;i>=0;i--){
    if(s.charAt(i)=='m'){
      String r=s.substring(i-4,i+1);
      if(r.equals("dream")){
        i=i-4;
      }
      else{
        System.out.println("NO");
        break;
      }
    }
    else if(s.charAt(i)=='e'){
      String r=s.substring(i-4,i+1);
      if(r.equals("erase")){
        i=i-4;
      }
    }
    else if(s.charAt(i)=='r'){
      String r=s.substring(i-6,i+1);
      String r1=s.substring(i-5,i+1);
      if(r.equals("dreamer")){
        i=i-6;
      }
      else if(r1.equals("eraser")){
        i=i-5;
      }
      else{
        System.out.println("NO");
        break;
      }
    }
    else{
      System.out.println("NO");
      break;
    }
  }
  //System.out.println(i);
  if(i==-1){
    System.out.println("YES");
  }
 }

}
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
	
	String dream = "dream";
	String dreamer = "dreamer";
	String erase = "erase";
	String eraser = "eraser";

	public static void main(String[] args) throws IOException {
		Main mainObj = new Main();
		mainObj.solve();
	}

	public void solve() throws IOException {
		FastScanner fs = new FastScanner();
		
		String s = fs.next();
		
		int index = 0;
		boolean yes = true;
		
		while(index < s.length()) {
			int retIndex;
			if(s.charAt(index) == 'e') {
				retIndex = checkStrOrStrer(s, index, erase);
				if(retIndex == -1) {
					yes = false;
					break;
				}
				index = retIndex;
			}else if(s.charAt(index) == 'd') {
				retIndex = checkStrOrStrer(s, index, dream);
				if(retIndex == -1) {
					yes = false;
					break;
				}
				index = retIndex;
			}else {
				yes = false;
				break;
			}
				
			
		}
		
		if(yes) {
			System.out.println("YES");
		}else {
			System.out.println("NO");
		}
	}
	
	
	int checkStrOrStrer(String s, int index, String checkString) {
		
		int beforeIndex = 0;
		for(; beforeIndex < checkString.length() && beforeIndex + index < s.length(); beforeIndex++) {
			if(s.charAt(index + beforeIndex) != checkString.charAt(beforeIndex)) {
				return -1;
			}
		}
		
		if(beforeIndex < checkString.length()) {
			return -1;
		}
		
		int afterIndex = 0;
		for(; afterIndex < 3 && index + checkString.length() + afterIndex < s.length(); afterIndex++) {
			if(s.charAt(index + checkString.length() + afterIndex) != eraser.charAt(afterIndex)) {
				break;
			}
		}
		
		if(afterIndex == 2) {
			return index + checkString.length()+2;
		}else {
			return index +checkString.length() ;
		}
	}

	

	public class FastScanner {

		BufferedReader reader;
		private StringTokenizer st;

		public FastScanner() {
			st = null;
			reader = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() throws IOException {
			if (st == null || !st.hasMoreElements()) {
				st = new StringTokenizer(reader.readLine());
			}
			return st.nextToken();
		}

		public String nextLine() throws IOException {
			st = null;
			String readLine = null;
			readLine = reader.readLine();
			return readLine;
		}

		public int nextInt() throws NumberFormatException, IOException {
			return Integer.parseInt(next());
		}

		public long nextLong() throws NumberFormatException, IOException {
			return Long.parseLong(next());
		}

		public int[] nextIntArr(int n) throws NumberFormatException, IOException {
			int[] retArr = new int[n];
			for (int i = 0; i < n; i++) {
				retArr[i] = nextInt();
			}
			return retArr;
		}

		public long[] nextLongArr(int n) throws NumberFormatException, IOException {
			long[] retArr = new long[n];
			for (int i = 0; i < n; i++) {
				retArr[i] = nextLong();
			}
			return retArr;
		}

		public void close() throws IOException {
			reader.close();
		}
	}

}
//  [cpp]
#include <stdio.h>
#include <string.h>

int main(void)
{
    char S[100001],T[100001]={};
    char *Tc[4]={"dream","dreamer","erase","eraser"}; //Tに入る要素
    int Tclen[4]={5,7,5,6};
    int Slen,count=0,Tlen=0; 

    scanf("%s",S);
    //printf("%s\n",S);
    Slen = strlen(S);

    //for(int i=0;i<4;i++)printf("Tc[%d] = %s\n",i,Tc[i]);

    while(Slen>0){
        count=0;
        for(int i=0;i<4;i++){
            //printf("%s\n",Tc[i]);
            if(strncmp(Tc[i],S+Slen-Tclen[i],Tclen[i])==0){Slen -= Tclen[i];/*printf("%d\n",Slen);*/break;}
            count++;
        }
        if(count ==4)break;
    }
    
    if(Slen==0){
		printf("YES\n");
	}else if(Slen!=0){
		printf("NO\n");
	}
    return 0;

}
//  [cpp]
#include <cstdio>
#include <cstring>

bool dp[100000 + 10];
char s[100000 + 10];

int main()
{
	scanf("%s", s);
	dp[0] = true;

	for (int i = 0; i < strlen(s); ++i)
	{
		if (dp[i] == false) continue;

		if (memcmp(s + i, "dream", 5) == 0)
		{
			dp[i + 5] = true;
			if (s[i + 5] == 'e' && s[i + 6] == 'r')
			{
				dp[i + 7] = true;
			}
		}
		else if (memcmp(s + i, "erase", 5) == 0)
		{
			dp[i + 5] = true;
			if (s[i + 5] == 'r')
			{
				dp[i + 6] = true;
			}
		}
	}

	printf(dp[strlen(s)] ? "YES\n" : "NO\n");

	return 0;
}
//  [cpp]
#include<cstdio>
#include<cstring>
char s[100001];
int main()
{
	scanf("%s",s+1);
	int r=strlen(s+1);
	while(r>=1){
		if(s[r]=='r'&&s[r-1]=='e'&&s[r-2]=='m'&&s[r-3]=='a'&&s[r-4]=='e'&&s[r-5]=='r'&&s[r-6]=='d'){
			r-=7;
		}else if(s[r]=='m'&&s[r-1]=='a'&&s[r-2]=='e'&&s[r-3]=='r'&&s[r-4]=='d'){
			r-=5;
		}else if(s[r]=='e'&&s[r-1]=='s'&&s[r-2]=='a'&&s[r-3]=='r'&&s[r-4]=='e'){
			r-=5;
		}else if(s[r]=='r'&&s[r-1]=='e'&&s[r-2]=='s'&&s[r-3]=='a'&&s[r-4]=='r'&&s[r-5]=='e'){
			r-=6;
		}else{
			break;
		}
	}
	printf("%s\n",r<=0?"YES":"NO");
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
#define M_PI           3.14159265358979323846  /* pi */
using namespace std;
using  ll = long long;

vector<string>A = { "dream", "dreamer", "erase", "eraser" };

int main() {
    string s;
    cin >> s;

    reverse(s.begin(), s.end());
 

    for (int i = 0; i < 4; i++) {
        reverse(A.at(i).begin(), A.at(i).end());

    }

    bool result = true;

    for (int i = 0; i < s.size(); i++) {
        bool divide = false;
        for (int j = 0; j < 4; j++) {
            string X = A.at(j);
            if (s.substr(i, X.size()) == X) {
                divide = true;
                i += X.size();
            }

        }
        if (divide == false) {
            result = false;
            break;

        }
    }

    if (result == true) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }


}
//  [cpp]
#include <bits/stdc++.h>
#define M_PI           3.14159265358979323846  /* pi */
using namespace std;
using  ll = long long;

vector<string>A = { "dream", "dreamer", "erase", "eraser" };

int main() {
    string s;
    cin >> s;

    reverse(s.begin(), s.end());
 

    for (int i = 0; i < 4; i++) {
        reverse(A.at(i).begin(), A.at(i).end());

    }

    bool result = true;

    for (int i = 0; i < s.size(); i++) {
        bool divide = false;
        for (int j = 0; j < 4; j++) {
            string X = A.at(j);
            if (s.substr(i, X.size()) == X) {
                divide = true;
                i += X.size();
            }

        }
        if (divide == false) {
            result = false;
            break;

        }
    }

    if (result == true) {
        cout << "Yes" << endl;
    }
    else {
        cout << "No" << endl;
    }


}
//  [cpp]
#include <bits/stdc++.h>
#define M_PI           3.14159265358979323846  /* pi */
using namespace std;
using  ll = long long;

int main() {
	string s;
	cin >> s;

	reverse(s.begin(), s.end());
	vector<string>A = { "dream", "dreamer", "erase", "eraser" };

	for (int i = 0; i < 4; i++) reverse(A.at(i).begin(), A.at(i).end());

	bool result = true;

	for (int i = 0; i < s.size(); i++) {
		bool divide = false;
		for (int j = 0; j < 4; j++) {
			string X = A.at(i);
			if (s.substr(i, X.size()) == X) {
				divide = true;
				i += X.size();
			}

		}
		if (divide == false) {
			result = false;
			break;
		}
	}

	if (result == true) {
		cout << "Yes" << endl;
	}
	else {
		cout << "No" << endl;
	}

		
}
//  [c]
#include <stdio.h>
#include <string.h>
int main(){
  char s[100001];
  int f=0;
  scanf("%s",&s);
  for(int i=strlen(s)-1;i>0;i--){
    if(s[i]=='m'){//dream
      if(s[i--]=='m'&&s[i--]=='a'&&s[i--]=='e'&&s[i--]=='r'&&s[i]=='d')f=1;  
      else f=0;
     }
    else if(s[i]=='e'){//erase
      if(s[i--]=='e'&&s[i--]=='s'&&s[i--]=='a'&&s[i--]=='r'&&s[i]=='e')f=1; 
      else f=0;
     }
    else if(s[i]=='r'&&s[i-5]=='e'){//eraser 
      if(s[i--]=='r'&&s[i--]=='e'&&s[i--]=='s'&&s[i--]=='a'&&s[i--]=='r'&&s[i]=='e') f=1;
      else f=0;
      }
    else if(s[i]=='r'&&s[i-6]=='d'){//dreamer
      if(s[i--]=='r'&&s[i--]=='e'&&s[i--]=='m'&&s[i--]=='a'&&s[i--]=='e'&&s[i--]=='r'&&s[i]=='d') f=1;
      else f=0;
      }
    if(f==0) break;
  }
 if(f==1) printf("YES\n");
 else printf("NO\n");
 return 0;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>

typedef long long ll;

int main(){
  char key1[6] = "maerd";
  char key2[8] = "remaerd";
  char key3[6] = "esare";
  char key4[7] = "resare";
  char s[100007];
  int n,i,j,flag;
  char t;

  scanf("%s", s);

  n = strlen(s);
  for(i = 0,j = n - 1;i < n/2;i++,j--){
    t = s[i]; s[i] = s[j]; s[j] = t;
  }

  i = 0; flag = 0;
  while(s[i] != '\0'){
    if(s[i] == 'm'){
      if(strncmp(s + i,key1,5) != 0){
        flag = 1;
        break;
      }

      else i = i + 5;
    }

    else if(s[i] == 'e'){
      if(strncmp(s + i,key3,5) != 0){
        flag = 1;
        break;
      }

      else i = i + 5;
    }

    else if(s[i] == 'r'){
      if(s[i + 2] == 'm'){
        if(strncmp(s + i,key2,7) != 0){
          flag = 1;
          break;
        }

        else i = i + 7;
      }

      else if(s[i + 2] == 's'){
        if(strncmp(s + i,key4,6) != 0){
          flag = 1;
          break;
        }

        else i = i + 6;
      }

      else{
        flag = 1;
        break;
      }
    }

    else{
      flag = 1;
      break;
    }
  }

  if(flag) printf("NO\n");

  else printf("YES\n");

  return 0;
}
//  [c]
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
int main() {
	char s[100001], tmp;
	char dream[6] = "maerd";
	char dreamer[8] = "remaerd";
	char erase[6] = "esare";
	char eraser[7] = "resare";
	bool isDream, isDreamer, isErase, isEraser;
	scanf("%s", s);
	int len = strlen(s);
	for (int i = 0; i < len / 2; i++) {
		tmp = s[i];
		s[i] = s[len - i - 1];
		s[len - i - 1] = tmp;
	}
	for (int i = 0; i < len;) {
		isDream = isDreamer = isErase = isEraser = true;
		for (int j = 0; j < 5; j++) {
			if (s[i + j] != dream[j]) {
				isDream = false;
				break;
			}
		}
		for (int j = 0; j < 7; j++) {
			if (s[i + j] != dreamer[j]) {
				isDreamer = false;
				break;
			}
		}
		for (int j = 0; j < 5; j++) {
			if (s[i + j] != erase[j]) {
				isErase = false;
				break;
			}
		}
		for (int j = 0; j < 6; j++) {
			if (s[i + j] != eraser[j]) {
				isEraser = false;
				break;
			}
		}
		if (isDream || isErase) {
			i += 5;
		} else if (isEraser) {
			i += 6;
		} else if (isDreamer) {
			i += 7;
		} else {
			printf("NO\n");
			return 0;
		}
	}
	printf("YES\n");
	return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
int main(void){
  char s[100000];
  char t[100000]; // maerd , remaerd , esare , resare 
  int s_length,i;
  scanf("%s",s);
  s_length = strlen(s);
  for(i=s_length-1;i>=0;i--){
    if(s[i]=='m'){
      t[i]='m'; t[i-1]='a'; t[i-2]='e'; t[i-3]='r'; t[i-4]='d';
      i=i-4;
    }else if(s[i]=='e'){
      t[i]='e'; t[i-1]='s'; t[i-2]='a'; t[i-3]='r'; t[i-4]='e';
      i=i-4;
    }else if(s[i-2]=='m'){
      t[i]='r'; t[i-1]='e'; t[i-2]='m'; t[i-3]='a'; t[i-4]='e';
      t[i-5]='r'; t[i-6]='d';
      i=i-6;
    }else if(s[i-2]=='s'){
      t[i]='r'; t[i-1]='e'; t[i-2]='s'; t[i-3]='a'; t[i-4]='r'; t[i-5]='e';
      i=i-5;
    }
  }
    if(strcmp(s,t)==0 && i==-1){
      printf("YES\n");
    }else{
      printf("NO\n");
    }

  return 0;
}