use std::fmt;

#[derive(Debug)]
enum ANS {
    WAR,
    NOWAR,
}
impl fmt::Display for ANS {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let text = match self {
            ANS::WAR => "War",
            ANS::NOWAR => "No War",
        };
        write!(f, "{}", text)
    }
}

fn main() {
    let (_n, _m, x, y) = read_tuple::<i32>();
    let x_points = read_vec::<i32>();
    let y_points = read_vec::<i32>();

    let mut ans = ANS::WAR;
    for z in (x+1)..=y {
        if x_points.iter().all(|&x| x < z) && y_points.iter().all(|&y| z <= y) {
            ans = ANS::NOWAR;
            break;
        }
    }
    println!("{}", ans);
}
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}
fn read_tuple<T: std::str::FromStr + Copy>() -> (T, T, T, T) {
    let temp = read_vec();
    (temp[0], temp[1], temp[2], temp[3])
}


import Foundation
func toTuple<T>(_ args: [T]) -> (T, T, T, T) { (args[0], args[1], args[2], args[3]) }
func readInts() -> [Int] { readLine()!.split(separator: " ").map { Int($0)! } }

let (n, m, x, y) = toTuple(readInts())
let xi = readInts().sorted(by: >)
let yi = readInts().sorted()
var z = -100
var ok = false
while !ok && z <= 100 {
  ok = xi[0] < z && yi[0] >= z && x < z && z <= y
  z += 1
}
print(ok ? "No War" : "War")


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    func count() -> Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
}
extension Array where Element: Comparable {
    func max() -> Element! {
        return self.maxElement()
    }
    func min() -> Element! {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

/*************** メインプログラム ***************/

let input = readIntSplit(by: " ")
let (X, Y) = (input[2], input[3])
let maxX = readIntSplit(by: " ").sorted().reversed()[0]
let minY = readIntSplit(by: " ").sorted()[0]
for Z in X+1...Y {
    if maxX < Z && minY >= Z {
        print("No War")
        break
    }
    if Z == Y {
        print("War")
    }
}


import Foundation
func toTuple<T>(_ args: [T]) -> (T, T, T, T) { (args[0], args[1], args[2], args[3]) }
func readInts() -> [Int] { readLine()!.split(separator: " ").map { Int($0)! } }

let (n, m, x, y) = toTuple(readInts())
let xi = readInts().sorted(by: >)
let yi = readInts().sorted()

var count = 1
var ok = false
while !ok && count <= 100 {
  ok = xi[0] < count && yi[0] >= count && x < count && y >= count
  count += 1
}
print(ok ? "No War" : "War")


import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    func count() -> Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
}
extension Array where Element: Comparable {
    func max() -> Element! {
        return self.maxElement()
    }
    func min() -> Element! {
        return self.minElement()
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/

/*************** メインプログラム ***************/

let input = readIntSplit(by: " ")
let (N, M, X, Y) = (input[0], input[1], input[2], input[3])
let minX = readIntSplit(by: " ").sorted()[0]
let maxY = readIntSplit(by: " ").sorted().reversed()[0]
for Z in X+1...Y {
    if minX < Z && maxY >= Z {
        print("No War")
        break
    }
    if Z == Y {
        print("War")
    }
}


const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);const tn=():number=>{const a=input[0];input.shift();return Number(a)};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{const a=input[0];input.shift();return String(a)};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const tc=():string=>{let a=input[0].split('');const b=a[0];a.shift();if(a.length>0){input[0]=a.join('')}else{input.shift()}return String(b)};const tcc=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(tc())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const gojo=(a:number,b:number):number=>{if(a%b===0)return b;return gojo(b,a%b)};
const main=()=>{
  let[n,m,x,y]=tnn(4)
  let[xx,yy]=[tnn(n),tnn(m)]
  let f;
  for(let j=x+1;j<=y;j++){
    f=false
    for(let i=0;i<n;i++){
      if(xx[i]>=j){
        f=true
        break
      }
    }
    for(let i=0;i<m;i++){
      if(yy[i]<j){
        f=true
        break
      }
    }
    if(!f){break}
  }
  to(f?'War':'No War')
}
main()


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

const [n, m, _x, _y] = stdin.split('\n')[0].split(' ').map(Number)
const x = stdin.split('\n')[1].split(' ').map(Number)
const y = stdin.split('\n')[2].split(' ').map(Number)

const xMax = Math.max(...x)
const yMin = Math.min(...y)

const ans = _ => {
  for(let i = _x + 1; i <= _y; i++){
    if(xMax < i && yMin >= i){
      return 'No War'
    }
  }
  return 'War'
}

console.log(ans())


{
	const process = (a: string[][]): string => {
		const aa = a.map((e) => e.map((ee) => parseInt(ee)))
		const n = aa[0][0]
		const m = aa[0][1]
		const x = aa[0][2]
		const y = aa[0][3]
		const xx = aa[1]
		const yy = aa[2]

		if (y - x <= 0) {
			return "War"
		}
		const xxMax = Math.max(...xx)
		const yyMin = Math.min(...yy)

		if (yyMin - xxMax <= 0) {
			return "War"
		}

		if (yyMin > x && xxMax < y) {
			return "No War"
		}
		return "War"
	}

	const Main = (input: string): void => {
		//const n: number = parseInt(input)
		//const a: string[]  = input.split(" ")
		const aa: string[][]  = input.split("\n").map((e) => e.split(" "))
		console.log(process(aa))
	}

	Main(require("fs").readFileSync("/dev/stdin", "utf8"))
}


{
	const process = (a: string[][]): string => {
		const aa = a.map((e) => e.map((ee) => parseInt(ee)))
		const n = aa[0][0]
		const m = aa[0][1]
		const x = aa[0][2]
		const y = aa[0][3]
		const xx = aa[1]
		const yy = aa[2]

		if (y - x <= 0) {
			return "War"
		}
		const xxMax = Math.max(...xx)
		const yyMin = Math.min(...yy)
		console.log(x, y, xxMax, yyMin)

		if (yyMin - xxMax <= 0) {
			return "War"
		}

		if (yyMin > x && xxMax < y) {
			return "No War"
		}
		return "War"
	}

	const Main = (input: string): void => {
		//const n: number = parseInt(input)
		//const a: string[]  = input.split(" ")
		const aa: string[][]  = input.split("\n").map((e) => e.split(" "))
		console.log(process(aa))
	}

	Main(require("fs").readFileSync("/dev/stdin", "utf8"))
}


var int = x=>parseInt(x,10);var spln = x=>x.split(/\n/g);var spsp = x=>x.split(/\s/g);
function main(input) {
  var a = input.split(/\n/g)
  var p = a[0].split(/\s/g).map((v)=>parseInt(v,10))
  var n = parseInt(p[0],10)
  var m = parseInt(p[1],10)
  var x = a[1].split(/\s/g).map((v)=>parseInt(v,10)).slice(0,n)
  x.push(n)
  x = x.sort((a,b)=>{
    	if( a > b ) return -1;
        if( a < b ) return 1;
        return 0;
})
  var y = a[2].split(/\s/g).map((v)=>parseInt(v,10)).slice(0,m)
  y.push(m)
  y = y.sort((a,b)=>{
        if( a < b ) return -1;
        if( a > b ) return 1;
        return 0;
})

  if(x[0]>=y[0]){
     console.log('War')
  }else{
     console.log('No War')
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


import itertools
H,W,K=map(int,input().split())

C=[]

for i in range(H):
  C.append(input())

ans=0
for i in range(H+1):
  for j in range(W+1):
    for n in itertools.combinations(list(range(H)),i):
      for m in itertools.combinations(list(range(W)),j):
        count = 0
        for a in n:
          for b in m:
            if(C[a][b]=="#"):count+=1
        if(count == K):
          ans += 1
print(ans)


import sys
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
from itertools import product
def main():
    h, w, k = map(int, input().split())
    gg = []
    for _ in range(h):
        row = [1 if c == '#' else 0 for c in list(input())]
        gg.extend(row)
    row_pro = tuple(product((0, 1), repeat=h))
    col_pro = tuple(product((0, 1), repeat=w))
    rows = []
    for re in row_pro:
        rows.append([i for i, b in enumerate(re) if b])
    cols = []
    for ce in col_pro:
        cols.append([i for i, b in enumerate(ce) if b])
    pat = tuple(product(rows, cols))
    r = 0
    for pate in pat:
        t0 = 0
        for p0 in pate[0]:
            for p1 in pate[1]:
                t0 += gg[p0*w + p1]
        if t0 == k:
            r += 1
    print(r)

if __name__ == '__main__':
    main()


H,W,K = map(int, input().split())
C = [input() for _ in range(H)]
ANS = 0

for i in range(1<<W):
    D = [0]*37
    D[0] = 1

    for c in C:
        cnt = 0
        for b in range(6):
            if (i & (1<<b)) and c[b] == '#':
               cnt += 1

        for j in range(36-cnt, -1, -1):
            D[j+cnt] += D[j]

    ANS += D[K]

print(ANS)


N = int(input())

ans = 0
for i in range(1, N):
    ans += (N-1) // i

print(ans)


import sys
H,W,K = map(int,input().split())
s = [list(input()) for i in range(H)]
laynum = []
rownum = []
for i in range(H):
    blnum = 0
    for j in range(W):
        if s[i][j] == "#":
            blnum += 1
    laynum.append(blnum)
for i in range(W):
    blnum = 0
    for j in range(H):
        if s[j][i] == "#":
            blnum+=1
    rownum.append(blnum)
total = sum(laynum)
if total == K:
    print(1)
    sys.exit()
way = 0
for i in laynum:
    for j in rownum:
        if i==total-K or j==total-K or j+i==total-K:
            way+=1
for s in range(0,len(laynum)):
    for t in range(s+1,len(laynum)):
        if laynum[s]+laynum[t] == total-K:
            way+=1
for s in range(0,len(rownum)):
    for t in range(s+1,len(rownum)):
        if rownum[s]+rownum[t] == total-K:
            way+=1
print(way)


H,W,K = map(int,input().split())
s = [list(input()) for i in range(H)]
laynum = []
rownum = []
for i in range(H):
    blnum = 0
    for j in range(W):
        if s[i][j] == "#":
            blnum += 1
    laynum.append(blnum)
for i in range(W):
    blnum = 0
    for j in range(H):
        if s[j][i] == "#":
            blnum+=1
    rownum.append(blnum)
total = sum(laynum)
way = 0
for i in laynum:
    for j in rownum:
        if i==total-K or j==total-K or j+i==total-K:
            way+=1
for s in range(0,len(laynum)):
    for t in range(s+1,len(laynum)):
        if laynum[s]+laynum[t] == total-K:
            way+=1
for s in range(0,len(rownum)):
    for t in range(s+1,len(rownum)):
        if rownum[s]+rownum[t] == total-K:
            way+=1
if way == 0:
    way = 1
print(way)


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

public class Main {
    public static void main(String[] args) {
        FastReader s = new FastReader();
        int h = s.nextInt();
        int w = s.nextInt();
        int k = s.nextInt();
        char [][] arr = new char[h][w];
        String s1;
        int bl,wh;
        bl=0;
        wh=0;
        for(int i=0;i<h;i++){
            s1=s.next();
            for(int j=0;j<w;j++){
                arr[i][j]=s1.charAt(j);
            }
        }
        int res=0;
        for (int i = 0; i < (1 << h); ++i) {
            for (int j = 0; j < (1 << w); ++j) {
                int cur = 0;
                for (int l = 0; l < h; ++l) {
                    for (int m = 0; m < w; ++m) {
                        if (((i&(1 << l))!=0) || (j & (1 << m)) !=0) {
                            continue;
                        }
                        if(arr[l][m] == '#')
                            cur++;
                    }
                }
                if(cur==k)
                    res++;
            }
        }
        System.out.println(res);
    }

    private static boolean isPrime(int n) {
        if (n == 2)
            return true;
        else if ((n % 2 == 0 && n > 2) || n < 2)
            return false;
        else {
            for (int i = 3; i <= (int) Math.sqrt(n); i += 2) {
                if (n % i == 0)
                    return false;
            }
            return true;
        }

    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

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

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

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

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

}


import java.util.*;
import java.io.*;
import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);

		// 入力
		int h = sc.nextInt();
		int w = sc.nextInt();
		int k = sc.nextInt();
		char[][] grid = new char[h][w];
		for(int i = 0; i < h; i++){
		    String s = sc.next();
		    grid[i] = s.toCharArray();
		}

		// 計算
		long result = 0;
		for(int ih = 0; ih < (1<<h); ih++){
			for(int iw = 0; iw < (1<<w); iw++){
			    long cnt = 0;
			    for(int i = 0; i < h; i++){
		            for(int j = 0; j < w; j++){
		                if(((ih>>i)&1) == 1) continue;
		                if(((iw>>j)&1) == 1) continue;
		                if(grid[i][j] == '#') cnt++;
		            }
		        }
		        if(cnt == k) result++;
			}
		}

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

	public static class Scanner {
		private BufferedReader br; private StringTokenizer tok;
		public Scanner(InputStream is) throws IOException { br = new BufferedReader(new InputStreamReader(is));}
		private void getLine() throws IOException { while(!hasNext()) tok = new StringTokenizer(br.readLine());}
		private boolean hasNext() { return tok != null && tok.hasMoreTokens();}
		public String next() throws IOException { getLine(); return tok.nextToken();}
		public int nextInt() throws IOException { return Integer.parseInt(next());}
		public long nextLong() throws IOException { return Long.parseLong(next());}
		public double nextDouble() throws IOException { return Double.parseDouble(next());}
	}
}


import java.util.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        FastScanner sc = new FastScanner(System.in);
        int h = sc.nextInt();
        int w = sc.nextInt();
        int k = sc.nextInt();
        char[][] map = new char[h][w];
        int total = 0;
        for(int i = 0; i < h; i++){
            map[i] = sc.next().toCharArray();
        }
        int ans = 0;
        for(int i = 0; i < (1 << h); i++){
            for(int j = 0; j < (1 << w); j++){
                int tmp = 0;
                for(int i2 = 0; i2 < h; i2++){
                    if((i >> i2) % 2 == 1){
                        for(int j2 = 0; j2 < w; j2++){
                            if((i >> i2) % 2 == 1){
                                if((j >> j2) % 2 == 1 && map[i2][j2] == '#'){
                                    tmp++;
                                }
                            }
                        }
                    }
                }
                if(tmp == k){
                    ans++;
                }
            }
        }
        System.out.println(ans);
    }

}

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 String[] nextArray(int n) {
        String[] a = new String[n];
        for (int i = 0; i < n; i++)
            a[i] = next();
        return a;
    }

    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;
    }
}


