Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: There are three parts of speech: the adjective, the noun, the verb. Each word in his language is an adjective, noun or verb.  There are two genders: masculine and feminine. Each word in his language has gender either masculine or feminine.  Masculine adjectives end with -lios, and feminine adjectives end with -liala.  Masculine nouns end with -etr, and feminime nouns end with -etra.  Masculine verbs end with -initis, and feminime verbs end with -inites.  Thus, each word in the Petya's language has one of the six endings, given above. There are no other endings in Petya's language.  It is accepted that the whole word consists of an ending. That is, words "lios", "liala", "etr" and so on belong to the Petya's language.  There aren't any punctuation marks, grammatical tenses, singular/plural forms or other language complications.  A sentence is either exactly one valid language word or exactly one statement. Statement is any sequence of the Petya's language, that satisfy both conditions: Words in statement follow in the following order (from the left to the right): zero or more adjectives followed by exactly one noun followed by zero or more verbs.  All words in the statement should have the same gender.After Petya's friend Vasya wrote instant messenger (an instant messaging program) that supported the Petya's language, Petya wanted to add spelling and grammar checking to the program. As Vasya was in the country and Petya didn't feel like waiting, he asked you to help him with this problem. Your task is to define by a given sequence of words, whether it is true that the given text represents exactly one sentence in Petya's language.

The first line contains one or more words consisting of lowercase Latin letters. The overall number of characters (including letters and spaces) does not exceed 105. It is guaranteed that any two consecutive words are separated by exactly one space and the input data do not contain any other spaces. It is possible that given words do not belong to the Petya's language.

If some word of the given text does not belong to the Petya's language or if the text contains more that one sentence, print "NO" (without the quotes). Otherwise, print "YES" (without the quotes).

petr
etis atis animatis etis atis amatis
nataliala kataliala vetra feinites

import Data.List
solve::[String]->String
solve input | length input == 1  = case isWord $ head input of
                                           True -> "YES"
                                           False -> "NO"
            | not $ any isWord input = "NO"
            | otherwise = if isStatement input then "YES" else "NO"
                             where isWord xs = any (flip elem (tails xs)) allw
                                   adj1 = ["lios"]
                                   adj2 = ["liala"]
                                   adjs = adj1 ++ adj2
                                   n1 = ["etr"]
                                   n2 = ["etra"]
                                   ns = n1 ++ n2
                                   v1 = ["initis"]
                                   v2 = ["inites"]
                                   vs = v1 ++ v2
                                   ms = adj1 ++ n1 ++ v1
                                   fs = adj2 ++ n2 ++ v2
                                   allw = adj1 ++ adj2 ++ n1 ++ n2 ++ v1 ++ v2
                                   genderEqm xs = any (flip elem (tails xs)) ms
                                   genderEqf xs = any (flip elem (tails xs)) fs
                                   isNoun xs =  any (flip elem (tails xs)) ns
                                   isVerb xs =  any (flip elem (tails xs)) vs
                                   isAdj xs =  any (flip elem (tails xs)) adjs
                                   samepart x y = (isNoun x && isNoun y) ||
                                                  (isVerb x && isVerb y) ||
                                                  (isAdj x && isAdj y)
                                   isStatement xs = (all genderEqm xs
                                            ||
                                       all genderEqf xs) &&
                                          case length gr of
                                               1 -> ((isNoun.head) (gr !! 0)) &&
                                                      (length (head gr) == 1)
                                               2 -> ((isAdj.head.head) gr &&
                                                    (isNoun.head) (gr !! 1) &&
                                                    length (gr !! 1) == 1 ) ||
                                                    ((isNoun.head.head) gr &&
                                                    (isVerb.head) (gr !! 1) &&
                                                    length (head gr) == 1)
                                               3 -> (isAdj.head.head) gr &&
                                                    (isNoun.head) (gr !! 1) &&
                                                    (isVerb.head) (gr !! 2) &&
                                                    length (gr !! 1) == 1

                                             where  gr = groupBy samepart xs
main = do
           input <- getLine >>= return.words
           putStrLn $ solve input

import Data.List

grm :: String -> Maybe (Char, Char)
grm x
	| (reverse . take 4 . reverse) x == "lios" = Just ('m', 'a')
	| (reverse . take 5 . reverse) x == "liala" = Just ('f', 'a')
	| (reverse . take 3 . reverse) x == "etr" = Just ('m', 'n')
	| (reverse . take 4 . reverse) x == "etra" = Just ('f', 'n')
	| (reverse . take 6 . reverse) x == "initis" = Just ('m', 'v')
	| (reverse . take 6 . reverse) x == "inites" = Just ('f', 'v')
	| otherwise = Nothing

rex :: Int -> String -> Bool
rex 0 [] = False
rex _ [] = True
rex 0 ('v':xs) = rex 0 xs
rex 0 ('n':xs) = rex 1 xs
rex 0 ('a':xs) = False
rex 1 ('v':xs) = False
rex 1 ('n':xs) = False
rex 1 ('a':xs) = rex 2 xs
rex 2 ('v':xs) = False
rex 2 ('n':xs) = False
rex 2 ('a':xs) = rex 2 xs

solve :: [String] -> String
solve strs
	| grms == Nothing = "NO"
	| (grms >>= Just . length) == Just 1 = "YES"
	| (grms >>= Just . (/=1) . length . group . map fst) == Just True = "NO"
	| (grms >>= Just . rex 0 . map snd) == Just True = "YES"
	| otherwise = "NO"
	where
		grms = foldl (\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)

main = do
	getLine >>= putStrLn . solve . words

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    BS.words <$> readLine
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = putStr =<< solve . evalState parseInput <$> BS.getContents

solve words
    | any isNothing typesMaybe   = "NO"
    | length types == 1          = "YES"
    | any ((/=gender).snd) types = "NO"
    | checkStatement types'      = "YES"
    | otherwise                  = "NO"
  where
    typesMaybe = map getType words
    types = map fromJust typesMaybe
    gender = snd $ head types

    types' = map fst types

checkStatement :: [Words] -> Bool
checkStatement (Adjective:xs) = checkStatement xs
checkStatement (Noun:Verb:xs) = checkStatement (Noun:xs)
checkStatement [Noun] = True
checkStatement _ = False

data Words = Adjective | Noun | Verb deriving (Show, Eq)

getType :: ByteString -> Maybe (Words, Bool)
getType word
    | BS.pack "lios"   `BS.isSuffixOf` word = Just (Adjective, False)
    | BS.pack "liala"  `BS.isSuffixOf` word = Just (Adjective, True)
    | BS.pack "etr"    `BS.isSuffixOf` word = Just (Noun, False)
    | BS.pack "etra"   `BS.isSuffixOf` word = Just (Noun, True)
    | BS.pack "initis" `BS.isSuffixOf` word = Just (Verb, False)
    | BS.pack "inites" `BS.isSuffixOf` word = Just (Verb, True)
    | otherwise                             = Nothing

----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

newtype State s a = State { runState :: s -> (a, s) }

