jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]

import java.util.*;

public class Main {

	public static int i_max;
	public static int j_max;
	public static int field[][];
	public static boolean nurui[];
	public static boolean nuruj[];

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		i_max = Integer.parseInt(sc.next());
		j_max = Integer.parseInt(sc.next());
		int k = Integer.parseInt(sc.next());

		field = new int[i_max][j_max];
		for (int i = 0; i < i_max; i++) {
			String s = sc.next();
			for (int j = 0; j < j_max; j++) {
				field[i][j] = (s.charAt(j) == '.') ? 0 : 1;
			}
		}

		nurui = new boolean[i_max];
		nuruj = new boolean[j_max];
		int answer = 0;

		for (int i = 0; i < (int) Math.pow(2, i_max); i++) {
			for (int j = 0; j < (int) Math.pow(2, j_max); j++) {

				// 塗りパターンを作る
				String bin_i = String.format("%0" + i_max + "d",
						Integer.valueOf(Integer.toBinaryString(i)));
				String bin_j = String.format("%0" + j_max + "d",
						Integer.valueOf(Integer.toBinaryString(j)));
				for (int p = 0; p < i_max; p++) {
					nurui[p] = (bin_i.charAt(p) == '0') ? false : true;
				}
				for (int p = 0; p < j_max; p++) {
					nuruj[p] = (bin_j.charAt(p) == '0') ? false : true;
				}

				// このパターンで塗ったときの黒マス数は、目標 k と一致するか？
				if (countBlack() == k) {
					answer++;
//					System.out.println(Arrays.toString(nurui));
//					System.out.println(Arrays.toString(nuruj));
//					System.out.println("");
				}

			}
		}

		// 出力
		System.out.println(answer);
		
	}

	// 現在のnurui, nurujで塗ったときの黒マス数
	private static int countBlack() {

		int result = 0;

		for (int i = 0; i < i_max; i++) {
			for (int j = 0; j < j_max; j++) {
				if (!nurui[i] && !nuruj[j] && field[i][j] == 1) {
					result++;
				}
			}
		}
		return result;

	}
}
//  [java]

import java.util.Scanner;

public class Main {

	static Scanner scanner;

	static int h;
	static int w;
	static int k;
	static String[][] S;
	public static void main(String[] args) {
	    scanner = new Scanner(System.in);

	    h=gi();
	    w=gi();
	    k=gi();
	    S = new String[h][w];

	    for (int i=0; i<h;i++) {
	    	String s=gs();
	    	for (int j=0; j<w; j++) {
	    		S[i][j]=String.valueOf(s.charAt(j));

	    	}
	    }
	    int c=0;
	    for (int i=0; i<Math.pow(2, h+w);i++) {
	    	int ik=f(i);
	    	if (ik==k) {
	    		c++;
	    	}
	    }



	    System.out.println(c);

//	    if (isNumber(s1) && isNumber(s2) && s.charAt(a) == '-') {
//	    	System.out.print("Yes");
//	    }else {
//	    	System.out.print("No");
//	    }



	}

	public static int f(int n) {
		int c=0;
		String t=String.format("%0"+ String.valueOf(h+w) + "d", Long.parseLong(two(n)));
		for (int i=0; i<h;i++) {
			char inh = t.charAt(i);
			if (inh=='1') {
				continue;
			}
	    	for (int j=0; j<w; j++) {
	    		char inw = t.charAt(h+j);
	    		if (inw=='1') continue;
	    		if (S[i][j].equals("#")) c++;
	    	}
	    }
		return c;
	}

	public static String two(int n) {
		StringBuilder sb = new StringBuilder();
		if(n==0) return "0";
		while(n>0) {
			int k=n%2;
			sb.insert(0, k);
			if (k==0) {
				n=n/2;
			} else {
				n= (n-1) /2;
			}
		}

		return sb.toString();
	}

	public static long d(long n) {
		String a=String.valueOf(n);
		return (long)a.length();
	}

	// 文字列として入力を取得
	public static String gs() {
		return scanner.next();
	}

	// intとして入力を取得
	public static int gi() {
		return Integer.parseInt(scanner.next());
	}

	// longとして入力を取得
	public static long gl() {
		return Long.parseLong(scanner.next());
	}

	// doubleとして入力を取得
	public static double gd() {
		return Double.parseDouble(scanner.next());
	}
}
//  [cpp]
#include <bits/stdc++.h>
#define rep(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
using namespace std;
using ll = long long;
using d = double;