import java.util.*;
public class Atcoder4 {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int h = sc.nextInt();
		int w = sc.nextInt();
		int k = sc.nextInt();
		int count_Bl=0;
		int result=0;
		int[][] board =new int[h][w];

		for(int i=0;i<h;i++){
			String input=sc.next();
			for(int j=0;j<w;j++){
				if(input.charAt(j)=='#'){
					board[i][j] = 1;
				}else{
					board[i][j] = 0;
				}

			}
		}
		for(int i=0;i<Math.pow(2,h);i++){
			String paH=String.format("%6s",Integer.toBinaryString(i));
			for(int j=0;j<Math.pow(2,w);j++){
				String paW=String.format("%6s",Integer.toBinaryString(j));

				for(int n=0;n<h;n++){
					for(int m=0;m<w;m++){
						if(paH.charAt(6-h+n)!='1' && paW.charAt(6-w+m)!='1'){
							if(board[n][m]==1){
								count_Bl+=1;
							}
						}
					}
				}
				if(count_Bl==k){
					result+=1;
				}
				count_Bl=0;
			}
		}
		System.out.println(result);
	}
}


import java.util.Scanner;

//解説を参考した
public class Main{
    public static int change(String s) {
        if (s.equals("#"))
            return 1;
        return 0;
    }

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