instance Functor (State s) where
	fmap f m = State $ \s -> let
		(a, s') = runState m s
		in (f a, s')

instance Applicative (State s) where
    pure = return
    (<*>) = ap

instance Monad (State s) where
	return a = State $ \s -> (a, s)
	m >>= k  = State $ \s -> let
		(a, s') = runState m s
		in runState (k a) s'

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State

import List
t s=last$6:[i|i<-[0..5],isSuffixOf(words"lios liala etr etra initis inites"!!i)s]
n="NO"
c x|any(>5)x=n
c[_]="YES"
c(x:y)|any((/=odd x).odd)y=n
c x=g$map(`div`2)x
g(0:x)=g x
g(1:2:x)=g(1:x)
g[1]="YES"
g _=n
main=interact$c.map t.words

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Data.Array
import Data.Char
class Scan a where scan' :: String -> a
instance Scan Int where scan' = read
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' = read
instance Scan Double where scan' = read
instance Scan Integer where scan' = read
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = (\(x:y:_) -> (scan' x,scan' y)) (words x)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z
scan :: (Scan a) => IO a
scan = getLine>>=(return.scan')
scans :: (Scan a) => Int -> IO [a]
scans n = if n==0 then return [] else scan>>=(\x->scans (n-1)>>=return.(x:))
scanlist :: (Scan a) => IO [a]
scanlist = getLine>>=return.(map scan').words
scanlists :: (Scan a) => Int -> IO [[a]]
scanlists n = if n==0 then return [] else scanlist>>=(\x->scanlists (n-1)>>=return.(x:))
putAnsLn :: (Ans a) => a -> IO ()
putAnsLn = putStrLn.showans
putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns = mapM_ putAnsLn

isAdj f = isSuffixOf (if f then "lios" else "liala")
isNoun f = isSuffixOf (if f then "etr" else "etra")
isVerb f = isSuffixOf (if f then "initis" else "inites")

parse f s = let s' = dropWhile (isAdj f) s in
            case s' of
              [] -> "NO"
              (x:xs) -> if isNoun f x && all (isVerb f) xs then
                            "YES"
                        else
                            "NO"

validword [] = False
validword (x:_) = (isVerb True x)
                  ||(isVerb False x)
                  ||(isNoun True x)
                  ||(isNoun False x)
                  ||(isAdj True x)
                  ||(isAdj False x)

solve s = if length s == 1 && validword s then
              "YES"
          else
              if parse True s == "NO" then
                  parse False s
              else
                  "YES"

main = do statement <- scanlist :: IO [String]
          putAnsLn (solve statement)

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Data.Function
import Data.Array

same [] = True
same (h:t) = all(==h)t

r w=case reverse w of
  ('s':'o':'i':'l':_) -> (True, 0)
  ('a':'l':'a':'i':'l':_) -> (False, 0)
  ('r':'t':'e':_) -> (True, 1)
  ('a':'r':'t':'e':_) -> (False, 1)
  ('s':'i':'t':'i':'n':'i':_) -> (True, 2)
  ('s':'e':'t':'i':'n':'i':_) -> (False, 2)
  _ -> (False, 3)
g = g' . (dropWhile (==0))
g' (1:l) = all (==2) l
g' _ = False
gg [x]=x/=3
gg l=g l
s w=same(map fst w)&&(gg$map snd w)
p b|b="YES"|1>0="NO"
main=interact$p.s.map r.words

import List
d=words"soil alail rte arte sitini setini"`zip`[(i,j)|j<-[0..2],i<-[0..1]]
r w=maybe(8,3)snd$find((`isPrefixOf`reverse w).fst)d
g(1:l)=all(==2)l
g _=1<0
c[x]=x<3
c l=g$dropWhile(==0)l
s((h:g),t)|all(==h)g&&c t="YES"|1>0="NO"
main=interact$s.unzip.map r.words

import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import Control.Monad
import Control.Applicative
import Data.List

isMadj btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4)  btr
                                  in end == BS.pack "lios"
           | otherwise = False

isFadj btr | BS.length btr >= 5 = let end = BS.drop (BS.length btr - 5)  btr
                                  in end == BS.pack "liala"
           | otherwise = False

isMnou btr | BS.length btr >= 3 = let end = BS.drop (BS.length btr - 3)  btr
                                  in end == BS.pack "etr"
           | otherwise = False
isFnou btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4)  btr
                                  in end == BS.pack "etra"
           | otherwise = False

isMver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6)  btr
                                  in end == BS.pack "initis"
           | otherwise = False

isFver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6)  btr
                                  in end == BS.pack "inites"
           | otherwise = False

inir btr = if isMadj btr
           then 1
           else if isFadj btr
                then 2
                else if isMnou btr
                     then 3
                     else if isFnou btr
                          then 4
                          else 5

f 5 _ = 5
f 1 btr | isMadj btr = 1
        | isMnou btr = 3
f 2 btr | isFadj btr = 2
        | isFnou btr = 4
f 3 btr | isMver btr = 3
f 4 btr | isFver btr = 4
f _ _ = 5

main = do
  str <- BS.words <$> BS.getLine
  let w = head str
      b = isMadj w || isFadj w || isMnou w || isFnou w || isMver w || isFver w
      ans = foldl' f (inir . head $ str) (tail str)
  case str of
    [x] -> if b
           then putStrLn "YES"
           else putStrLn "NO"
    _ ->   case ans of
           1 -> putStrLn "NO"
           2 -> putStrLn "NO"
           3 -> putStrLn "YES"
           4 -> putStrLn "YES"
           5 -> putStrLn "NO"

import Data.List

masc = ["lios", "etr", "initis"]
femi = ["liala", "etra", "inites"]

adj = ["lios", "liala"]
noun = ["etr", "etra"]
verb = ["initis", "inites"]

isMasc w = any (\m -> isSuffixOf m w) masc
isFemi w = any (\f -> isSuffixOf f w) femi

isAdj w = any (\a -> isSuffixOf a w) adj
isNoun w = any (\n -> isSuffixOf n w) noun
isVerb w = any (\v -> isSuffixOf v w) verb

kind w
  | isAdj w = "A"
  | isNoun w = "N"
  | isVerb w = "V"
  | otherwise = "X"

main = do
  contents <- getContents
  let d = words contents
  let order = concat $ map nub $ group.concat $ map kind d
  let nouns = length $ filter isNoun d
  let isValidStmt = nouns == 1 && any (== order) ["ANV", "AN", "NV", "N"]
  if (all isMasc d || all isFemi d) && (isValidStmt || length d == 1) then
  	putStrLn "YES"
  else
    putStrLn "NO"

ok :: [String] -> Bool
ok s
	| length s /= 1 = isValid (map gender s) && checkSpeech 0 (map speech s)
	| otherwise 	= speech (s !! 0) > 0

isValid :: [Int] -> Bool
isValid [] = True
isValid (a:(b:c)) = a == b && (a /= 0 && isValid (b:c))
isValid [a] = (a /= 0)

checkSpeech :: Int -> [Int] -> Bool
checkSpeech cur [] = cur >= 2
checkSpeech cur (x:xs)
	| x < cur				= False
	| cur < 2 && x == 3		= False
	| cur == 2 && x == 2	= False
	| otherwise				= checkSpeech x xs

speech :: String -> Int
speech s
	| suffixMatch s "lios"		= 1
	| suffixMatch s "liala"		= 1
	| suffixMatch s "etr"		= 2
	| suffixMatch s "etra"		= 2
	| suffixMatch s "initis"	= 3
	| suffixMatch s "inites"	= 3
	| otherwise					= 0

gender :: String -> Int
gender s
	| suffixMatch s "lios"		= 1
	| suffixMatch s "etr"		= 1
	| suffixMatch s "initis"	= 1
	| suffixMatch s "liala"		= 2
	| suffixMatch s "etra"		= 2
	| suffixMatch s "inites"	= 2
	| otherwise					= 0

suffixMatch :: String -> String -> Bool
suffixMatch s a = prefixMatch (reverse s) (reverse a)

prefixMatch :: String -> String -> Bool
prefixMatch _ []  = True
prefixMatch [] _  = False
prefixMatch (x:xs) (y:ys) = (x == y) && (prefixMatch xs ys)

main :: IO()
main = do
	str <- getLine
	if (ok(words (str)))
		then putStrLn "YES"
		else putStrLn "NO"

{-# OPTIONS -O2 #-}

import Data.List

data Ws = MA | FA | MN | FN | MV | FV | NO deriving (Eq, Show)

main = do
  ws' <- fmap words getLine
  let ws = map formalize ws'
  putStrLn $ if check ws then "YES" else "NO"

formalize w
  | isSuffixOf "lios" w = MA
  | isSuffixOf "liala" w = FA
  | isSuffixOf "etr" w = MN
  | isSuffixOf "etra" w = FN
  | isSuffixOf "initis" w = MV
  | isSuffixOf "inites" w = FV
  | otherwise = NO

check ws
  | elem NO ws = False
  | length ws == 1 = True
  | otherwise = checkGender ws && checkNumWord ws && checkSyntax ws

checkGender ws = checkGenderMas ws || checkGenderFem ws

checkGenderMas ws = all (`elem` [MA, MN, MV]) ws
checkGenderFem ws = all (`elem` [FA, FN, FV]) ws

checkNumWord l = 1 == length (filter (`elem` [MN, FN]) l)

checkSyntax ws
  | elem MA nvs || elem FA nvs = False
  | head nvs /= MN && head nvs /= FN = False
  | all (== MV) (tail nvs) || all (== FV) (tail nvs) = True
  | otherwise = False
  where
    nvs = dropWhile (`elem` [MA, FA]) ws

main = do
	input <- getContents
	let ws = words input
	putStr $ toString $ isValid ws
		where toString b = if b then "YES" else "NO"

data Gender = Male | Female | Unknown deriving (Eq, Show)

isValid [] = False
isValid (x:xs)
	| xs == [] = any (\w -> endsWith w x) ["lios","liala","etr","etra","initis","inites"]
	| otherwise = adj (x:xs) Unknown

adj [] g = False
adj (x:xs) g
	| endsWith "lios" x = if g == Female then False else adj xs Male
	| endsWith "liala" x = if g == Male then False else adj xs Female
	| otherwise = noun (x:xs) g

noun [] g = False
noun (x:xs) g
	| endsWith "etr" x = if g == Female then False else verb xs Male
	| endsWith "etra" x = if g == Male then False else verb xs Female
	| otherwise = False

verb [] g = True
verb (x:xs) g
	| endsWith "initis" x = if g == Female then False else verb xs Male
	| endsWith "inites" x = if g == Male then False else verb xs Female
	| otherwise = False

endsWith suf str
	| length suf > length str = False
	| otherwise = suf == drop (length str - length suf) str

main = do
	input <- getContents
	let ws = words input
	putStr $ toString $ isValid ws
		where toString b = if b then "YES" else "NO"

data Gender = Male | Female | Unknown deriving (Eq, Show)

isValid [] = False
isValid (x:xs)
	| xs == [] = any (\w -> endsWith w x) ["lios","liala","etr","etra","initis","inites"]
	| otherwise = adj (x:xs) Unknown

adj [] g = False
adj (x:xs) g
	| endsWith "lios" x = sendTailIfMale g adj xs
	| endsWith "liala" x = sendTailIfFemale g adj xs
	| otherwise = noun (x:xs) g

noun [] g = False
noun (x:xs) g
	| endsWith "etr" x = sendTailIfMale g verb xs
	| endsWith "etra" x = sendTailIfFemale g verb xs
	| otherwise = False

verb [] g = True
verb (x:xs) g
	| endsWith "initis" x = sendTailIfMale g verb xs
	| endsWith "inites" x = sendTailIfFemale g verb xs
	| otherwise = False

endsWith suf str
	| length suf > length str = False
	| otherwise = suf == drop (length str - length suf) str

sendTailIfOK badG expG g fun xs = if g == badG then False else fun xs expG
sendTailIfMale = sendTailIfOK Female Male
sendTailIfFemale = sendTailIfOK Male Female

import Data.List

grm :: String -> Maybe (Char, Char)
grm x
	| (reverse . take 4 . reverse) x == "lios" = Just ('m', 'a')
	| (reverse . take 5 . reverse) x == "liala" = Just ('f', 'a')
	| (reverse . take 3 . reverse) x == "etr" = Just ('m', 'n')
	| (reverse . take 4 . reverse) x == "etra" = Just ('f', 'n')
	| (reverse . take 6 . reverse) x == "initis" = Just ('m', 'v')
	| (reverse . take 6 . reverse) x == "inites" = Just ('f', 'v')
	| otherwise = Nothing

rex :: Int -> String -> Bool
rex 0 [] = False
rex _ [] = True
rex 0 ('v':xs) = rex 0 xs
rex 0 ('n':xs) = rex 1 xs
rex 0 ('a':xs) = False
rex 1 ('v':xs) = False
rex 1 ('n':xs) = False
rex 1 ('a':xs) = rex 2 xs
rex 2 ('v':xs) = False
rex 2 ('n':xs) = False
rex 2 ('a':xs) = rex 2 xs

solve :: [String] -> String
solve strs
	| grms == Nothing = "NO"
	| (grms >>= Just . (/=1) . length . group . map fst) == Just True = "NO"
	| (grms >>= Just . rex 0 . map snd) == Nothing = "NO"
	| otherwise = "YES"
	where
		grms = foldl (\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)

main = do
	getLine >>= putStrLn . solve . words

import Data.List

grm :: String -> Maybe (Char, Char)
grm x
	| (reverse . take 4 . reverse) x == "lios" = Just ('m', 'a')
	| (reverse . take 5 . reverse) x == "liala" = Just ('f', 'a')
	| (reverse . take 3 . reverse) x == "etr" = Just ('m', 'n')
	| (reverse . take 4 . reverse) x == "etra" = Just ('f', 'n')
	| (reverse . take 6 . reverse) x == "initis" = Just ('m', 'v')
	| (reverse . take 6 . reverse) x == "inites" = Just ('f', 'v')
	| otherwise = Nothing

rex :: Int -> String -> Bool
rex 0 [] = False
rex _ [] = True
rex 0 ('v':xs) = rex 0 xs
rex 0 ('n':xs) = rex 1 xs
rex 0 ('a':xs) = False
rex 1 ('v':xs) = False
rex 1 ('n':xs) = False
rex 1 ('a':xs) = rex 2 xs
rex 2 ('v':xs) = False
rex 2 ('n':xs) = False
rex 2 ('a':xs) = rex 2 xs

solve :: [String] -> String
solve strs
	| grms == Nothing = "NO"
	| (grms >>= Just . (/=1) . length . group . map fst) == Just True = "NO"
	| (grms >>= Just . rex 0 . map snd) == Just False = "NO"
	| otherwise = "YES"
	where
		grms = foldl (\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)

main = do
	getLine >>= putStrLn . solve . words

import Data.List

grm :: String -> Maybe (Char, Char)
grm x
	| (reverse . take 4 . reverse) x == "lios" = Just ('m', 'a')
	| (reverse . take 5 . reverse) x == "liala" = Just ('f', 'a')
	| (reverse . take 3 . reverse) x == "etr" = Just ('m', 'n')
	| (reverse . take 4 . reverse) x == "etra" = Just ('f', 'n')
	| (reverse . take 6 . reverse) x == "initis" = Just ('m', 'v')
	| (reverse . take 6 . reverse) x == "inites" = Just ('f', 'v')
	| otherwise = Nothing

rex :: Int -> String -> Bool
rex 0 [] = False
rex _ [] = True
rex 0 ('v':xs) = rex 0 xs
rex 0 ('n':xs) = rex 1 xs
rex 0 ('a':xs) = False
rex 1 ('v':xs) = False
rex 1 ('n':xs) = False
rex 1 ('a':xs) = rex 2 xs
rex 2 ('v':xs) = False
rex 2 ('n':xs) = False
rex 2 ('a':xs) = rex 2 xs

solve :: [String] -> String
solve strs
	| grms == Nothing = "NO"
	| (grms >>= Just . (/=1) . length . group . map fst) == Just True = "NO"
	| (grms >>= Just . rex 0 . map snd) == Just True = "YES"
	| otherwise = "NO"
	where
		grms = foldl (\x y -> do xx <- x; yy <- y; Just (yy:xx)) (Just []) (map grm strs)

main = do
	getLine >>= putStrLn . solve . words

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    BS.words <$> readString
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = putStr =<< solve . evalState parseInput <$> BS.getContents

solve words
    | any isNothing typesMaybe   = "NO"
    | any ((/=gender).snd) types = "NO"
    | length types == 1          = "YES"
    | checkStatement types'      = "YES"
    | otherwise                  = "NO"
  where
    typesMaybe = map getType words
    types = map fromJust typesMaybe
    gender = snd $ head types

    types' = map fst types

checkStatement :: [Words] -> Bool
checkStatement (Adjective:xs) = checkStatement xs
checkStatement (Noun:Verb:xs) = checkStatement (Noun:xs)
checkStatement [Noun] = True
checkStatement _ = False

data Words = Adjective | Noun | Verb deriving (Show, Eq)

getType :: ByteString -> Maybe (Words, Bool)
getType word
    | BS.pack "lios"   `BS.isSuffixOf` word = Just (Adjective, False)
    | BS.pack "liala"  `BS.isSuffixOf` word = Just (Adjective, True)
    | BS.pack "etr"    `BS.isSuffixOf` word = Just (Noun, False)
    | BS.pack "etra"   `BS.isSuffixOf` word = Just (Noun, True)
    | BS.pack "initis" `BS.isSuffixOf` word = Just (Verb, False)
    | BS.pack "inites" `BS.isSuffixOf` word = Just (Verb, True)
    | otherwise                          = Nothing

----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

newtype State s a = State { runState :: s -> (a, s) }

instance Functor (State s) where
	fmap f m = State $ \s -> let
		(a, s') = runState m s
		in (f a, s')

instance Applicative (State s) where
    pure = return
    (<*>) = ap

instance Monad (State s) where
	return a = State $ \s -> (a, s)
	m >>= k  = State $ \s -> let
		(a, s') = runState m s
		in runState (k a) s'

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State

import List
d=words"soil alail rte arte sitini setini"`zip`[(i,j)|j<-[0..2],i<-[1..0]]
r w=maybe(0,3)snd$find((`isPrefixOf`reverse w).fst)d
g(1:l)=all(==2)l
g _=1<0
c[x]=x<3
c l=g$dropWhile(==0)l
s((h:g),t)|all(==h)g&&c t="YES"|1>0="NO"
main=interact$s.unzip.map r.words

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Data.Function
import Data.Array

same [] = True
same (h:t) = all(==h)t

r w=case reverse w of
  ('s':'o':'i':'l':_) -> (True, 0)
  ('a':'l':'a':'i':'l':_) -> (False, 0)
  ('r':'t':'e':_) -> (True, 1)
  ('a':'r':'t':'e':_) -> (False, 1)
  ('s':'i':'t':'i':'n':'i':_) -> (True, 2)
  ('s':'e':'t':'i':'n':'i':_) -> (False, 2)
  _ -> (False, 3)
g = g' . (dropWhile (==0))
g' (1:l) = all (==2) l
g' _ = False
s w=same(map fst w)&&g(map snd w)
p b|b="YES"|1>0="NO"
main=interact$p.s.map r.words

import Data.List

masc = ["lios", "etr", "initis"]
femi = ["liala", "etra", "inites"]

adj = ["lios", "liala"]
noun = ["etr", "etra"]
verb = ["initis", "inites"]

isMasc w = any (\m -> isSuffixOf m w) masc
isFemi w = any (\f -> isSuffixOf f w) femi

isAdj w = any (\a -> isSuffixOf a w) adj
isNoun w = any (\n -> isSuffixOf n w) noun
isVerb w = any (\v -> isSuffixOf v w) verb

kind w
  | isAdj w = "A"
  | isNoun w = "N"
  | isVerb w = "V"
  | otherwise = "X"

main = do
  contents <- getContents
  let d = words contents
  let order = concat $ map nub $ group.concat $ map kind d
  let nouns = length $ filter isNoun d
  if (all isMasc d || all isFemi d) && nouns == 1 && any (== order) ["ANV", "AN", "NV", "N"] then
  	putStrLn "YES"
  else
    putStrLn "NO"

import Data.List

masc = ["lios", "etr", "initis"]
femi = ["liala", "etra", "inites"]

adj = ["lios", "liala"]
noun = ["etr", "etra"]
verb = ["initis", "inites"]

isMasc w = any (\m -> isSuffixOf m w) masc
isFemi w = any (\f -> isSuffixOf f w) femi

isAdj w = any (\a -> isSuffixOf a w) adj
isNoun w = any (\n -> isSuffixOf n w) noun
isVerb w = any (\v -> isSuffixOf v w) verb

kind w
  | isAdj w = "A"
  | isNoun w = "N"
  | isVerb w = "V"
  | otherwise = "X"

main = do
  contents <- getContents
  let d = words contents
  let order = concat $ map nub $ group.concat $ map kind d
  let nouns = length $ filter isNoun d
  let isValidStmt = nouns == 1 && any (== order) ["ANV", "AN", "NV", "N"]
  if (all isMasc d || all isFemi d) && isValidStmt || length d == 1 then
  	putStrLn "YES"
  else
    putStrLn "NO"

ok :: [String] -> Bool
ok s = isValid (map gender s) && checkSpeech 0 (map speech s)

isValid :: [Int] -> Bool
isValid [] = True
isValid (a:(b:c)) = a == b && (a /= 0 && isValid (b:c))
isValid [a] = (a /= 0)

checkSpeech :: Int -> [Int] -> Bool
checkSpeech cur [] = cur >= 2
checkSpeech cur (x:xs)
	| x < cur				= False
	| cur == 2 && x == 2	= False
	| otherwise				= checkSpeech x xs

speech :: String -> Int
speech s
	| suffixMatch s "lios"		= 1
	| suffixMatch s "liala"		= 1
	| suffixMatch s "etr"		= 2
	| suffixMatch s "etra"		= 2
	| suffixMatch s "initis"	= 3
	| suffixMatch s "inites"	= 3
	| otherwise					= 0

gender :: String -> Int
gender s
	| suffixMatch s "lios"		= 1
	| suffixMatch s "etr"		= 1
	| suffixMatch s "initis"	= 1
	| suffixMatch s "liala"		= 2
	| suffixMatch s "etra"		= 2
	| suffixMatch s "inites"	= 2
	| otherwise					= 0

suffixMatch :: String -> String -> Bool
suffixMatch s a = prefixMatch (reverse s) (reverse a)

prefixMatch :: String -> String -> Bool
prefixMatch _ []  = True
prefixMatch [] _  = False
prefixMatch (x:xs) (y:ys) = (x == y) && (prefixMatch xs ys)

main :: IO()
main = do
	str <- getLine
	if (ok(words (str)))
		then putStrLn "YES"
		else putStrLn "NO"

ok :: [String] -> Bool
ok s = isValid (map gender s) && checkSpeech 0 (map speech s)

isValid :: [Int] -> Bool
isValid [] = True
isValid (a:(b:c)) = a == b && (a /= 0 && isValid (b:c))
isValid [a] = (a /= 0)

checkSpeech :: Int -> [Int] -> Bool
checkSpeech cur [] = cur >= 2
checkSpeech cur (x:xs)
	| x < cur				= False
	| cur < 2 && x == 3		= False
	| cur == 2 && x == 2	= False
	| otherwise				= checkSpeech x xs

speech :: String -> Int
speech s
	| suffixMatch s "lios"		= 1
	| suffixMatch s "liala"		= 1
	| suffixMatch s "etr"		= 2
	| suffixMatch s "etra"		= 2
	| suffixMatch s "initis"	= 3
	| suffixMatch s "inites"	= 3
	| otherwise					= 0

gender :: String -> Int
gender s
	| suffixMatch s "lios"		= 1
	| suffixMatch s "etr"		= 1
	| suffixMatch s "initis"	= 1
	| suffixMatch s "liala"		= 2
	| suffixMatch s "etra"		= 2
	| suffixMatch s "inites"	= 2
	| otherwise					= 0

suffixMatch :: String -> String -> Bool
suffixMatch s a = prefixMatch (reverse s) (reverse a)

prefixMatch :: String -> String -> Bool
prefixMatch _ []  = True
prefixMatch [] _  = False
prefixMatch (x:xs) (y:ys) = (x == y) && (prefixMatch xs ys)

main :: IO()
main = do
	str <- getLine
	if (ok(words (str)))
		then putStrLn "YES"
		else putStrLn "NO"

main = do
	input <- getContents
	let ws = words input
	putStr $ toString $ isValid ws
		where toString b = if b then "YES" else "NO"

data Gender = Male | Female | Unknown deriving (Eq, Show)

isValid [] = False
isValid (x:xs)
	| xs == [] = any (\w -> endsWith w x) ["lios","liala","etr","liala","etr","etra"]
	| otherwise = adj xs Unknown

adj [] g = False
adj (x:xs) g
	| endsWith "lios" x = if g == Female then False else adj xs Male
	| endsWith "liala" x = if g == Male then False else adj xs Female
	| otherwise = noun (x:xs) g

noun [] g = False
noun (x:xs) g
	| endsWith "etr" x = if g == Female then False else verb xs Male
	| endsWith "etra" x = if g == Male then False else verb xs Female
	| otherwise = False

verb [] g = True
verb (x:xs) g
	| endsWith "initis" x = if g == Female then False else verb xs Male
	| endsWith "inites" x = if g == Male then False else verb xs Female
	| otherwise = False

endsWith suf str
	| length suf > length str = False
	| otherwise = suf == drop (length str - length suf) str

import Debug.Trace
main = do
	input <- getContents
	let ws = words input
	putStr $ toString $ isValid ws
		where toString b = if b then "YES" else "NO"

data Gender = Male | Female | Unknown deriving (Eq, Show)

isValid [] = False
isValid (x:xs)
	| xs == [] = any (\w -> endsWith w x) ["lios","liala","etr","liala","etr","etra"]
	| otherwise = adj (x:xs) Unknown

adj [] g = False
adj (x:xs) g
	| endsWith "lios" x = if g == Female then False else adj xs Male
	| endsWith "liala" x = if g == Male then False else adj xs Female
	| otherwise = noun (x:xs) g

noun [] g = False
noun (x:xs) g
	| endsWith "etr" x = if g == Female then False else verb xs Male
	| endsWith "etra" x = if g == Male then False else verb xs Female
	| otherwise = False

verb [] g = True
verb (x:xs) g
	| endsWith "initis" x = if g == Female then False else verb xs Male
	| endsWith "inites" x = if g == Male then False else verb xs Female
	| otherwise = False

endsWith suf str
	| length suf > length str = False
	| otherwise = suf == drop (length str - length suf) str

main = do
	input <- getContents
	let ws = words input
	putStr $ toString $ isValid ws
		where toString b = if b then "YES" else "NO"

data Gender = Male | Female | Unknown deriving (Eq, Show)

isValid [] = False
isValid (x:xs)
	| xs == [] = any (\w -> endsWith w x) ["lios","liala","etr","etra","initis","inites"]
	| otherwise = adj (x:xs) Unknown

adj [] g = False
adj (x:xs) g
	| endsWith "lios" x = sendTailIfMale g adj xs
	| endsWith "liala" x = sendTailIfFemale g adj xs
	| otherwise = noun (x:xs) g

noun [] g = False
noun (x:xs) g
	| endsWith "etr" x = sendTailIfMale g verb xs
	| endsWith "etra" x = sendTailIfFemale g verb xs
	| otherwise = False

verb [] g = True
verb (x:xs) g
	| endsWith "initis" x = sendTailIfMale g verb xs
	| endsWith "inites" x = sendTailIfFemale g verb xs
	| otherwise = False

endsWith suf str
	| length suf > length str = False
	| otherwise = suf == drop (length str - length suf) str

sendTailIfOK badG expG g fun xs = if g == expG then False else fun xs expG
sendTailIfMale = sendTailIfOK Female Male
sendTailIfFemale = sendTailIfOK Male Female

main = do
	input <- getContents
	let ws = words input
	putStr $ toString $ isValid ws
		where toString b = if b then "YES" else "NO"

data Gender = Male | Female | Unknown deriving (Eq, Show)

isValid [] = False
isValid xs = adj xs Unknown

adj [] g = False
adj (x:xs) g
	| endsWith "lios" x = if g == Female then False else adj xs Male
	| endsWith "liala" x = if g == Male then False else adj xs Female
	| otherwise = noun (x:xs) g

noun [] g = False
noun (x:xs) g
	| endsWith "etr" x = if g == Female then False else verb xs Male
	| endsWith "etra" x = if g == Male then False else verb xs Female
	| otherwise = False

verb [] g = True
verb (x:xs) g
	| endsWith "initis" x = if g == Female then False else verb xs Male
	| endsWith "inites" x = if g == Male then False else verb xs Female
	| otherwise = False

endsWith suf str
	| length suf > length str = False
	| otherwise = suf == drop (length str - length suf) str

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Data.Array
import Data.Char
class Scan a where scan' :: String -> a
instance Scan Int where scan' = read
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' = read
instance Scan Double where scan' = read
instance Scan Integer where scan' = read
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = (\(x:y:_) -> (scan' x,scan' y)) (words x)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z
scan :: (Scan a) => IO a
scan = getLine>>=(return.scan')
scans :: (Scan a) => Int -> IO [a]
scans n = if n==0 then return [] else scan>>=(\x->scans (n-1)>>=return.(x:))
scanlist :: (Scan a) => IO [a]
scanlist = getLine>>=return.(map scan').words
scanlists :: (Scan a) => Int -> IO [[a]]
scanlists n = if n==0 then return [] else scanlist>>=(\x->scanlists (n-1)>>=return.(x:))
putAnsLn :: (Ans a) => a -> IO ()
putAnsLn = putStrLn.showans
putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns = mapM_ putAnsLn

isAdj f = isSuffixOf (if f then "lios" else "liala")
isNoun f = isSuffixOf (if f then "etr" else "etra")
isVerb f = isSuffixOf (if f then "initis" else "inites")

parse f s = let s' = dropWhile (isAdj f) s in
            case s' of
              [] -> "NO"
              (x:xs) -> if isNoun f x && all (isVerb f) xs then
                            "YES"
                        else
                            "NO"

solve s = if parse True s == "NO" then
              parse False s
          else
              "YES"

main = do statement <- scanlist :: IO [String]
          putAnsLn (solve statement)

import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import Control.Monad
import Control.Applicative
import Data.List

isMadj btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4)  btr
                                  in end == BS.pack "lios"
           | otherwise = False

isFadj btr | BS.length btr >= 5 = let end = BS.drop (BS.length btr - 5)  btr
                                  in end == BS.pack "liala"
           | otherwise = False

isMnou btr | BS.length btr >= 3 = let end = BS.drop (BS.length btr - 3)  btr
                                  in end == BS.pack "etr"
           | otherwise = False
isFnou btr | BS.length btr >= 4 = let end = BS.drop (BS.length btr - 4)  btr
                                  in end == BS.pack "etra"
           | otherwise = False

isMver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6)  btr
                                  in end == BS.pack "initis"
           | otherwise = False

isFver btr | BS.length btr >= 6 = let end = BS.drop (BS.length btr - 6)  btr
                                  in end == BS.pack "inites"
           | otherwise = False

inir btr = if isMadj btr
           then 1
           else if isFadj btr
                then 2
                else if isMnou btr
                     then 3
                     else if isFnou btr
                          then 4
                          else 5

f 5 _ = 5
f 1 btr | isMadj btr = 1
        | isMnou btr = 3
f 2 btr | isFadj btr = 2
        | isFnou btr = 4
f 3 btr | isMver btr = 3
f 4 btr | isFver btr = 4
f _ _ = 5

main = do
  str <- BS.words <$> BS.getLine
  let ans = foldl' f (inir . head $ str) (tail str)
  case ans of
    1 -> putStrLn "NO"
    2 -> putStrLn "NO"
    3 -> putStrLn "YES"
    4 -> putStrLn "YES"
    5 -> putStrLn "NO"


Monocarp is playing a computer game. In this game, his character fights different monsters.A fight between a character and a monster goes as follows. Suppose the character initially has health $$$h_C$$$ and attack $$$d_C$$$; the monster initially has health $$$h_M$$$ and attack $$$d_M$$$. The fight consists of several steps:  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  the character attacks the monster, decreasing the monster's health by $$$d_C$$$;  the monster attacks the character, decreasing the character's health by $$$d_M$$$;  and so on, until the end of the fight. The fight ends when someone's health becomes non-positive (i. e. $$$0$$$ or less). If the monster's health becomes non-positive, the character wins, otherwise the monster wins.Monocarp's character currently has health equal to $$$h_C$$$ and attack equal to $$$d_C$$$. He wants to slay a monster with health equal to $$$h_M$$$ and attack equal to $$$d_M$$$. Before the fight, Monocarp can spend up to $$$k$$$ coins to upgrade his character's weapon and/or armor; each upgrade costs exactly one coin, each weapon upgrade increases the character's attack by $$$w$$$, and each armor upgrade increases the character's health by $$$a$$$.Can Monocarp's character slay the monster if Monocarp spends coins on upgrades optimally?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. Each test case consists of three lines: The first line contains two integers $$$h_C$$$ and $$$d_C$$$ ($$$1 \le h_C \le 10^{15}$$$; $$$1 \le d_C \le 10^9$$$) — the character's health and attack; The second line contains two integers $$$h_M$$$ and $$$d_M$$$ ($$$1 \le h_M \le 10^{15}$$$; $$$1 \le d_M \le 10^9$$$) — the monster's health and attack; The third line contains three integers $$$k$$$, $$$w$$$ and $$$a$$$ ($$$0 \le k \le 2 \cdot 10^5$$$; $$$0 \le w \le 10^4$$$; $$$0 \le a \le 10^{10}$$$) — the maximum number of coins that Monocarp can spend, the amount added to the character's attack with each weapon upgrade, and the amount added to the character's health with each armor upgrade, respectively. The sum of $$$k$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print YES if it is possible to slay the monster by optimally choosing the upgrades. Otherwise, print NO.

NoteIn the first example, Monocarp can spend one coin to upgrade weapon (damage will be equal to $$$5$$$), then health during battle will change as follows: $$$(h_C, h_M) = (25, 9) \rightarrow (25, 4) \rightarrow (5, 4) \rightarrow (5, -1)$$$. The battle ended with Monocarp's victory.In the second example, Monocarp has no way to defeat the monster.In the third example, Monocarp has no coins, so he can't buy upgrades. However, the initial characteristics are enough for Monocarp to win.In the fourth example, Monocarp has $$$4$$$ coins. To defeat the monster, he has to spend $$$2$$$ coins to upgrade weapon and $$$2$$$ coins to upgrade armor.

import Data.Int (Int64)
import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase =  readNums >>=
        \[hc, dc] -> readNums >>=
        \[hm, dm] -> readNums >>=
        \[k, w, a] -> putStrLn (if slay hc dc hm dm k w a then "YES" else "NO")
  where
    readNums :: IO [Int64]
    readNums = map read . words <$> getLine

ceil a b = if mod a b == 0 then div a b else 1 + div a b
slay hc dc hm dm k w a = any (\t -> s' (hc+t*a) (dc+(k-t)*w) hm dm) [0..k]
  where s' hc dc hm dm =  (ceil hc dm >= ceil hm dc)

import Control.Monad.Except (replicateM_)
import Data.Int (Int64)

main = do
    n <- readLn :: IO Int
    replicateM_ n run

run = do
    (hc:dc:_) <- readInt64s
    (hm:dm:_) <- readInt64s
    (k:w:a:_) <- readInt64s
    let x = ok hc dc hm dm k w a
    if x then putStrLn "YES" else putStrLn "NO"

ok hc dc hm dm k w a = or [ok' (hc+n*a) (dc+(k-n)*w) hm dm |n <- [0..k]]

ok' hc dc hm dm = f hc dm >= f hm dc

f health attack = (health - 1) `div` attack + 1

readInt64s :: IO [Int64]
readInt64s = fmap (map read.words) getLine


Let's call (yet again) a string good if its length is even, and every character in odd position of this string is different from the next character (the first character is different from the second, the third is different from the fourth, and so on). For example, the strings good, string and xyyx are good strings, and the strings bad, aa and aabc are not good. Note that the empty string is considered good.You are given a string $$$s$$$, you have to delete minimum number of characters from this string so that it becomes good.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$, consisting of exactly $$$n$$$ lowercase Latin letters.

In the first line, print one integer $$$k$$$ ($$$0 \le k \le n$$$) — the minimum number of characters you have to delete from $$$s$$$ to make it good. In the second line, print the resulting string $$$s$$$. If it is empty, you may leave the second line blank, or not print it at all.

main = do
    unusefulThrash <- getLine
    s <- getLine
    let ans = solve s
    putStrLn $ show $ length s - length ans
    putStrLn ans

solve :: String -> String
solve [] = []
solve [x] = []
solve (x:y:xs) =
    if x == y
    then solve (x:xs)
    else x:y:(solve xs)

import Control.Monad
import Data.List
import Data.Maybe
import Data.Char

solve :: String -> String
solve [] = []
solve [a] = []
solve (a:b:c)
    | a /= b    = (a:b:(solve c))
    | otherwise = solve (b:c)

main :: IO ()
main = do
    _ <- getLine
    s <- getLine
    print $ (-) (length s) (length $ solve s)
    putStrLn $ solve s

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

solve :: [C.ByteString] -> Builder
solve (sn:s:_) = intDec (n - C.length r) <> char7 '\n' <> byteString r <> char7 '\n'
  where
    !n = ri sn
    z = C.take n s
    loop :: String -> String -> String
    loop [] r = r
    loop [a] r = r
    loop (a:b:xs) r
      | a == b = loop (b:xs) r
      | True = loop xs (b : a : r)
    r = C.reverse $ C.pack $ loop (C.unpack z) []

main :: IO ()
main = hPutBuilder stdout . solve . C.words =<< C.getContents

module Main where

main :: IO ()
main = do
  count <- read <$> getLine
  string <- getLine
  let (removed, goodString) = goodCount count string
  print $ removed
  putStrLn goodString

goodCount::Int -> String -> (Int, String)
goodCount count string =
  let
    indexedString s = zip [1..] s
    evens s = snd <$> filter (even .fst) ( indexedString s)
    odds s = snd <$> filter (odd .fst) ( indexedString s)
    goodLength:: String -> Int
    goodLength s = length $ takeWhile (uncurry (/=)) $ zip (odds s) (evens s)
    extension [] = []
    extension (x:[]) = []
    extension s@(x:y:xs) = if x == y
      then extension (y:xs)
      else finalString s
    good  s = take ((goodLength s)*2) s
    bad s = drop ((goodLength s)*2) s
    finalString s = (good s) ++ extension (bad s)
    fs = finalString string
  in (length string - length fs, fs)


You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 106) — the number of segments and the value of k. The next n lines contain two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109) each — the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.

First line contains integer m — the smallest number of segments. Next m lines contain two integers aj, bj (aj ≤ bj) — the ends of j-th segment in the answer. The segments should be listed in the order from left to right.

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Prelude hiding (getContents, getLine, words)

sort xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))

    let sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        t <- readArray a i
                        readArray a j >>= writeArray a i
                        writeArray a j t
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    ys = find 0 ps
      where
        ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((x, d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  putStr . unwords $ map show ys

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3  -funbox-strict-fields #-}

import Control.Applicative ((<$>))

import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)
import System.Random

data Pair = Pair !Int !Int deriving (Eq, Ord)

{- NOTE
    attempt to use STRef for loop i j - slow
    System.Random - not better
    succ, pred - slow
-}

sort gen xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents
  gen <- getStdGen

  let
    ys = find 0 ps
      where
        ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3  -funbox-strict-fields #-}

import Control.Applicative ((<$>))

import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)
import System.Random

data Pair = Pair !Int !Int deriving (Eq, Ord)

{- NOTE
    attempt to use STRef for loop i j - slow
    System.Random is slow
-}
sort gen xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents
  gen <- getStdGen

  let
    ys = find 0 ps
      where
        ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3  -funbox-strict-fields #-}

import Control.Applicative ((<$>))

import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)

data Pair = Pair !Int !Int deriving (Eq, Ord)

sort xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))

    let sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    ys = find 0 ps
      where
        ps = sort . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O2  -funbox-strict-fields #-}