int main(){
  int h,w,k;
  cin >> h >> w >> k;
  vector<vector<char>> c(h, vector<char>(w));
  rep(i,h){
    rep(j,w){
      cin >> c.at(i).at(j);
    }
  }
  vector<vector<int>> y(10000,vector<int>(10000));
  rep(i,1<<h){
    rep(l,1<<w){
      int t=0;
      rep(j,h){
      // rep(m,w){
          rep(m,w){
            if(i>>j&1 && l>>m&1){
              if(c.at(j).at(m)=='#')++t;
            }
          }
      }
    y.at(i).at(l)=t;
    }
  }
  int z=0;
  rep(i,10000){
    rep(j,10000){
    if(y.at(i).at(j)==k)++z;
    }
  }
  cout << z << endl;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> P;

#define all(v) v.begin(), v.end()

const ll mod=1000000007;

ll countBits(ll in){
  int res=0;
  for(;in>0;in>>=1){
    if((in&0x01)!=0){
      res++;
    }
  }
  return res;
}

template<typename T>
void show2dVector(vector<vector<T>>& v){
  for(int i=0;i<v.size();i++){
    int m=v[i].size();
    cout<<i<<" : ";
    for(int j=0;i<m;i++){
      cout<<v[i][j]<<" ";
    }
    cout<<endl;
  }
}

void bfs(const vector<vector<int>>&g, int v, vector<bool>& seen){
  seen[v]=true;
  cout<<v<<" ";
  for(auto next: g[v]){
    if(seen[next]){
      continue;
    }
    bfs(g,next,seen);
  }
}

bool dfs(vector<vector<int>> &g,int start,int goal,vector<bool>&seen){
  bool res=false;
  seen[start]=true;
  if(start==goal){
    return true;
  }
  for(auto next: g[start]){
    if(seen[next]){
      continue;
    }
    res=dfs(g,next,goal,seen);
    if(res){
      break;
    }
  }
  return res;
}

ll gcd(ll a,ll b) {
  return b? gcd(b,a%b): a;  
}
ll lcm(ll a,ll b) {
  return a*b/gcd(a,b);
}
bool isLowerCase(char c){
  return (c>='a'&&c<='z');
}

ll powm(ll a,ll n, ll m){
  ll ret=1;
  while(n>0){
    if(n%2==1){
      ret=(ret*a)%m;
    }
    n>>=1;
    a=(a*a)%m;
  }
  return ret;
}

const string yesno(bool ans){
  return (ans?"Yes":"No");
}
int main() {
  int h,w,k;cin>>h>>w>>k;
  vector<string> m(h);
  for(int i=0;i<h;i++){
    cin>>m[i];
  }
  int ans=0;
  for(int path=0;path<(1<<h);path++){
    for(int patw=0;patw<(1<<w);patw++){
      int cnt=0;
      cerr<<"H : "<<path<<", W : "<<patw<<endl;
      for(int i=0;i<h;i++){
        for(int j=0;j<w;j++){
          if(((path&(1<<i))!=0)||((patw&(1<<j))!=0)){
            continue;
          }
          if(m[i][j]=='#'){
            cerr<<i<<" ,"<<j<<endl;
            cnt++;
          }
        }
        cerr<<endl;
      }
      if(cnt==k){
        ans++;
      }
    }
  }
  cout<<ans<<endl;
  return 0;
}
//  [c]
#include<stdio.h>
int main(){
  int h,w,i,j,k,l,ans=0,n,c;
  char s[10][10];
  scanf("%d %d %d",&h,&w,&n);
  for(i=0;i<h;i++)scanf("%s",s[i]);
  for(i=0;i<(1<<h);i++){
    for(j=0;j<(1<<w);j++){
      c=0;
      for(k=0;k<h;k++){
	if(i&(1<<k))continue;
	for(l=0;l<w;l++){
	  if(j&(1<<l))continue;
	  if(s[k][l]=='#')c++;
	}
      }
      if(c==n)ans++;
    }
  }
  printf("%d\n",ans);
  return 0;
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>

int W_Length(char *str){
	int length = 0;
	while(*str++ != '\0')
		length++;
	return length;
}

void swap(int *a, int *b){
  int temp;
  temp=*a;
  *a=*b;
  *b=temp;
}
//swap(&a, &b)

double deg(double theta){//deg to theta
return theta*(2*3.14159265359)/360;
}

int cmp( const void *p, const void *q ) {
    return *(int*)p - *(int*)q;
}//ちいさい順
//qsort(a,n,sizeof(int),cmp);
//char s[n][11]

int cmp_s(const void * left, const void * right)
{
	char *left_char = (char *)left;
  char *right_char = (char *)right;
  return strcmp(left_char, right_char);
}
//qsort(s,n,sizeof(s[0]),cmp_s);


int main (void)
{
	int a[7][7],b[7][7],c[7],d[7],e,f,g,n,i,h,w,k,j,l,count,coun=0,temp1,temp2;
  char s[8];

scanf("%d%d%d",&h,&w,&k);
	for(i=0;i<h;i++){
        scanf("%s",s);
        for(l=0;l<w;l++){
          //printf("%c\n",s[l]);
        if(s[l]=='#'){
        a[i][l]=1;//黒が1
          b[i][l]=1;
        }
  else{
  a[i][l]=0;
    b[i][l]=0;
  }
      }
	}
  

  for(c[0]=0;c[0]<2;c[0]++){for(c[1]=0;c[1]<2;c[1]++){for(c[2]=0;c[2]<2;c[2]++){for(c[3]=0;c[3]<2;c[3]++){for(c[4]=0;c[4]<2;c[4]++){for(c[5]=0;c[5]<2;c[5]++){for(c[6]=0;c[6]<2;c[6]++){for(d[0]=0;d[0]<2;d[0]++){for(d[1]=0;d[1]<2;d[1]++){for(d[2]=0;d[2]<2;d[2]++){for(d[3]=0;d[3]<2;d[3]++){for(d[4]=0;d[4]<2;d[4]++){for(d[5]=0;d[5]<2;d[5]++){for(d[6]=0;d[6]<2;d[6]++){
 count=0;
    temp1=0;
    temp2=0;
    for(i=h;i<7;i++){
    temp1+=c[i];
    }
    for(j=w;j<7;j++){
    temp2+=d[j];
    }
    
    if(temp1>0||temp2>0){
    break;
    }
    
    for(i=0;i<h;i++){
    for(j=0;j<w;j++){
      
  if(d[j]==1||c[i]==1){
    b[i][j]=2;
  }  
    }
  }
    
    
    for(i=0;i<h;i++){
    for(j=0;j<w;j++){
    if(b[i][j]==1){
    count++;
    }
      
      b[i][j]=a[i][j];
    }
    }
    
    if(count==k){
    coun++;
          }

  
    
    
    
  
  }}}}}}}}}}}}}}
    
    
  
  printf("%d",coun);
return 0;

}
//  [c]
#include <stdio.h>

int main() {
    int i, j, H, W, K, black, ans, biti, bitj;
    black = ans = 0;

    scanf("%d %d %d", &H, &W, &K);

    char buf, c[H][W];

    for (i = 0; i < H; i++) {
        scanf("%c", &buf);

        for (j = 0; j < W; j++) {
            scanf("%c", &buf);
            c[i][j] = buf;
        }
    }

    for(biti=0; biti < (1 << H); biti++) {
        for(bitj=0; bitj < (1 << W); bitj++) {
            black = 0;

            for(i=0; i < H; i++) {
                for(j=0; j < W; j++) {
                    if((c[i][j] == '#') && !((biti >> i) & 1) && !((bitj >> j) & 1)) {
                        black++;
                    }
                }
            }
            if(black == K) ans++;
        }
    }

    printf("%d\n", ans);
    return 0;
}
//  [javascript]

function main(input = "") {
    const lines = input.split("\n");
    const arr = lines[0].split(" ").map((v) => (0 | v));
    const H = arr[0], W = arr[1], K = arr[2];
    const GRID = lines.slice(1).join("").split("").map((v) => (v === "#" ? 1 : 0));

    let res = 0;
    for (let i = 0; i < 2 ** H; i++) {
        for (let k = 0; k < 2 ** W; k++) {
            let grid = GRID.slice();
            for (let r = 0; r < H; r++) {
                if (i & (1 << r)) {
                    for (let ir = 0; ir < W; ir++) {
                        grid[ir + r * W] = 0;
                    }
                }
            }
            for (let c = 0; c < W; c++) {
                if (k & (1 << c)) {
                    for (let ic = c; ic < grid.length; ic += W) {
                        grid[ic] = 0;
                    }
                }
            }
            let cnt = grid.reduce((p,c)=>(p+c));
            if(cnt === K){
                res++;
            }
        }
    }
    return res;
}

//******************************
exports.main = main;

function Main(input) {
    console.log(main(input.trim()));
}

if (process.argv[2] !== "test") {
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var H = parseInt(input[0].split(" ")[0]);
  var W = parseInt(input[0].split(" ")[1]);
  var K = parseInt(input[0].split(" ")[2]);
  input.shift();
  var c = input.map(i => i.split(""));
  var ans =0;
  c.splice(H,c.length);
  var maph = new Array([0],[1]);
  for(var i=0;i<H-1;i++){
    var mapsub = new Array(0);
    for(var j=0;j<maph.length;j++){
      var zero =[...maph[j]];
      var one =[...maph[j]];
      zero.push(0);
      one.push(1);
      mapsub.push(zero);
      mapsub.push(one);
    }
    maph=mapsub;
  }
  var mapw = new Array([0],[1]);
  for(var i=0;i<W-1;i++){
    var mapsub = new Array(0);
    for(var j=0;j<mapw.length;j++){
      var zero =[...mapw[j]];
      var one =[...mapw[j]];
      zero.push(0);
      one.push(1);
      mapsub.push(zero);
      mapsub.push(one);
    }
    mapw=mapsub;
  }
  var blacks=0;
  for(var i=0;i<maph.length;i++){
    for(var j=0;j<mapw.length;j++){
      for(var k=0;k<H;k++){
        for(var l=0;l<W;l++){
          if(maph[i][k]==0&&mapw[j][l]==0&&c[k][l]=="#"){
            blacks++;
          }
        }
      }
      if(blacks==K){
        ans++;
      }
      blacks=0;
    }
  }

  console.log('%s', ans);
  return ans;
}

function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict';
const fs = require('fs');
const mod = BigInt(1e9+7);


class ABC041 {
  static A(input) {
    var s, i
    input = input.trim().split('\n');
    [s, i] = input;
    i = parseInt(i, 10);
    console.log(s[i-1]);
  }
  static B(input) {
    var a, b, c;
    input = input.trim().split(' ').map(BigInt);
    [a, b, c] = input;
    var ans = a * b % mod * c % mod;
    ans = Number(ans);
    console.log(ans);
  }
  static C(input) {
    var [n, height] = input.trim().split('\n');
    height = height.split(' ').map(n => parseInt(n, 10));
    n = parseInt(n, 10);
    var height = Object.keys(height).map(key => [parseInt(key, 10)+1, height[key]]);
    height.sort(function(first, second) {
      return (second[1] - first[1]);
    });
    for (var [i, _] of height) {console.log(i);}
  }
  static D(input) {
    var lines = input.trim().split('\n');
    var [n, m] = lines[0].split(' ').map(x => +x);
    var edges = new Array(n).fill(0);
    for (var i = 0; i < m; i++) {
      var [x, y] = lines[1+i].split(' ').map(x => +x);
      edges[x-1] |= 1<<(y-1);
    }
    var comb = new Array(1<<n).fill(null); comb[0] = 1;
    function count(edges, bit) {
      if (comb[bit] != null) {return comb[bit];}
      comb[bit] = 0;
      for (var i = 0; i < n; i++) {
        if (bit>>i&1 && !edges[i]) {
          var nxt_bit = bit & ~(1<<i);
          var nxt_edges = edges.slice();
          for (var j = 0; j < n; j++) {
            nxt_edges[j] &= ~(1<<i);
          }
          comb[bit] += count(nxt_edges, nxt_bit);
        }
      }
      return comb[bit];
    }
    console.log(count(edges, (1<<n)-1));
  }
}

class ABC173 {
  static A(input) {
    var n = +input.trim();
    console.log(Math.floor((n+999)/1000)*1000 - n);
  }
  static B(input) {
    var lines = input.trim().split('\n');
    var n = +lines[0];
    var cnt = {
      'AC': 0,
      'WA': 0,
      'TLE': 0,
      'RE': 0
    }
    for (var i = 0; i < n; i++) {
      cnt[lines[1+i]]++;
    }
    for (var [verd, c] of Object.entries(cnt)) {
      console.log(`${verd} x ${c}`);
    }
  }
  static C(input) {
    var lines = input.trim().split('\n');
    var [h, w, k] = lines[0].split(' ').map(x => +x);
    var c = lines.slice(1);
    var tot = 0;
    for (var i = 0; i < (1<<h); i++) {
      for (var j = 0; j < (1<<w); j++) {
        var cnt = 0;
        for (var y = 0; y < h; y++) {
          for (var x = 0; x < w; x++) {
            cnt += c[y][x]=='#' && ~i>>y&1 && ~j>>x&1;
          }
        }
        tot += cnt == k;
      }
    }
    console.log(tot);
  }
  static D(input) {
  }
  static E(input) {
  }
  static F(input) {
  }
}


var input = fs.readFileSync('/dev/stdin', 'utf8');
ABC173.C(input);
//  [go]
package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 1000000
)

var sc *bufio.Scanner

func initScanner(r io.Reader) *bufio.Scanner {
	buf := make([]byte, initialBufSize)

	sc := bufio.NewScanner(r)
	sc.Buffer(buf, maxBufSize)
	sc.Split(bufio.ScanWords) // bufio.ScanLines
	return sc
}

func main() {
	sc = initScanner(os.Stdin)
	fmt.Println(resolve(parseProblem()))
}

func parseProblem() (h, w, k int, g [][]int) {
	h, w, k = scanInt(sc), scanInt(sc), scanInt(sc)
	g = nextGrid(h, w)
	return
}

const (
	white = 0 + iota
	black
	red
)

func nextGrid(h, w int) [][]int {
	grid := make([][]int, h)
	for i := 0; i < h; i++ {
		grid[i] = make([]int, w)
		str := scanString(sc)
		for j := 0; j < w; j++ {
			switch str[j] {
			case '.':
				grid[i][j] = white
			case '#':
				grid[i][j] = black
			}
		}
	}
	return grid
}

func resolve(h, w, k int, g [][]int) int {
	num := 0
	for i := 0; i < 1<<uint(h); i++ {
		for j := 0; j < 1<<uint(w); j++ {
			if fullfill(g, uint(i), uint(j), k) {
				num++
			}
		}
	}
	return num
}

func fullfill(g [][]int, xFilter, yFilter uint, k int) bool {
	h := len(g)
	if h == 0 {
		return k == 0
	}
	w := len(g[0])
	num := 0
	for i := range loop0(h) {
		if xFilter&(1<<uint(i)) != 0 {
			continue
		}
		for j := range loop0(w) {
			if yFilter&(1<<uint(j)) != 0 {
				continue
			}
			if g[i][j] == black {
				num++
			}
			if num > k {
				return false
			}
		}
	}
	return num == k
}

func loop0(n int) chan int {
	return loop(0, n-1, 1)
}

func loop1(n int) chan int {
	return loop(1, n, 1)
}

func loop(s, e, d int) chan int {
	ch := make(chan int)
	go func() {
		for i := s; i <= e; i += d {
			ch <- i
		}
		close(ch)
	}()
	return ch
}

// snip-scan-funcs
func scanInt(sc *bufio.Scanner) int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return int(i)
}
func scanString(sc *bufio.Scanner) string {
	sc.Scan()
	return sc.Text()
}
//  [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
	var ans int

	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] = s[k][0:m] + string('.') + s[k][m+1:len(s[k])]
						}
					}
				}
			}

			var count int
			for t := 0; t < H; t++ {
				for u := 0; u < W; u++ {
					if s[t][u] == '#' {
						count++
					}
				}
			}

			if count == K {
				ans++
			}
		}
	}

	fmt.Println(ans)
}
//  [ruby]
input = readlines()
h, w, k = input.shift.chomp.split("\s").map{|x| x.to_i}