        final int H = sc.nextInt();
        final int W = sc.nextInt();
        final int K = sc.nextInt();

        String[][] s = new String[H][W];

        for (int i = 0; i < H; i++)
            for (int j = 0; j < W; j++)
                s[i][j] = sc.next();

        int ans = 0;
        for (int is = 0; is < (1 << H); is++) {
            for (int js = 0; js < (1 << W); js++) {

                int count = 0;
                for (int i = 0; i < H; i++) {
                    for (int j = 0; j < W; j++) {
                        //マスが消されているならcontinueする
                        if (((is >>> i) & 1) > 0)
                            continue;
                        if (((js >>> j) & 1) > 0)
                            continue;
                        if (s[i][j].equals("#"))
                            ++count;
                    }
                }
                if (count == K) ++ans;

            }
        }

        System.out.println(ans);

    }

}


import java.util.Scanner;

//解説を参考した
public class Main{
	public static int change(String s) {
		if (s.equals("#"))
			return 1;
		return 0;
	}

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

		final int H = sc.nextInt();
		final int W = sc.nextInt();
		final int K = sc.nextInt();

		String[][] s = new String[H][W];

		for (int i = 0; i < H; i++)
			for (int j = 0; j < W; j++)
				s[i][j] = sc.next();

		int ans = 0;
		for (int is = 0; is < (1 << H); is++) {
			for (int js = 0; js < (1 << W); js++) {

				int count = 0;
				for (int i = 0; i < H; i++) {
					for (int j = 0; j < W; j++) {
						//マスが消されているならcontinueする
						if (((is >>> i) & 1) == 1)
							continue;
						if (((js >>> j) & 1) == 1)
							continue;
						if (s[i][j].equals("#"))
							++count;
					}
				if (count == K)
					++ans;
				}

			}
		}

		System.out.println(ans);

	}

}


#include <algorithm>
#include <cstdio>
#include <cstring>
#include <map>
#include <math.h>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <vector>

using namespace std;

typedef long long ll;

char a[8][8];

int solve (int H, int W, int K) {
   int res = 0;
   for (int hMask = 0; hMask < (1 << H); hMask++) {
      for (int wMask = 0; wMask < (1 << W); wMask++) {
         int count = 0;
         for (int i = 0; i < H; i++) {
            for (int j = 0; j < W; j++) {
               if (a[i][j] == '#'
                  && !(hMask & (1 << i))
                  && !(wMask & (1 << j))) {
                  count++;
               }
            }
         }
         if (count == K) {
            res++;
         }
      }
   }
   return res;
}

int main() {

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

   for (int i = 0; i < H; i++) {
      scanf("%s", a[i]);
   }

   int ans = solve(H, W, K);
   printf("%d\n", ans);

   return 0;
}


#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using LD = long double;
using PII = pair<int, int>;
using PLI = pair<long long, int>;
using PLL = pair<long long, long long>;
using TI = tuple<int, int, int>;
mt19937 mrand(random_device{}());
int rnd(int x) { return mrand() % x; }
template<class A, class B> ostream& operator <<(ostream& out, const pair<A, B> &p) {
    return out << "(" << p.first << ", " << p.second << ")";
}
template <typename T, size_t N>
ostream& operator <<(ostream& out, const array<T, N>& a) {
  out << "["; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
  return out;
}
template <typename T>
ostream& operator <<(ostream& out, const vector<T>& a) {
  out << "["; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
  return out;
}
template <typename T>
ostream& operator <<(ostream& out, const deque<T>& a) {
  out << "["; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]";
  return out;
}
template <typename T, class Cmp>
ostream& operator <<(ostream& out, const set<T, Cmp>& a) {
  out << "{"; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "}";
  return out;
}
template <typename T>
ostream& operator <<(ostream& out, const unordered_set<T>& a) {
  out << "{"; bool first = true;
  for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "}";
  return out;
}
template <typename U, typename T, class Cmp>
ostream& operator <<(ostream& out, const map<U, T, Cmp>& a) {
  out << "{"; bool first = true;
  for (auto& p : a) { out << (first ? "" : ", "); out << p.first << ":" << p.second; first = 0;} out << "}";
  return out;
}
template<class T> inline void YES(T condition) {
    if(condition) cout << "YES" << '\n';
    else cout << "NO" << '\n';
}
template<class T> inline void Yes(T condition) {
    if(condition) cout << "Yes" << '\n';
    else cout << "No" << '\n';
}
template<class T> T gcd(T a, T b) {
    while (b) {
        T tmp = b;
        b = a % b;
        a = tmp;
    }
    return a;
}
template<class T> T lcm(T a, T b){
    return a / gcd(a, b) * b;
}