import Control.Applicative ((<$>))

import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)
import System.Random

data Pair = Pair !Int !Int deriving (Eq, Ord)

{- NOTE
    attempt to use STRef for loop i j - slow
    System.Random - not better
    succ, pred - slow
-}

sort gen xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents
  gen <- getStdGen

  let
    ys = find 0 ps
      where
        ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3 #-}

import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)

sort xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))

    let sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        t <- readArray a i
                        readArray a j >>= writeArray a i
                        writeArray a j t
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    ys = find 0 ps
      where
        ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((x, d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (replicateM, when, forM_)
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)
import Data.ByteString.Char8 (readInt, getLine, getContents, words)
-- import Data.List (sort)
import Data.Maybe (fromJust)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getLine, lines, getContents, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)
-- import GHC.Exts (sortWith)

data Pair = Pair !Int !Int deriving (Eq, Ord)

sort :: forall a . Ord a => [a] -> [a]
sort xs = runST $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STArray s Int a)

    let
      sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let
            f i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                if ai < s
                   then f (i+1) j
                   else do
                     aj <- readArray a j
                     if aj > s
                        then f i (j-1)
                        else do
                          t <- readArray a i
                          readArray a j >>= writeArray a i
                          writeArray a j t
                          f (i+1) (j-1)

        (i, j) <- f l r
        sort' l j
        sort' i r

    sort' 1 n
    getElems a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  let read = map (fst . fromJust . readInt) . words <$> getContents
  xs <- read

  let
    r = find 0 ps
      where
        find _ [] = []
        find !p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

        ps = sort . zipWith Pair xs $ alt
          where alt = (-1):1:alt :: [Int]

    write = do
      print $ (length r) `div` 2
      hPutBuilder stdout $ unwords_ $ map intDec r
      where unwords_ = mconcat . map (<> charUtf8 ' ')

  write

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3  -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)
import System.Random