cells = {}

input.each_with_index do |l, ih|
  l.chomp.split('').each_with_index do |color, iw|
    cells[ih + 1] = {} if cells[ih + 1].nil?
    cells[ih + 1][iw + 1] = color == '.' ? 'white' : 'black'
  end
end

h_list = []
w_list = []

def addNext(tmp, lim)
  res = []
  if tmp.length == 0
    (1..lim).each do |n|
      res.push([n])
    end
  else
    tmp.each do |t|
      (1..lim).each do |n|
        n_tmp = t.clone
        n_tmp.push(n)
        res.push(n_tmp)
      end
    end
  end

  res
end

(1..h).each do |n|
  h_list = addNext(h_list, h)
end

h_uniq = ['0']
h_list.each do |l|
  targets = l.uniq.sort.join(',')
  h_uniq.push(targets) unless h_uniq.include?(targets)
end

(1..w).each do |n|
  w_list = addNext(w_list, w)
end

w_uniq = ['0']
w_list.each do |l|
  targets = l.uniq.sort.join(',')
  w_uniq.push(targets) unless w_uniq.include?(targets)
end

cnt = 0
h_uniq.each do |hl|
  h_targets = hl.split(',').map{|x| x.to_i}
  w_uniq.each do |wl|
    w_targets = wl.split(',').map{|x| x.to_i}
    bk_cnt = 0
    (1..h).each do |h_idx|
      (1..w).each do |w_idx|
        next if h_targets.include?(h_idx)
        next if w_targets.include?(w_idx)
        bk_cnt += 1 if cells[h_idx][w_idx] == 'black'
      end
    end
    cnt += 1 if bk_cnt == k
  end