#define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)
template <typename Arg1>
void __f(const char* name, Arg1&& arg1){
  cerr << name << ": " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char* names, Arg1&& arg1, Args&&... args){
  const char* comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << ": " << arg1 << " |";
  __f(comma + 1, args...);
}

long long qpow(long long a, long long b, int MOD) {
    if (b == 0) return 1;
    long long res = 1;
    while (b) {
        if (b & 1) res = (res * a) % MOD;
        a = (a * a) % MOD;
        b >>= 1;
    }
    return res;
}

const int MOD = 1e9 + 7;
const int maxn = 2e6;
int fac[maxn + 5];
int invfac[maxn + 5];
void init() {
    fac[0] = 1;
    for (int i = 1; i <= maxn; i++) fac[i] = 1LL * fac[i - 1] * i % MOD;
    invfac[maxn] = (int)(qpow(fac[maxn], MOD - 2, MOD));
    for (int i = maxn - 1; i >= 0; i--) invfac[i] = 1LL * invfac[i + 1] * (i + 1) % MOD;
}
int C(int n, int k) {
    assert(0 <= k && n >= k);
    int tmp = (int)(1LL * invfac[k] * invfac[n - k] % MOD);
    return (int)(1LL * fac[n] * tmp % MOD);
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    int n, m, k;
    cin >> n >> m >> k;
    vector<string> mat(n);
    int ans = 0;
    for (int i = 0; i < n; i++) cin >> mat[i];
    for (int m1 = 0; m1 < 1 << n; m1++) {
        for (int m2 = 0; m2 < 1 << m; m2++) {
            int cnt = 0;
            for (int i = 0; i < n; i++) if (m1 & (1 << i)) {
                for (int j = 0; j < m; j++) if (m2 & (1 << j)) {
                    cnt += mat[i][j] == '#';
                }
            }
            ans += (cnt == k);
        }
    }
    cout << ans << '\n';
    return 0;
}


#include <bits/stdc++.h>
#define ll long long int
#define ld long double
#define f first
#define s second
#define pb push_back
#define eb emplace_back
#define mk make_pair
#define mt make_tuple
#define MOD 1000000007
#define fo(i,a,b) for(i=a;i<b;i++)
#define foe(i,a,b) for(i=a;i<=b;i++)
#define all(x) x.begin(), x.end()
#define vi vector<int>
#define vl vector <long long int>
#define pii pair <int,int>
#define pll pair <long long int, long long int>
#define vpii vector< pair<int,int> >
#define vpll vector < pair <long long int,long long int> >
#define boost ios::sync_with_stdio(false); cin.tie(0)
using namespace std;
const int inf = 1e9 + 5;
const ll inf64 = 1e18 + 5;

int main()
{
	boost;
	int n, m, z, i, j;
	cin >> n >> m >> z;
	char arr[n][m], b[n][m];
	fo(i, 0, n) {
		fo(j, 0, m)
		cin >> arr[i][j];
	}

	int ans = 0;
	for(int i = 0; i < (1 << n); i++) {
		for(int j = 0; j < (1 << m); j++) {
			for(int k = 0; k < n; k++) {
				for(int k1 = 0; k1 < m; k1++)
				b[k][k1] = arr[k][k1];
			}

			for(int k = 0; k < n; k++) {
				if(i >> k & 1) {
					for(int k1 = 0; k1 < m; k1++)
					b[k][k1] = '.';
				}
			}

			for(int k = 0; k < m; k++) {
				if(j >> k & 1) {
					for(int k1 = 0; k1 < n; k1++)
					b[k1][k] = '.';
				}
			}

			int cnt = 0;
			for(int k = 0; k < n; k++) {
				for(int k1 = 0; k1 < m; k1++)
				cnt += (b[k][k1] == '#');
			}
			if(cnt == z) ++ans;
		}
	}
	cout << ans;
}


#include <bits/stdc++.h>
#define _GLIBCXX_DEBUG
#define rep(i,n) for(int i=0;i<(n);++i)
#define repi(i,a,b) for(int i=int(a);i<int(b);++i)
#define all(x) (x).begin(), (x).end()
#define PI 3.14159265358979323846264338327950L
using namespace std;
typedef long long ll;
typedef long double ld;
int main() {
    int h,w,k;
    cin>>h>>w>>k;
    char c[h][w];
    rep(i,h){
        rep(j,w) cin>>c[i][j];
    }
    int ans=0;
    for(int i=0;i<(1<<h);i++){
        for(int j=0;j<(1<<w);j++){
            int cnt=0;
            rep(l,h){
                rep(m,w){
                    if(c[l][m]=='#') cnt++;
                }
            }
            if(cnt==k) ans++;
        }
    }
    cout<<ans;
}


#include<bits/stdc++.h>
using namespace std;

int main(){
  int H,W,K;cin>>H>>W>>K;
  char A[H][W];
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++) cin>>A[i][j];
  }
  int ans=0;
  for(int s=0;s<(1<<H);s++){
    for(int t=0;t<(1<<W);t++){
      int black=0;
      for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
          if(((s>>i) & 1)==0 && ((t>>j) &1)== 0 && A[i][j]=='#') black++;

          if(black==K) ans++;
        }
      }
    }
  }
  cout<<ans<<endl;
}


#include<bits/stdc++.h>
using namespace std;

int main(){
  int H,W,K;cin>>H>>W>>K;
  char A[H][W];
  for(int i=0;i<H;i++){
    for(int j=0;j<W;j++) cin>>A[i][j];
  }
  int ans=0;
  for(int s=0;s<(1<<H);s++){
    for(int t=0;t<(1<<W);t++){
      int black=0;
      for(int i=0;i<H;i++){
        for(int j=0;j<W;j++){
          if(((s>>i) & 1)==0 && ((t>>j) &1)== 0 && C[i][j]=='#') black++;

          if(black==K) ans++;
        }
      }
    }
  }
  cout<<ans<<endl;
}