data Pair = Pair !Int !Int deriving (Eq, Ord)

sort gen xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        s <- readArray a $ (l + r) `div` 2

        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents
  gen <- getStdGen

  let
    ys = find 0 ps
      where
        ps = sort gen . zip xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((x, d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3 #-}

import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Prelude hiding (getContents, getLine, words)

sort xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))

    let sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        t <- readArray a i
                        readArray a j >>= writeArray a i
                        writeArray a j t
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    ys = find 0 ps
      where
        ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((x, d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  putStr . unwords $ map show ys

{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}
{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (replicateM, when, forM_)
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)
import Data.ByteString.Char8 (readInt, getLine, getContents, words)
import Data.Maybe (fromJust)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getLine, lines, getContents, words)

data Pair = Pair Int Int deriving (Eq, Ord)

sort :: forall a . Ord a => [a] -> [a]
sort xs = runST $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STArray s Int a)

    let
      sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let
            f i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                if ai < s
                   then f (i+1) j
                   else do
                     aj <- readArray a j
                     if aj > s
                        then f i (j-1)
                        else do
                          t <- readArray a i
                          readArray a j >>= writeArray a i
                          writeArray a j t
                          f (i+1) (j-1)

        (i, j) <- f l r
        sort' l j
        sort' i r

    sort' 1 n
    getElems a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    r = find 0 ps
      where
        ps = sort . zipWith Pair xs $ alt
          where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length r) `div` 2
  putStr . unwords $ map show r

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3  -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)
import System.Random