end

puts cnt
//  [ruby]
# 0と1で表せる。
# hの選び方, 0,0, 1,0 0,1 1,1
# wの選び方, 0,0,0, 0,0,1, 0,1,0, 1,0,0, 0,1,1, 1,0,1, 1,1,0, 1,1,1

h,w,k=gets.split.map &:to_i
c = h.times.map { gets.chomp.chars }
c2 = Marshal.load(Marshal.dump(c))
res=0
=begin
#ph = [*0..h]
#pw = [*0..w]
pc = [h,w].max
p c
h.times do |i|
  w.times do |j|
   c[i][j]
  end
end
=end
ch = [0,1].repeated_permutation(h).to_a
cw = [0,1].repeated_permutation(w).to_a

# 組み合わせを全て試す。
ch.each do |i|
  cw.each do |j|
    # 赤く塗る作業
    # indexメソッドだと全ての1を取得できない
    #h_paint_idx = i.index(1)
    #h_paint_idx = j.index(1)
    i.each_with_index do |ii, eii|
      j.each_with_index do |jj, ejj|
        #if i == [0, 0] && j == [0, 1, 1]
        #  puts "=========#{jj}==and===#{j.index(jj)}===" 
        #end
        if ii == 1
          w.times do |wj|
            c[eii][wj] = 'red'
          end
        elsif  jj == 1
          h.times do |hi|
            c[hi][ejj] = 'red'
          end
        end # if end
      end # j
    end # i
    res += 1 if c.flatten.count('#') == k
    #p res
    #p c
    #puts "i:#{i}, j:#{j}"
    c = Marshal.load(Marshal.dump(c2))
    #p "##ターン##"
  end # cw