#include <stdio.h>
#define SIZE 6

int bi1[SIZE], bi2[SIZE];
const int disit[SIZE + 1] = {1, 2, 4, 8, 16, 32, 64};

void de_bi1(int de){
  int i;
  for(i = SIZE-1; i >= 0; i--){
    bi1[i] = de / disit[i];
    de %= disit[i];
  }
  return;
}

void de_bi2(int de){
  int i;
  for(i = SIZE-1; i >= 0; i--){
    bi2[i] = de / disit[i];
    de %= disit[i];
  }
  return;
}

int main(void){
  int row, col, n, sum = 0, ans = 0, i, j, k, l;
  char bw[SIZE][SIZE];
  scanf("%d %d %d", &row, &col, &n);

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

  for(i = 0; i < disit[row]; i++){
    de_bi1(i);
    for(j = 0; j < disit[col]; j++){
      de_bi2(j);
      for(k = 0; k < row; k++){
        if(bi1[k] == 1){
          for(l = 0; l < col; l++){
            if(bi2[l] == 1){
              if(bw[k][l] == '#')
                sum++;
            }
          }
        }
      }
      if(sum == n)ans++;
      sum = 0;
    }
  }

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


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include<math.h>
#include<limits.h>
#define MAX 6
char table[MAX][MAX];
char table_copy[MAX][MAX];
char table_ori[MAX][MAX];
int H, W, K;
int count()
{
    int ret = 0;
    for (int i = 0; i < H; i++) {
        for (int j = 0; j < W; j++) {
            if (table[i][j] == '#')
                ret++;
        }
    }
    return ret;
}

int main()
{
    int ans = 0;
    scanf("%d %d %d", &H, &W, &K);
    char str[100];
    for (int i = 0; i < H; i++){
        scanf("%s", str);
        for (int j = 0; j < W; j++) {
            table[i][j] = str[j];
        }
    }

    memcpy(table_ori, table, sizeof(table));

    for (int bit1 = 0; bit1 < (1 << W); bit1++) {
        memcpy(table, table_ori, sizeof(table));
        for (int i = 0; i < W; i++) {
            if (bit1 & (1 << i)) {
                for (int j = 0; j < H; j++)
                    table[j][i] = '*';
            }
        }

        memcpy(table_copy, table, sizeof(table));

        for (int bit2 = 0; bit2 < (1 << H); bit2++) {
            memcpy(table, table_copy, sizeof(table));
            for (int k = 0; k < H; k++) {
                if (bit2 & 1 << k) {
                    for (int l = 0; l < W; l++)
                        table[k][l] = '*';
                }
            }
            if (count() == K)
                ans++;
        }
    }

    printf("%d", ans);
}


#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) < (b) ? (a) : (b))

typedef long long int ll;

int read_int()
{
    int a;
    scanf("%d", &a);
    return a;
}

int read_lint()
{
    ll a;
    scanf("%lld", &a);
    return a;
}

int read_float()
{
    float a;
    scanf("%f", &a);
    return a;
}

char read_char()
{
    char c;
    scanf("%c", &c);
    return c;
}

int read_double()
{
    double a;
    scanf("%lf", &a);
    return a;
}

void read_string(char *s)
{
    scanf("%s", s);
}

#define N 6

char c[N][N + 1];
char t[N][N + 1];

int main()
{
    ll h = read_lint();
    ll w = read_lint();
    ll k = read_lint();
    for (int i = 0; i < h; i++)
    {
        read_string(c[i]);
    }

    ll ans = 0;
    ll paternh = (int)pow(2.0, (double)h);
    ll paternw = (int)pow(2.0, (double)w);
    for (int i = 0; i < paternh; i++)
    {
        for (int j = 0; j < paternw; j++)
        {
            for (int l = 0; l < h; l++)
            {
                strcpy(t[l], c[l]);
            }

            int mask = 1;
            for (int l = 0; l < h; l++)
            {
                if (i & mask)
                {
                    for (int m = 0; m < w; m++)
                    {
                        t[l][m] = '.';
                    }
                }
                mask <<= 1;
            }

            mask = 1;
            for (int l = 0; l < w; l++)
            {
                if (j & mask)
                {
                    for (int m = 0; m < h; m++)
                    {
                        t[m][l] = '.';
                    }
                }
                mask <<= 1;
            }

            ll black = 0;
            for (int l = 0; l < h; l++)
            {
                for (int m = 0; m < w; m++)
                {
                    if (t[l][m] == '#')
                    {
                        black++;
                    }
                }
            }

            // printf("%lld\n", black);
            if (black == k)
            {
                ans++;
            }
        }
    }

    printf("%lld\n", ans);

    return 0;
}


#include <stdio.h>
#define MAX_H 6
#define MAX_W 6

int two_exp(int x) {
  int n =1;
  int i;
  for (i=0; i<x; i++) {
    n *= 2;
  }
  return n;
}

int main(void) {
  int h, w, k;
  int i, j;
  int ans = 0;
  char col[MAX_H+1][MAX_W+1] = {0};
  scanf("%d%d%d",&h,&w,&k);
  for (i=0;i<h;i++) {
      scanf("%s",col[i]);
  }

  for (i=0; i<two_exp(h);i++) {
    for (j=0; j<two_exp(w);j++) {
      int t, s;
      int block = 0;
      for (t=0; t<h; t++) {
        if (block>k) {
          break;
        }
        for (s=0; s<w; s++) {
          if (col[t][s]=='#' && (1<<t & i == 0) && (1<<s & j == 0)) {
            block++;
          }
          if (block>k) {
            break;
          }
        }
      }
      if (block == k) ans++;
    }
  }

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


#include <stdio.h>
#define MAX_H 6
#define MAX_W 6

int two_exp(int x) {
  int n =1;
  int i;
  for (i=0; i<x; i++) {
    n *= 2;
  }
  return n;
}

int main(void) {
  int h, w, k;
  int i, j;
  int ans = 0;
  char col[MAX_H][MAX_W+1] = {0};
  scanf("%d%d%d",&h,&w,&k);
  for (i=0;i<h;i++) {
      scanf("%s",col[i]);
  }

  for (i=0; i<two_exp(h);i++) {
    for (j=0; j<two_exp(w);j++) {
      int t, s;
      int block = 0;
      for (t=0; t<h; t++) {
        if (block>k) {
          break;
        }
        for (s=0; s<w; s++) {
          if (col[t][s]=='#' && (1<<t & i == 0) && (1<<s & j == 0)) {
            block++;
          }
          if (block>k) {
            break;
          }
        }
      }
      if (block == k) ans++;
    }
  }

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


#include <stdio.h>
#define MAX_H 6
#define MAX_W 6

int two_exp(int x) {
  int n =1;
  int i;
  for (i=0; i<x; i++) {
    n *= 2;
  }
  return n;
}

int main(void) {
  int h, w, k;
  int i, j;
  int ans = 0;
  char col[MAX_H][MAX_W+1] = {0};
  scanf("%d%d%d",&h,&w,&k);
  for (i=0;i<h;i++) {
      scanf("%s",&col[i][0]);
  }

  for (i=0; i<two_exp(h);i++) {
    for (j=0; j<two_exp(w);j++) {
      int t, s;
      int block = 0;
      for (t=0; t<h; t++) {
        if (block>k) {
          break;
        }
        for (s=0; s<w; s++) {
          if (col[t][s]=='#' && (1<<t & i == 0) && (1<<s & j == 0)) {
            block++;
          }
          if (block>k) {
            break;
          }
        }
      }
      if (block == k) ans++;
    }
  }

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


var GET = (function () {function f(s) {return new g(s);}function g(s) {this._s = s.trim().split("\n");}g.prototype.getValue = function (n) {return this._s[n];};g.prototype.getArray = function (n) {return this.stoa(this._s[n]);};g.prototype.slice = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stox(v));};g.prototype.sliceArray = function (s, limit) {return this._s.slice(s, +limit + s || undefined).map(v => this.stoa(v));};g.prototype.stoa = function (s) {return s.split(" ").map(v => this.stox(v));};g.prototype.stox = function (v) {var i = +v;return (i === i) ? i : v;};return f;})();
var o = GET(require("fs").readFileSync("/dev/stdin", "utf8"));

console.log(main());

function main() {
    var v1 = o.getArray(0);
    var H = +v1[0];
    var W = +v1[1];
    var K = +v1[2];

    var cn = [];
    for (var i = 0; H > i; i++) {
        cn.push(o.getValue(i + 1));
    }

    var result = 0;
    for (let bit = 0; bit < (1 << H); bit++) {
        for (let wbit = 0; wbit < (1 << W); wbit++) {
            let count = 0;
            for (let i = 0; i < H; i++) {
                if (bit & (1 << i)) continue;
                for (let j = 0; j < W; j++) {
                    if (wbit & (1 << j)) continue;
                    if (cn[i][j] === '#') {
                        count++;
                    }
                }
            }
            if (count === K) {
                result++;
            }
        }
    }
    return result;
}


'use strict';
function Main(stdin){
  const input = stdin.trim().split(/\r?\n/g);
  const [h,w,k] = input.shift().split(' ').map(Number);
  const c = input;
  let result = 0;
  for(let is = 0; is < 1 << h; is++){
    for(let js = 0; js < 1 << w; js++){
    let sum = 0;
      for(let i = 0; i < h; i++){
        if((is >> i) & 1) continue;
        for(let j = 0; j < w; j++){
          if((js >> j) & 1) continue;
          if(c[i][j] === "#") sum++;
        }
      }
      if(sum === k) result++;
    }
  }
  console.log(result);
}
// 固定
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(String(myOut));

function main(){
  var [h,w,k] = nexts(3);
  var c = nexts(h,1);
  var ans = 0;
  for(var y = 0; y < 1 << h; y++)for(var x = 0; x < 1 << w; x++){
    var sum = 0;
    for(var y2 = 0; y2 < h; y2++){
      if((y >> y2) & 1)continue;
      for(var x2 = 0; x2 < w; x2++){
        if((x >> x2) & 1)continue;
        if(c[y2][x2] === "#")sum++;
      }
    }
    if(sum === k)ans++;
  }
  return ans;
}


console.log(this)


const solve = (data, H, W, K, debug = 0) => {
  const _ = (i, j) => i * W + j;
  let result = 0;

  // Enumerate 2^H, 2^W
  for (let rows = 0; rows < 2 ** W; rows++) {
    for (let cols = 0; cols < 2 ** H; cols++) {
      // Count surviving black entries
      let count = 0;
      for (let i = 0; i < H; i++) {
        for (let j = 0; j < W; j++) {
          if (data[_(i, j)] && ((1 << i) & rows) && ((1 << j) & cols)) {
            count++;
          }
        }
      }

      if (count === K) {
        result++;
      }
    }
  }
  return result;
};

const main = async (istr, ostr) => {
  const readline = require('readline');
  const it = readline.createInterface({input: istr})[Symbol.asyncIterator]();
  const getLine = async () => (await it.next()).value;
  const getMany = async () => (await getLine()).split(' ');

  const [H, W, K] = (await getMany()).map(Number);
  const data = new Uint8Array(H * W);
  const _ = (i, j) => i * W + j;
  for (let i = 0; i < H; i++) {
    const line = await getLine();
    for (let j = 0; j < W; j++) {
      data[_(i, j)] = line[j] === '#';
    }
  }
  const result = solve(data, H, W, K);
  ostr.write(`${result}\n`);
};

if (require.main === module) {
  main(process.stdin, process.stdout);
}


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"));


package main

import (
	"bufio"
	"errors"
	"fmt"
	"io"
	"math/bits"
	"os"
	"strconv"
	"strings"
)

type Input struct {
	lines [][]string // Input は複数行からなる文字列から値をいい感じに取り出すためのメソッドを提供します.

}

func (i *Input) GetFirstAndSecondIntValue(rowIndex int) (int, int, error) {
	first, err := i.GetIntValue(rowIndex, 0)
	if err != nil {
		return first, 0, err
	}
	second, err := i.GetIntValue(rowIndex, 1)
	return first, second, err
}
func (i *Input) GetFromFirstToThirdIntValue(rowIndex int) (int, int, int, error) {
	first, second, err := i.GetFirstAndSecondIntValue(rowIndex)
	if err != nil {
		return first, second, 0, err
	}
	third, err := i.GetIntValue(rowIndex, 2)
	return first, second, third, err
}
func (i *Input) GetIntValue(rowIndex, colIndex int) (int, error) {
	line, err := i.GetLine(rowIndex)
	if err != nil {
		return 0, err
	}
	if colIndex < 0 || colIndex >= len(line) {
		return 0, fmt.Errorf("Invalid col index: %v ", colIndex)
	}
	v, err := strconv.ParseInt(line[colIndex], 10, 64)
	if err != nil {
		return 0, fmt.Errorf("failed to convert string to int: %v, %v", line[colIndex], err)
	}
	return int(v), nil
}
func (i *Input) GetLine(index int) ([]string, error) {
	if err := i.validateRowIndex(index); err != nil {
		return nil, err
	}
	return i.lines[index], nil
}
func (i *Input) GetStringLinesFrom(fromIndex int) (newLines [][]string, err error) {
	for index := range i.lines {
		if index < fromIndex {
			continue
		}
		newLine, err := i.GetLine(index)
		if err != nil {
			return nil, err
		}
		newLines = append(newLines, newLine)
	}
	return
}
func (i *Input) MustGetFromFirstToThirdIntValue(rowIndex int) (int, int, int) {
	_v0, _v1, _v2, _err := i.GetFromFirstToThirdIntValue(rowIndex)
	if _err != nil {
		panic(_err)
	}
	return _v0, _v1, _v2
}
func (i *Input) MustReadAsStringGridFrom(fromIndex int) [][]string {
	_v0, _err := i.ReadAsStringGridFrom(fromIndex)
	if _err != nil {
		panic(_err)
	}
	return _v0
}
func (i *Input) ReadAsStringGridFrom(fromIndex int) ([][]string, error) {
	lines, err := i.GetStringLinesFrom(fromIndex)
	if err != nil {
		return nil, err
	}
	var m [][]string
	for _, line := range lines {
		if len(line) > 1 {
			return nil, fmt.Errorf("unexpected length line: %v", line)
		}
		var mLine []string
		for _, r := range line[0] {
			mLine = append(mLine, string(r))
		}
		m = append(m, mLine)
	}
	return m, nil
}
func (i *Input) validateRowIndex(index int) error {
	if index >= len(i.lines) {
		return errors.New(fmt.Sprintf("index(%d) is larger than lines(%d)", index, len(i.lines)))
	}
	if index < 0 {
		return errors.New(fmt.Sprintf("index is under zero: %d", index))
	}
	return nil
}
func lib_IntToBits(v int, minDigits int) (bts []bool) {
	minDigits = lib_MustMaxInt(minDigits, bits.Len64(uint64(v)))
	for b := 0; b < minDigits; b++ {
		bts = append(bts, (v>>b)&1 == 1)
	}
	return
}
func lib_MaxInt(values ...int) (max int, err error) {
	if len(values) == 0 {
		return 0, errors.New("empty slice is given")
	}
	max = values[0]
	for _, value := range values {
		if max < value {
			max = value
		}
	}
	return
}
func lib_MustMaxInt(values ...int) (max int) {
	max, err := lib_MaxInt(values...)
	if err != nil {
		panic(err)
	}
	return max
}
func lib_MustNewInputFromReader(reader *bufio.Reader) *Input {
	_v0, _err := lib_NewInputFromReader(reader)
	if _err != nil {
		panic(_err)
	}
	return _v0
}
func lib_NewInputFromReader(reader *bufio.Reader) (*Input, error) {
	lines, err := lib_toLinesFromReader(reader)
	if err != nil {
		return nil, fmt.Errorf("failed to create new Input from reader: %v", err)
	}
	return &Input{lines: lines}, nil
}
func lib_TrimSpaceAndNewLineCodeAndTab(s string) string {
	return strings.TrimFunc(s, func(r rune) bool {
		return r == ' ' || r == '\r' || r == '\n' || r == '\t'
	})
}
func lib_readLineAsChunks(reader *bufio.Reader) (chunks []string, err error) {
	for {
		chunk, isPrefix, err := reader.ReadLine()
		if err != nil {
			return nil, err
		}
		chunks = append(chunks, string(chunk))
		if !isPrefix {
			return chunks, nil
		}
	}
}
func lib_toLinesFromReader(reader *bufio.Reader) (lines [][]string, err error) {
	for {
		chunks, err := lib_readLineAsChunks(reader)
		if err == io.EOF {
			return lines, nil
		}
		if err != nil {
			return nil, fmt.Errorf("failed to read line from reader: %v", err)
		}
		lineStr := lib_TrimSpaceAndNewLineCodeAndTab(strings.Join(chunks, ""))
		line := strings.Split(lineStr, " ")
		lines = append(lines, line)
	}
}
func main() {
	input := lib_MustNewInputFromReader(bufio.NewReader(io.Reader(os.Stdin)))
	fmt.Println(solve(input))
}
func solve(input *Input) int {
	H, W, K := input.MustGetFromFirstToThirdIntValue(0)
	board := input.MustReadAsStringGridFrom(1)
	cnt := 0
	for hb := 0; hb < (1 << H); hb++ {
		hBits := lib_IntToBits(hb, H)
		for wb := 0; wb < (1 << W); wb++ {
			wBits := lib_IntToBits(wb, W)
			blackCnt := 0
			for i, row := range board {
				if hBits[i] {
					continue
				}
				for j, color := range row {
					if wBits[j] {
						continue
					}
					if color == "#" {
						blackCnt++
					}
				}
			}
			if blackCnt == K {
				cnt++
			}
		}
	}
	return cnt
}


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
}


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)
}


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('.')
						//}
					}
				}
			}
		}
	}
}


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)
}


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)
}


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


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


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


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


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


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


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);
}