data Pair = Pair !Int !Int deriving (Eq, Ord)

sort gen xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x

        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents
  gen <- getStdGen

  let
    ys = find 0 ps
      where
        ps = sort gen . zip xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((x, d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE FlexibleContexts #-}

import Control.Applicative ((<$>))

import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)
import System.Random

data Pair = Pair !Int !Int deriving (Eq, Ord)

{- NOTE
    attempt to use STRef for loop i j - slow
    System.Random - not better
    succ, pred - slow
-}

sort gen xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents
  gen <- getStdGen

  let
    ys = find 0 ps
      where
        ps = sort gen . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O3  -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.ST.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getContents, getLine, words)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)

data Pair = Pair !Int !Int deriving (Eq, Ord)

sort xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))

    let sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        t <- readArray a i
                        readArray a j >>= writeArray a i
                        writeArray a j t
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    ys = find 0 ps
      where
        ps = sort . zipWith Pair xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  let unwords_ = mconcat . map (<> charUtf8 ' ')
  hPutBuilder stdout $ unwords_ $ map intDec ys
  -- putStr . unwords $ map show ys

{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}
{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (replicateM, when, forM_)
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)
import Data.ByteString.Char8 (readInt, getLine, getContents, words)
import Data.Maybe (fromJust)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getLine, lines, getContents, words)