end # ch

puts res
//  [ruby]
require 'matrix'

h, w, k = gets.split.map(&:to_i)
rows = Array.new(h){gets.chomp.chars.map{|c| (c == '#') ? 1 : 0}}
cnt = 0
[0, 1].repeated_permutation(h).each do |x|
  m = Matrix.rows(rows.dup.shift(h))
  x.each_with_index do |y, i|
    next if y == 0
    w.times do |j|
      m[i, j] = 0
    end
  end
  [0, 1].repeated_permutation(w) do |u|
    mc = m.dup
    u.each_with_index do |v, j|
      next if v == 0
      h.times do |i|
        mc[i, j] = 0
      end
    end
    cnt += 1 if mc.sum == k
  end
end
puts cnt
//  [rust]
use proconio::input;

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

    let mut ans = 0;

    for s in 0..1 << h {
        for sw in 0..1 << w {
            let mut black = 0;
            for i in 0..h {
                for j in 0..w {
                    let chars: Vec<char> = hw[i].chars().collect();
                    if s >> i & 1 == 0 && sw >> j & 1 == 0 && chars[j] == '#' {
                        black += 1;
                    }
                }
            }
            if black == k {
                ans += 1
            }
        }
    }
    println!("{}", ans);
}
//  [swift]
import Foundation

extension String {
    func wordsMap<T>(_ f: (Substring) -> T?) -> [T] {
        return self.split(separator: " ").compactMap(f)
    }
}

private func readWords<T>(_ f: (Substring) -> T?) -> [T] {
    return readLine()!.wordsMap(f)
}

extension Optional {
    func pleaseAC(){
        print(self!)
    }
}

readLine().map { line -> Any in 
    let hwk = line.wordsMap { Int($0) }
    let H = hwk[0]
    let W = hwk[1]
    let K = hwk[2]

    var count = 0
    let grid = (0..<H).map { _ -> [Character] in 
        let row = Array(readLine()!)
        count += row.filter { $0 == "#" }.count
        return row
    }

    var points = [[Int]]()
    for h in 0..<H {
        points.append([h, -1])
    }

    for w in 0..<W {
        points.append([-1, w])
    }

    var ans = 0
    if count == K {
        ans += 1
    }
    for i in 1...H+W {
        for comb in Combinations(points, i) {
            var tmp = 0
            let reds = Set(comb)
            for h in 0..<H {
                for w in 0..<W {
                    if reds.contains([h, -1]) || reds.contains([-1, w]) {
                        continue
                    }
                    if grid[h][w] == "#" {
                        tmp += 1
                    }
                }   
            }
            if tmp == K {
                ans += 1
            }
        }
        
    }
    return ans

}
.pleaseAC()

struct Combinations<Seq: Sequence>: Sequence, IteratorProtocol {
    let pool: [Seq.Element]
    let r: Int

    var indecies: [Int]
    var first = true

    init(_ seq: Seq, _ r: Int) {
        self.pool = [Seq.Element](seq)
        self.r = r
        self.indecies = [Int](0..<r)
    }

    mutating func next() -> [Seq.Element]? {
        let n = pool.count
        guard 0...n ~= r else { return nil }
        guard !first else {
            first = false
            return indecies.map { pool[$0] }
        }

        var i = r - 1
        while indecies[i] == i + n - r {
            if i > 0 {
                i -= 1
            } else {
                return nil
            }
        }

        indecies[i] += 1
        for j in i+1..<r {
            indecies[j] = indecies[j - 1] + 1
        }

        return indecies.map { pool[$0] }
    }
}
//  [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.map(([j]) => (css[i][j] === "Black" ? 1 : 0)).reduce((acc: number, x) => acc + x, 0)
                  )
                  .reduce((acc: number, x) => acc + x, 0) +
                  hPicks
                    .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) -
                  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 { 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 pickHFn = (n: number, picksH: [number, boolean][]): number => {
      const pickWFn = (picksH: [number, boolean][]): number => {
        const pickWFn = (n: number, picksW: [number, boolean][]): number =>
          n >= W
            ? (() => {
                const getBlackCnt = (picksH: [number, boolean][], picksW: [number, boolean][]): number =>
                  picksH
                    .filter(([, b]) => b)
                    .map(([i]) =>
                      picksW
                        .filter(([, b]) => b)
                        .map(([j]) => (css[i][j] === "Black" ? 1 : 0) as number)
                        .reduce((acc, x) => acc + x, 0)
                    )
                    .reduce((acc, x) => acc + x, 0);

                const cntH = getBlackCnt(
                  range(H).map((i) => [i, true]),
                  picksW
                );
                const cntW = getBlackCnt(
                  picksH,
                  range(W).map((j) => [j, true])
                );
                const cntHW = getBlackCnt(picksH, picksW);

                return initialBlackCnt - (cntH + cntW - cntHW);
              })() === K
              ? 1
              : 0
            : pickWFn(n + 1, picksW) +
              pickWFn(
                n + 1,
                picksW.map(([j, b]) => (j === n ? [j, true] : [j, b]))
              );

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

      return n >= H
        ? pickWFn(picksH)
        : pickHFn(n + 1, picksH) +
            pickHFn(
              n + 1,
              picksH.map(([i, b]) => (i === n ? [i, true] : [i, b]))
            );
    };

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

  console.log(cnt);
}
//  [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 -
                (() => {
                  const hCnt = hPicks
                    .filter(([, b]) => b)
                    .map(([i]) =>
                      range(W)
                        .map((j) => (css[i][j] === "Black" ? 1 : 0))
                        .reduce((acc: number, x) => acc + x, 0)
                    )
                    .reduce((acc: number, x) => acc + x, 0);

                  const wCnt = range(H)
                    .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);

                  const hwCnt = 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);

                  return hCnt + wCnt - hwCnt;
                })() ===
              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);
}
//  [python]
str = input()
words = ["dream", "dreamer", "erase", "eraser"]

