data Node = B | W | N Node Node Node Node deriving Show union :: Node -> Node -> Node union B _ = B union _ B = B union W x = x union x W = x union (N x1 x2 x3 x4) (N y1 y2 y3 y4) = N (union x1 y1) (union x2 y2) (union x3 y3) (union x4 y4) count :: Node -> Int count t = count1 (32*32 :: Int) t where count1 _ W = 0 count1 n B = n count1 n (N x1 x2 x3 x4) = count1 n1 x1 + count1 n1 x2 + count1 n1 x3 + count1 n1 x4 where n1 = n `div` 4 height :: Node -> Int height t = f 0 t where f n B = n f n W = n f n (N a b c d) = f (n+1) a `max` f (n+1) b `max` f (n+1) c `max` f (n+1) d readsTree ('e':s) = [(W, s)] readsTree ('f':s) = [(B, s)] readsTree ('p':s) = [(N x1 x2 x3 x4, t) | (x1,s1) <- readsTree s, (x2,s2) <- readsTree s1, (x3,s3) <- readsTree s2, (x4,t) <- readsTree s3] readsTree _ = [] instance Read Node where readsPrec _ = readsTree mymain s = m1 s where m1 (nstring : xs) = m2 (read nstring) xs m2 :: Int -> [String] -> [String] m2 0 _ = [] m2 n (x:y:xs) = ("There are " ++ show (count ((readc x) `union` (readc y))) ++ " black pixels.") : m2 (n-1) xs readc x = let t = read x in if height t > 5 then error "too high" else t main = interact (unlines . mymain . lines)