data Pair = Pair !Int !Int deriving (Eq, Ord)

sort :: forall a . Ord a => [a] -> [a]
sort xs = runST $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STArray s Int a)

    let
      sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let
            f i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                if ai < s
                   then f (i+1) j
                   else do
                     aj <- readArray a j
                     if aj > s
                        then f i (j-1)
                        else do
                          t <- readArray a i
                          readArray a j >>= writeArray a i
                          writeArray a j t
                          f (i+1) (j-1)

        (i, j) <- f l r
        sort' l j
        sort' i r

    sort' 1 n
    getElems a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    r = find 0 ps
      where
        ps = sort . zipWith Pair xs $ alt
          where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length r) `div` 2
  putStr $ unwords $ map show r

{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}
{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (replicateM, when, forM_)
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)
import Data.ByteString.Char8 (readInt, getLine, getContents, words)
import Data.Maybe (fromJust)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getLine, lines, getContents, words)

sort :: forall a . Ord a => [a] -> [a]
sort xs = runST $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STArray s Int a)

    let
      sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let
            f i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                if ai < s
                   then f (i+1) j
                   else do
                     aj <- readArray a j
                     if aj > s
                        then f i (j-1)
                        else do
                          t <- readArray a i
                          readArray a j >>= writeArray a i
                          writeArray a j t
                          f (i+1) (j-1)

        (i, j) <- f l r
        sort' l j
        sort' i r

    sort' 1 n
    getElems a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    r = find 0 ps
      where
        ps = sort . zip xs $ alt
          where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((x, d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length r) `div` 2
  putStr . unwords $ map show r

{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative ((<$>))
import Control.Monad (when)
import Control.Monad.ST.Lazy.Safe (ST, runST)
import Data.ByteString.Char8 (getLine, getContents, readInt, words)
import Data.Maybe (fromJust)
import Data.Array (elems)
import Data.Array.MArray.Safe (getElems, newListArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, runSTArray)
import Prelude hiding (getContents, getLine, words)

sort xs = elems $ runSTArray $ do
    let n = length xs
    a <- newListArray (1, n) xs -- :: ST s (STArray s Int (Int, Int))

    let sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        t <- readArray a i
                        readArray a j >>= writeArray a i
                        writeArray a j t
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    ys = find 0 ps
      where
        ps = sort . zip xs $ alt where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find p ((x, d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  print $ (length ys) `div` 2
  putStr . unwords $ map show ys

{-# LANGUAGE BangPatterns, ScopedTypeVariables, FlexibleContexts #-}
{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (replicateM, when, forM_)
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.MArray.Safe (newListArray, readArray, writeArray, newArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray, getElems)
import Data.ByteString.Char8 (readInt, getLine, getContents, words)
import Data.Maybe (fromJust)
import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Prelude hiding (getLine, lines, getContents, words)

data Pair = Pair !Int !Int deriving (Eq, Ord)

sort :: forall a . Ord a => [a] -> [a]
sort xs = runST $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STArray s Int a)

    let
      sort' l r = when (l < r) $ do
        s <- readArray a $ (l+r) `div` 2
        let
            f i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                if ai < s
                   then f (i+1) j
                   else do
                     aj <- readArray a j
                     if aj > s
                        then f i (j-1)
                        else do
                          t <- readArray a i
                          readArray a j >>= writeArray a i
                          writeArray a j t
                          f (i+1) (j-1)

        (i, j) <- f l r
        sort' l j
        sort' i r

    sort' 1 n
    getElems a

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  xs <- map (fst . fromJust . readInt) . words <$> getContents

  let
    r = find 0 ps
      where
        ps = sort . zipWith Pair xs $ alt
          where alt = (-1):1:alt :: [Int]

        find _ [] = []
        find !p ((Pair x d):ps)
          | f = x:(find c ps)
          | otherwise = find c ps
          where
            c = p + d
            f = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

  putStr $ unwords $ map show r

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields #-}

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.ByteString.Char8 (readInt, getLine, words, lines, getContents)
import Data.List (sort)
import Data.Maybe (fromJust)
import Prelude hiding (getLine, words, lines, getContents)

import Data.ByteString.Lazy.Builder  -- requires bytestring-0.10.x
import Data.ByteString.Lazy.Builder.ASCII -- omit for bytestring-0.10.2.x
import Data.Monoid
import System.IO hiding (getContents, getLine)

main = do
  [n, k] <- map (fst . fromJust . readInt). words <$> getLine
  let read = map (fst . fromJust . readInt) . words <$> getContents
  ps <- read

  let
    (xs, cs) = unzip ps' where ps' = reverse . sort . reverse . zip ps $ concat $ repeat [-1, 1 :: Int]

    cs' = scanl1 (+) cs
    f c p = (-c == k && -p == k-1) || (-c == k-1 && -p == k)

    r = map fst . filter snd $ zip xs bs
      where
        bs = map (uncurry f) $ zip cs' (0:cs')

    write = do
      print $ (length r) `div` 2
      hPutBuilder stdout $ unwords_ $ map intDec r
      where unwords_ = mconcat . map (<> charUtf8 ' ')

  write

import Data.ByteString.Char8 (readInt, getLine, words, lines, getContents)
import Data.Maybe (fromJust)
import Data.List (sort)
import Prelude hiding (getLine, words, lines, getContents)

readInt' = fst . fromJust . readInt

main = do
  [_, k] <- (map readInt' . words) `fmap` getLine
  ps <- (map ((\[a, b] -> (a, b)) . map readInt' . words) .  lines) `fmap` getContents

  let
    r :: ([Int], [Int])
    r@(xs, cs) = unzip . sort . concat $ map (\(a, b) -> [(a, -1), (b, 1)]) ps
    cs' = map abs $ scanl1 (+) cs

    ls = map (\(x, _, _) -> x) . filter (\(x, c, c') -> c == k && c' == k-1) $ zip3 (tail xs) (tail cs') cs'
    rs = map (\(x, _, _) -> x) . filter (\(x, c, c') -> c == k-1 && c' == k) $ zip3 (tail xs) (tail cs') cs'

    ans = zip ls rs

  print $ length ans
  putStr . unlines $ map (\(l, r) -> show l ++ " " ++ show r) ans


Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving in for some time and finally he decided to build the house. The rest is simple: he should choose in which part of the garden to build the house. In the evening he sat at his table and drew the garden’s plan. On the plan the garden is represented as a rectangular checkered field n × m in size divided into squares whose side length is 1. In some squares Vasya marked the trees growing there (one shouldn’t plant the trees too close to each other that’s why one square contains no more than one tree). Vasya wants to find a rectangular land lot a × b squares in size to build a house on, at that the land lot border should go along the lines of the grid that separates the squares. All the trees that grow on the building lot will have to be chopped off. Vasya loves his garden very much, so help him choose the building land lot location so that the number of chopped trees would be as little as possible.

The first line contains two integers n and m (1 ≤ n, m ≤ 50) which represent the garden location. The next n lines contain m numbers 0 or 1, which describe the garden on the scheme. The zero means that a tree doesn’t grow on this square and the 1 means that there is a growing tree. The last line contains two integers a and b (1 ≤ a, b ≤ 50). Note that Vasya can choose for building an a × b rectangle as well a b × a one, i.e. the side of the lot with the length of a can be located as parallel to the garden side with the length of n, as well as parallel to the garden side with the length of m.

Print the minimum number of trees that needs to be chopped off to select a land lot a × b in size to build a house on. It is guaranteed that at least one lot location can always be found, i. e. either a ≤ n and b ≤ m, or a ≤ m и b ≤ n.

NoteIn the second example the upper left square is (1,1) and the lower right is (3,2).

import Control.Monad
import Data.List

readL :: String -> [Int]
readL = map read.words

-- main function
main = do
    [n, m] <- getLine >>= return.readL
    xs <- replicateM n getLine >>= return.map readL
    [a, b] <- getLine >>= return.readL
    print $ solve n m a b xs

solve n m a b xs = min
    ((minimum.concatMap (sums n a).transpose.map (sums m b)) xs)
    ((minimum.concatMap (sums n b).transpose.map (sums m a)) xs)

sums n a xs | a > n = [100000]
sums n a xs = sums' xs' ys [sum xs'] where
    xs' = reverse (take a xs)
    ys = drop a xs
    sums' _  []     acc = reverse acc
    sums' xs (i:is) acc = sums' (i:init xs) is ((head acc-last xs+i):acc)

import Control.Monad (liftM)
import Data.Array

type Matrix  =  Array (Int, Int) Int

solve :: (Int, Int) -> (Int, Int) -> Matrix -> Int
solve (n, m) (a, b) array
  | a <= n && b <= m && a <= m && b <= n  =  min ansAB ansBA
  | a <= n && b <= m  =  ansAB
  | a <= m && b <= n  =  ansBA
  | otherwise  =  undefined
  where
    ansAB  =  solve' (a, b)
    ansBA  =  solve' (b, a)
    solve' (a, b)  =  minimum [sum [array ! (i+di,j+dj) | di <- [1..a], dj <- [1..b]] | i <- [0..n-a], j <- [0..m-b]]

main :: IO ()
main  =  do
    ints  <-  liftM (map read . concatMap words . lines) getContents
    let [n, m]  =  take 2 $ ints
    let matrix  =  listArray ((1,1), (n,m)) . take (n*m) . drop 2 $ ints
    let [a, b]  =  take 2 . drop (n*m) . drop 2 $ ints
    print $ solve (n,m) (a,b) matrix

import Array
main = interact solve
solve input = output where
  inputs = map (map (read:: String -> Int)) $ map words $ lines input
  [n,m] = head inputs
  garden = array (1,n*m) $ zip [1..n*m] $ concat $ take n $ tail inputs
  [a,b] = last inputs
  gsum0 x y = sum [garden!((j-1)*m+i)|i<-[x..x+a-1],j<-[y..y+b-1]]
  gsum1 x y = sum [garden!((j-1)*m+i)|i<-[x..x+b-1],j<-[y..y+a-1]]
  sums = [gsum0 x y|x<-[1..m-a+1],y<-[1..n-b+1]] ++
         [gsum1 x y|x<-[1..m-b+1],y<-[1..n-a+1]]
  output = show $ minimum sums

import Control.Monad
import Data.List

readL :: String -> [Int]
readL = map read.words

-- main function
main = do
    [n, m] <- getLine >>= return.readL
    xs <- replicateM n getLine >>= return.map readL
    [a, b] <- getLine >>= return.readL
    print $ solve n m a b xs

solve n m a b xs = min
    ((minimum.concatMap (sums m b).transpose.map (sums n a)) xs)
    ((minimum.concatMap (sums n b).transpose.map (sums m a)) (transpose xs))

sums n a xs | a >= n = [100000]
sums n a xs = sums' xs' ys [sum xs'] where
    xs' = reverse (take a xs)
    ys = drop a xs
    sums' _  []     acc = reverse acc
    sums' xs (i:is) acc = sums' (i:init xs) is ((head acc-last xs+i):acc)