def replace(S, s):
    reversedS = S[::-1]
    reverseds = s[::-1]
    replaced = reversedS.replace(reverseds, "", 1)
    return replaced[::-1]

while True:
    tmp = str
    for word in words:
        if str.endswith(word):
            str = replace(str, word)
            break
    if tmp == str:
        print("NO")
        break
    if str == "":
        print("YES")
        break
    tmp = str
//  [python]
S = input()
T = ['dream', 'dreamer', 'erase', 'eraser']
T = set([s[::-1] for s in T])

A = ''
for s in S[::-1]:
    A += s
    if A in T:
        A = ''
print('YES' if A == '' else 'NO')
//  [python]
def ABC67_B():
    N, K = LI()
    L = LI()
    L.sort(reverse=True)
    ans = sum(L[:K])
    print(ans)
    return

def ABC100_C():
    def factorization_2(n):
        arr = defaultdict(int)
        temp = n
        i = 2
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr[i] = cnt
        if temp != 1:
            arr[temp] = 1
        if arr == []:
            arr[n] = 1
        return arr[2]
    N = I()
    A = LI()
    ans = 0
    for a in A:
        ans += factorization_2(a)
    print(ans)
    return

def ARC68_C():
    X = I()
    ans = 0
    ans += 2*(X//11)
    rest = X%11
    if rest>0:
        ans += 1
    if rest>=7:
        ans += 1
    print(ans)
    return

def ABC49_C():
    S = SI()
    T = {"maerd","remaerd","esare","resare"}
    stack = ""
    for s in S[::-1]:
        stack += s
        if stack in T:
            stack = ""
    if stack:
        print("NO")
    else:
        print("YES")
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**6)

if __name__ == '__main__':
    ABC49_C()

"""

"""
//  [java]
import java.util.*;
class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    String s = sc.next();
    String[] words = new String[]{"dream","dreamer","erase","eraser"};
    int n = s.length();
    boolean[] dp = new boolean[n+1];
    dp[n] = true;
    for (int i = n-1; i >= 0; i--){
      for (String word: words){
        if (s.substring(i).startsWith(word)){
          dp[i] = dp[i] || dp[i+word.length()];
        }
      }
    }
    if (dp[0] == true){
      System.out.println("YES");
    }else{
      System.out.println("NO");
    }
  }
}
//  [java]
import java.util.*;
class Main{
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    String s = sc.next();
    int n = s.length();
    Map<Integer,Boolean> memo = new HashMap<>();
    String[] words = new String[]{"dream","dreamer","erase","eraser"};
    if (dp(0,s,memo,words) == true){
      System.out.println("YES");
    }else{
      System.out.println("NO");
    }

  }
  public static boolean dp(int i, String s, Map<Integer,Boolean> memo, String[] words){
    if (i == s.length()){return true;}
    if (!memo.containsKey(i)){
      boolean ans = false;
      for (String word: words){
        if (s.substring(i).startsWith(word) == true){
          ans = ans || dp(i + word.length(),s,memo,words);
        }
      }
      memo.put(i,ans);
    }
    return memo.get(i);
  }
}
//  [java]
import java.util.*;
import java.util.stream.*;

public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
        // programming
        String s = getInputString(sc);
        StringBuilder temp = new StringBuilder(s);
        boolean isFound = false;
        String[] words = {"dream","dreamer","erase","eraser"};
        int i = 0;

        l1: while (true) {
            i++;
            if (i % 100 == 0) {
                System.gc();
            }
            for (String w : words) {
                if (temp.toString().endsWith(w)) {
                    temp.delete(temp.length() - w.length(), temp.length());
                    if (temp.length() == 0) {
		                isFound = true;
		                break l1;
		            }
		            continue l1;
                }
            }
            break;
        }
        if (isFound) {
            output("YES");
        } else {
            output("NO");
        }
	}

	public static String getInputString(Scanner sc) {
		return sc.next();
	}

	public static int getInputInteger(Scanner sc) {
		return Integer.parseInt(sc.next());
	}

	public static void output(String... params) {
		boolean isInit = true;
		String str = "";
		for (String s : params) {
			if (!isInit) {
				str += " ";
			}
			str += s;
			isInit = false;
		}
		System.out.println(str);
	}

    public static int[] toIntegerList(String[] ss) {
        return Stream.of(ss).mapToInt(Integer::parseInt).toArray();
    }

    public static String[] toList(String s) {
        String[] ret = s.split("");
        return ret;
    }

    public static int sum(int[] vals) {
        int sum = 0;
        for (int val : vals) {
            sum += val;
        }
        return sum;
    }

    public static int[] sort(int[] vals, boolean isAsc) {
        Arrays.sort(vals);
		if (isAsc) {
			return vals;
		}
        int[] ret = new int[vals.length];
        for (int i = 0; i < vals.length; i++) {
            ret[vals.length - i - 1] = vals[i];
        }
		return ret;
	}
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<LL,LL> P;
const LL mod=1000000007;
const LL INF=100000000000;
string u="abcdefghijklmnopqrstuvwxyz";


int main(){
    string s[]={"eraser","erase","dreamer","dream"};
    string t;
    cin >> t;
    for(int i=0;i<4;i++){
        while(t.find(s[i])!=string::npos){
            t.erase(t.find(s[i]),s[i].length());
        }
    }
    if(t.length()==0)puts("YES");
    else puts("NO");
    return 0;
}
//  [cpp]
#include <iostream>
#include<algorithm>
using namespace std;