use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o).unwrap();
    stdout().write_all(&o).unwrap();
}

pub fn run(i: impl BufRead, o: &mut impl Write) -> std::io::Result<()> {
    let mut i = CpReader::new(i);
    let mut c = Vec::new();
    let (h, w, k) = i.read::<(usize, usize, usize)>();
    for _ in 0..h {
        let line: Vec<bool> = i.read_line().iter().map(|&x| x == b'#').collect();
        c.push(line);
    }
    writeln!(o, "{}", solve(c, w, k))?;
    Ok(())
}
fn solve(c: Vec<Vec<bool>>, w: usize, k: usize) -> usize {
    fn solve_y(c: &[Vec<bool>], x_to_blacks: &mut [usize], k: usize) -> usize {
        if let Some(c0) = c.get(0) {
            let c_next = &c[1..];
            let mut count = solve_y(c_next, x_to_blacks, k);
            assert!(c0.len() == x_to_blacks.len());
            for x in 0..x_to_blacks.len() {
                if c0[x] {
                    x_to_blacks[x] += 1;
                }
            }
            count += solve_y(c_next, x_to_blacks, k);
            for x in 0..x_to_blacks.len() {
                if c0[x] {
                    x_to_blacks[x] -= 1;
                }
            }
            count
        } else {
            solve_x(x_to_blacks, k)
        }
    }
    fn solve_x(x_to_blacks: &[usize], k: usize) -> usize {
        if let Some(&blacks) = x_to_blacks.get(0) {
            let count_false = solve_x(&x_to_blacks[1..], k);
            let count_true = if blacks > k {
                0
            } else {
                solve_x(&x_to_blacks[1..], k - blacks)
            };
            count_false + count_true
        } else {
            if k == 0 {
                1
            } else {
                0
            }
        }
    }
    let mut x_to_blacks = vec![0; w];
    solve_y(&c, &mut x_to_blacks, k)
}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            let mut consume = 0;
            loop {
                self.r.consume(consume);
                let b = self.r.fill_buf().unwrap();
                assert!(b.len() != 0);
                if let Some(p) = b.iter().position(|&x| x == b' ' || x == b'\n') {
                    self.b.extend_from_slice(&b[..p]);
                    consume = p + 1;
                    break;
                }
                self.b.extend_from_slice(b);
                consume = b.len();
            }
            self.r.consume(consume);
            &self.b
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            if self.b.last() == Some(&b'\n') {
                &self.b[..self.b.len() - 1]
            } else {
                &self.b
            }
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpIn>(&mut self) -> T {
            T::read_from(self)
        }

        pub fn read_vec<T: CpIn>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
        pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {
            CpIter {
                r: self,
                n: n,
                _pd: Default::default(),
            }
        }
    }
    pub struct CpIter<'a, R: BufRead + 'a, T> {
        r: &'a mut CpReader<R>,
        n: usize,
        _pd: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            if self.n == 0 {
                None
            } else {
                self.n -= 1;
                Some(self.r.read())
            }
        }
    }

    pub trait CpIn {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpIn for u64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpIn for i64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }
    impl CpIn for char {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            let b = r.r.fill_buf().unwrap()[0] as char;
            r.r.consume(1);
            let s = r.r.fill_buf().unwrap()[0];
            assert!(s == b' ' || s == b'\n');
            r.r.consume(1);
            b
        }
    }

    macro_rules! cpin_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpIn),*> CpIn for ($($t),*) {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::read_from(r)),*)
                }
            }
        };
    }

    macro_rules! cpin_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpIn for $t_self {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::read_from(r) as $t_self
                }
            }
        };
    }
    macro_rules! cpin_parse {
        ($t:ty) => {
            impl CpIn for $t {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }
    cpin_cast!(usize, u64);
    cpin_cast!(u32, u64);
    cpin_cast!(u16, u64);
    cpin_cast!(i32, i64);
    cpin_cast!(i16, i64);
    cpin_cast!(i8, i64);

    cpin_parse!(f64);

    cpin_tuple!(T1, T2);
    cpin_tuple!(T1, T2, T3);
    cpin_tuple!(T1, T2, T3, T4);
    cpin_tuple!(T1, T2, T3, T4, T5);

    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let mut idx = 0;
            let buf_len;
            {
                let buf = r.fill_buf().unwrap();
                buf_len = buf.len();
                assert!(buf_len != 0);
                while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {
                    value = value * 10 + (buf[idx] - b'0') as u64;
                    idx += 1;
                }
            }
            if idx < buf_len {
                r.consume(idx + 1);
                return value;
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let (consume, sign) = match r.fill_buf().unwrap()[0] {
            b'+' => (true, 1),
            b'-' => (true, -1),
            _ => (false, 1),
        };
        if consume {
            r.consume(1);
        }
        read_u64_fast(r) as i64 * sign
    }
}


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()
    );
}


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);
}


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()
}


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);
}


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()


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)


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)


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()


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()


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);
}


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)
});


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())


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);
}


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);
}


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);


N = input()

if N.replace('eraser', '').replace('erase', '').replace('dreamer', '').replace('dream', '') == '':
    print('YES')
else:
    print('NO')


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")


s = input().replace("eraser", "").replace("erase", "").replace("dreamer", "").replace("dream", "")
if s:
    print("NO")
else:
    print("YES")


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')


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')


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')


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;
	    }

	}

}


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();
    }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author GYSHGX868
 */
public class Main {
  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    OutputWriter out = new OutputWriter(outputStream);
    TaskC solver = new TaskC();
    solver.solve(1, in, out);
    out.close();
  }

  static class TaskC {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
      char[] s = in.nextString().toCharArray();
      for (int i = 0; i < s.length; i++) {
        if (s[i] == 'e') {
          int e1 = judge(s, i, new char[]{'e', 'r', 'a', 's', 'e', 'r'});
          if (e1 != -1) {
            i = e1;
            continue;
          }
          int e2 = judge(s, i, new char[]{'e', 'r', 'a', 's', 'e'});
          if (e2 != -1) {
            i = e2;
          } else {
            out.printLine("NO");
            return;
          }
        } else if (s[i] == 'd') {
          int e1 = judge(s, i, new char[]{'d', 'r', 'e', 'a', 'm', 'e', 'r'});
          if (e1 != -1) {
            i = e1;
            continue;
          }
          int e2 = judge(s, i, new char[]{'d', 'r', 'e', 'a', 'm'});
          if (e2 != -1) {
            i = e2;
          } else {
            out.printLine("NO");
            return;
          }
        } else if (s[i] == 'a') {
          if (i - 3 >= 0 && s[i - 3] == 'm' && s[i - 2] == 'e' && s[i - 1] == 'r') {
            int e1 = judge(s, i, new char[]{'a', 's', 'e', 'r'});
            if (e1 != -1) {
              i = e1;
              continue;
            }
            int e2 = judge(s, i, new char[]{'a', 's', 'e'});
            if (e2 != -1) {
              i = e2;
            } else {
              out.printLine("NO");
              return;
            }
          } else {
            out.printLine("NO");
            return;
          }
        } else {
          out.printLine("NO");
          return;
        }
      }
      out.printLine("YES");
    }

    private int judge(char[] s, int from, char[] substring) {
      for (int i = 1; i < substring.length; i++) {
        if (from + i >= s.length || s[from + i] != substring[i]) {
          return -1;
        }
      }
      return from + substring.length - 1;
    }

  }

  static class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private InputReader.SpaceCharFilter filter;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (numChars == -1) {
        throw new InputMismatchException();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (numChars <= 0) {
          return -1;
        }
      }
      return buf[curChar++];
    }

    public String nextString() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      StringBuilder res = new StringBuilder();
      do {
        if (Character.isValidCodePoint(c)) {
          res.appendCodePoint(c);
        }
        c = read();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
      boolean isSpaceChar(int ch);

    }

  }

  static class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
      writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
      this.writer = new PrintWriter(writer);
    }

    public void print(Object... objects) {
      for (int i = 0; i < objects.length; i++) {
        if (i != 0) {
          writer.print(' ');
        }
        writer.print(objects[i]);
      }
    }

    public void printLine(Object... objects) {
      print(objects);
      writer.println();
    }

    public void close() {
      writer.close();
    }

  }
}


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");
  }
 }

}


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");
  }
 }

}


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();
		}
	}

}


#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;

}