int main()
{
	unsigned int n,y;
	bool flg;


	string s, t = "", cnd[4] = { "eraser","erase","dreamer","dream" },ret;
	cin >> s;

	for (int i = 0; i < 4; i++) {
		while ((int)s.find(cnd[i]) >= 0) {
			s= s.erase((int)s.find(cnd[i]),cnd[i].length());
		}
	}
	if (s.length() == 0) {
		cout << "YES" << endl;
	}
	else {
		cout << "NO" << endl;
	}

	return 0;
}
//  [cpp]
//Be Name Khoda
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const int MOD = (int)1e9 + 7;
const int MAXN = (int)1e6 + 7;
bool dp[MAXN];
bool erase(string s, int i)
{
	if(i + 5 > s.size())
		return false;
	if(s[i] == 'e' and s[i + 1] == 'r' and s[i + 2] == 'a' and s[i + 3] == 's' and s[i + 4] == 'e')
		return true;
	return false;
}
bool eraser(string s, int i)
{
	if(i + 6 > s.size())
		return false;
	if(s[i] == 'e' and s[i + 1] == 'r' and s[i + 2] == 'a' and s[i + 3] == 's' and s[i + 4] == 'e' and s[i + 5] == 'r')
		return true;
	return false;
}
bool dream(string s, int i)
{
	if(i + 5 > s.size())
		return false;
	if(s[i] == 'd' and s[i + 1] == 'r' and s[i + 2] == 'e' and s[i + 3] == 'a' and s[i + 4] == 'm')
		return true;
	return false;
}
bool dreamer(string s, int i)
{
	if(i + 7 > s.size())
		return false;
	if(s[i] == 'd' and s[i + 1] == 'r' and s[i + 2] == 'e' and s[i + 3] == 'a' and s[i + 4] == 'm' and s[i + 5] == 'e' and s[i + 6] == 'r')
		return true;
	return false;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	string s;
	cin >> s;
	for (int i = s.size() - 1; i >= 0; i--)
	{
		if(erase(s, i) and (i + 5 == s.size() or dp[i + 5]))
			dp[i] = 1;
		else
		if(eraser(s, i) and (i + 6 == s.size() or dp[i + 6]))
			dp[i] = 1;
		else
		if(dream(s, i) and (i + 5 == s.size() or dp[i + 5]))
			dp[i] = 1;
		else
		if(dreamer(s, i) and (i + 7 == s.size() or dp[i + 7]))
			dp[i] = 1;
	}
	if(dp[0])
		cout << "YES";
	else
		cout << "NO";
}
//  [c]
#include <stdio.h>
#include <string.h>

int i;
int main(void)
{
    char s[100001];
    char t[4][8]={"maerd","remaerd","esare","resare"};// <-4種
    char tmp;
    scanf("%s",s);
    int len_s=(int)strlen(s);
    for(int k=0;k<len_s/2;k++){
        tmp=s[k];
        s[k]=s[len_s-1-k];
        s[len_s-1-k]=tmp;
    }
    while(s[0]){
        int a=0;//aの値をリセット
        for(i=0;i<4;i++){
            int c=0,same=0;//カウントをリセット
            for(int j=0;t[i][j]!='\0';j++){
                c++;
                if(s[j]==t[i][j]){
                    same++;
                }
            }
            if(c==same){//tの文字列の長さと同じだけ一致してたら
                a=same;//aにsameを保存
            }
        }
        if(a==0){
            printf("NO\n");
            return 0;
        }
        for(int j=0;s[j]!='\0';j++){//4種と比べ終わったら
            s[j]=s[j+a];
        }
    }
    printf("YES\n");
    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>

int i;
int main(void)
{
    char s[100001];
    char t[4][8]={"maerd","remaerd","esare","resare"};// <-4種
    char tmp;
    scanf("%s",s);
    int len_s=(int)strlen(s);
    for(int k=0;k<len_s/2;k++){
        tmp=s[k];
        s[k]=s[len_s-1-k];
        s[len_s-1-k]=tmp;
    }
    //printf("%s\n",s);
    while(s[0]){
        int a=0;//aの値をリセット
        for(i=0;i<4;i++){
            //printf("-------\n");
            int c=0,same=0;//カウントをリセット
            for(int j=0;t[i][j]!='\0';j++){
                //printf("t[%d][%d]=%c\n",i,j,t[i][j]);
                c++;
                if(s[j]==t[i][j]){
                    same++;
                }
            }
            //printf("c=%d,same=%d\n",c,same);
            if(c==same){//tの文字列の長さと同じだけ一致してたら
                a=same;//aにsameを保存
            }
            //
        }
        //printf("a=%d\n",a);
        if(a==0){
            printf("NO\n");
            return 0;
        }
        //4種と比べ終わったら
        for(int j=0;s[j]!='\0';j++){
            s[j]=s[j+a];
        }
    }
    printf("YES\n");
    return 0;
}
//  [c]
#include<stdio.h>
#include <string.h>

int main()
{
  char S[100001],temp;
    scanf("%s",&S);
  char T[4][8]={"maerd","remaerd","esare","resare"};
  
  int s,i,j,a,k;
  
  
  s=strlen(S);
  
  for(i=0;i<s/2;i++)
  {
    temp=S[i];
    S[i]=S[s-i-1];
    S[s-i-1]=temp;
  }

  
  for(i=0;i<4 && strlen(S)>1;i++)
  {
    k=strlen(T[i]);
    s=strlen(S);

    a=strncmp(S,T[i],k);
    if(a==0)
    {
      for(j=0;j<s;j++)
      {
        S[j]=S[j+k];
      }
      i=-1;
    }
  }

  a=strlen(S);
  if(a==0)
  {
      printf("YES");
  }
  else
  {
      printf("NO");
  }


  return 0;
}
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
  	
  	const reverse = (s) => {
      return s.split("").reverse().join("");
    };
  	
  	var WORDS = ["dream", "dreamer", "erase", "eraser"].map(reverse);
  	var S = reverse(input.split("\n")[0]);
  	var S_org = reverse(input.split("\n")[0]);
  	var word = "";
  	var T = ""; // 結果
  	var length = 0;
  	
  	// 一文字ずつ追加していきWORDSに一致するものがあるかどうか判定する
    // 見つかったらカウンタをリセットする、文字列も削る
  while(S.length>5){
      	word += S[length];
    
    	var result = -1;
    	var idx = 0;
    	// 文字が含まれるか検索
    	for(var i=0; i<WORDS.length; i++){
          // 一致する文字があるかどうか確かめる
          idx = word.indexOf(WORDS[i]);
          // 無かったら次へ
          if(idx == -1){
          	continue; 
          }
          // 余分な文字を削除し完全一致するか判定
          if(word.slice(idx) === WORDS[i]){
		  	result = i;
          }
        }
      	// 一致したものがあるとき
      	if(result != -1){
        	T += WORDS[result];  // 前に文字列を追加
          	S = S.slice(length);// 追加した文字までを削除する
          	word = ""   // 文字のリセット
          	length = 0; // カウントのリセット
        }
      	length += 1;
	}
  
  	// SとTが一致するとき
  	if(S_org == T){
      console.log("YES");
    // しないとき
    }else{
      console.log("NO");
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
  	
  	const reverse = (s) => {
      return s.split("").reverse().join("");
    };
  	
  	var WORDS = ["dream", "dreamer", "erase", "eraser"].map(reverse);
  	var S = reverse(input.split("\n")[0]);
  	var S_org = reverse(input.split("\n")[0]);
  	var word = "";
  	var T = ""; // 結果
  	var length = 0;
  	
  	// 一文字ずつ追加していきWORDSに一致するものがあるかどうか判定する
    // 見つかったらカウンタをリセットする、文字列も削る
  while(S.length>5){
      	word += S[length];
    	/*
    	console.log("length!!!!"+length);
        console.log("word!!!!!"+word);
        */
    
    	var result = -1;
    	var idx = 0;
    	// 文字が含まれるか検索
    	for(var i=0; i<WORDS.length; i++){
          // 一致する文字があるかどうか確かめる
          idx = word.indexOf(WORDS[i]);
          // 無かったら次へ
          if(idx == -1){
          	continue; 
          }
          //console.log(word.slice(idx)+" vs "+WORDS[i]);
          // 余分な文字を削除し完全一致するか判定
          if(word.slice(idx) === WORDS[i]){
		  	result = i;
            /*
            console.log("idx!!!"+idx);
            console.log("slice!!!"+word.slice(idx));
            console.log(word.length-idx+" vs "+WORDS[i].length);
            console.log(word);
            console.log("result!!!!!"+WORDS[result]);
            */
          }
        }
      	//var result = WORDS.indexOf(word); // 一致するものがあるか検索
      	// 一致したものがあるとき
      	if(result != -1){
        	T += WORDS[result];  // 前に文字列を追加
          	S = S.slice(length);// 追加した文字までを削除する
          	//console.log("T:"+T+" vs "+S+":S");
          	word = ""   // 文字のリセット
          	length = 0; // カウントのリセット
        }
      	length += 1;
	}
  
  	// SとTが一致するとき
  	if(S_org == T){
      console.log("YES");
    // しないとき
    }else{
      console.log("NO");
    }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(input) {
    const reverse = (s) => {
        return s.split('').reverse().join('');
    };

    const WORDS = ['dream', 'dreamer', 'erase', 'eraser'].map(reverse);
    const S = reverse(input.split('\n')[0]);

    var index = 0;

    while(true) {
        var w = WORDS.find((w) => S.startsWith(w, index));
        if (!w) break;
        index += w.length;
    }

    if (S.length === index) {
        console.log('YES');
    } else {
        console.log('NO');
    }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

import (
	"fmt"
	"strings"
)

type line struct {
	s string
}

func main() {
	var n int
	n = 1
	// fmt.Scan(&n, &m)

	lines := []line{}
	for i := 0; i < n; i++ {
		l := line{}
		fmt.Scan(&l.s)
		lines = append(lines, l)
	}
	// fmt.Println(lines)

	test := func(lines []line) string {
		for _, l := range lines {
			rest := ""
			for _, c := range l.s {
				rest = string(c) + rest
			}
			rTerms := []string{"maerd", "remaerd", "esare", "resare"}
			i := 0
			for i == 0 {
				for _, t := range rTerms {
					i = strings.Index(rest, t)
					if i == 0 {
						rest = rest[len(t):]
						break
					}
				}
			}
			if rest == "" {
				return "YES"
			}
		}
		return "NO"
	}
	fmt.Println(test(lines))
}
//  [go]
package main

import (
	"fmt"
	"strings"
)

func main() {
	var s string
	fmt.Scan(&s)

	fmt.Println(abc049c(s))
}

func abc049c(s string) string {
	s = reverse(s)
	s = strings.Replace(s, "resare", "", -1)
	s = strings.Replace(s, "esare", "", -1)
	s = strings.Replace(s, "remaerd", "", -1)
	s = strings.Replace(s, "maerd", "", -1)

	if len(s) == 0 {
		return "YES"
	} else {
		return "NO"
	}
}

func reverse(s string) string {
	var res string
	for i := len(s) - 1; i >= 0; i-- {
		res += string(s[i])
	}
	return res
}
//  [go]
package main

import "fmt"

func reverse(str string) string {
	rev := ""
	for i := range str {
		rev += string(str[len(str)-i-1])
	}
	return rev
}

func main() {
	var s string
	fmt.Scan(&s)

	rev := reverse(s)
	for {
		if rev == "" {
			fmt.Println("YES")
			break
		} else if len(rev) >= 7 && rev[:7] == "remaerd" {
			rev = rev[7:]
		} else if len(rev) >= 6 && rev[:6] == "resare" {
			rev = rev[6:]
		} else if len(rev) >= 5 && rev[:5] == "maerd" || rev[:5] == "esare" {
			rev = rev[5:]
		} else {
			fmt.Println("NO")
			break
		}
	}
}
//  [ruby]
string = gets.chomp.reverse
reg = /^(?:maerd)|(?:remaerd)|(?:esare)|(?:resare)/
 
while string.length > 0
  break unless string.gsub!(reg, '')
end
if string.length == 0
  puts 'YES'
else
  puts 'NO'
end