main = do
  [n,m] <- fmap (map read . words) getLine :: IO [Int]
  print $ length [ () | a <- [0 .. floor (sqrt $ fromIntegral n)]
                      , b <- [0 .. floor (sqrt $ fromIntegral m)]
                      , a^2 + b == n
                      , a + b^2 == m ]


main = interact $ show . solve . read

solve n | n <= 10 = 0
solve n | n < 20 = 4
solve 20 = 15
solve 21 = 4
solve n = 0


import Control.Applicative ((<$>))

data Offer = Offer { offerCost :: Integer
                   , offerVolume :: Integer
                   } deriving (Show, Eq, Ord)

doubleOffer :: Offer -> Offer
doubleOffer (Offer c v) = Offer (2 * c) (2 * v)

-- reverses the offer list
optimizeOffers :: Integer -> [Offer] -> [Offer]
optimizeOffers v = fillExtra v . optBwd . reverse . optFwd
  where
    optFwd (a:b:xs) = a : optFwd (min (doubleOffer a) b:xs)
    optFwd xs = xs

    optBwd (a@(Offer ca va):(Offer cb vb):xs) =
      a : optFwd (Offer (min cb ca) vb:xs)
    optBwd xs = xs

    fillExtra v (x:xs)
      | offerVolume x > v = (x:xs)
      | otherwise         = fillExtra v (doubleOffer x : x : xs)

optimizeCost :: Integer -> [Offer] -> Integer
optimizeCost left (Offer c v:xs)
  | left <= 0 = 0
  | null xs   = c
  | v <= left = c + optimizeCost (left - v) xs
  | otherwise = min c (optimizeCost left xs)

solve :: Integer -> [Offer] -> Integer
solve v xs = optimizeCost v (optimizeOffers v xs)

readIntegers :: IO [Integer]
readIntegers = fmap read . words <$> getLine

readOffers :: IO [Offer]
readOffers = build 1 <$> readIntegers
  where
    build _ [] = []
    build v (c:cs) = Offer c v : build (v * 2) cs

main = do
  [_, v] <- readIntegers
  offers <- readOffers
  print (solve v offers)


import Data.Int (Int64)
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

primes :: Integral a => [a]
primes = 2:3:rest
    where
    rest = filter isPrime $ chain [5,11..] [7,13..]
    chain (x:xs) (y:ys) = x:y:chain xs ys
    isPrime a = all (0 /=) . map (a `mod`) . takeWhile pred $ primes
        where pred x = x * x < a + 1

solve :: Int64 -> Int64 -> Int64
solve p q = loop (head a) n a m b
    where
    ispal a = d == reverse d
        where d = map (`mod` 10) . takeWhile (0 <) . iterate (`div` 10) $ a

    k = 1200000
    a = reverse . takeWhile (< k) $ primes
    b = reverse . filter ispal $ [1..k]
    n = fromIntegral . length $ a
    m = fromIntegral . length $ b

    loop 2 _ [] _ _ = 1
    loop prime i xs@(x:xs') j ys@(y:ys')
        | q * i < p * j + 1 = prime - 1
        | x < y = loop prime i xs (j - 1) ys'
        | y < x = loop x (i - 1) xs' j ys
        | otherwise = loop x (i - 1) xs' (j - 1) ys'

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = do
    [p, q] <- fmap fromIntegral . parse <$> B.getLine
    print $ solve p q


import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Int]
getIntList = map read <$> getStrList

main :: IO ()
main = do
    n <- readLn
    let {
        x = head . filter (\z -> n `mod` z == 0) $ [2..];
        y = n `div` x;
    } in putStrLn (show x ++ show y)


import Data.List

main :: IO()
main = do
  s <- getLine
  let n = length s
  print $ maximum $ (0:[ j - i + 1 | i <- [0..n - 2], j <- [i..n - 1], gao i j s ])
    where gao i j s = let sub = take (j - i + 1) $ drop i s in sub `isInfixOf` drop (i + 1) s


module Main where
main = interact $ solve . read

solve :: (Integral a) => a -> String
solve w
    | even w && w >= 4  =  "YES"
    | otherwise = "NO"


import Data.List
import Data.Array
import Data.Ord

isProg t = [a1,a2..alast]==t where
	(a1:a2:_)=t
	alast=last t

progr t = (last t)+d where
	(a1:a2:_)=t
	d=a2-a1

solve t
	|length t==2 = progr t
	|isProg t = progr t
	|otherwise = last t

main=do
	n<-fmap (\x->read x::Int) getLine
	t<-fmap (map (\x->read x::Int).take n.words)  $ getLine
	print $ solve t

{-
	fmap (map (\x->read x::Int).words)  $ getLine
-}


import qualified Data.Set as S
import Data.Array.IArray
import Data.List
data Color = R | O | Y | G | B | I | V deriving (Show, Eq, Ord, Enum)
f n = do
    let l' = [(0, S.singleton R)] ++
                [(i, S.fromList $ enumFrom O) | i <- [1..3] ++ [n-3..n-1]] ++
                [(i, S.fromList $ enumFrom R) | i <- [4..n-4]]
    f1 n (array (0, n-1) l':: Array Int (S.Set Color)) [R] 1

f1 n arr r i | i == n = if length (nub r) == 7 then return $ reverse r else fail ""
             | otherwise = do
        c <- S.toList $ arr ! i
        let arr' = (accum (flip S.delete) arr
                [((i+i') `mod` n, c) | i' <- ([-3..(-1)]++[1..3])]) // [(i, (S.singleton c))]
        f1 n arr' (c:r) (i+1)
main = do
    n <- read `fmap` getLine
    mapM (putStr.show) $ head $ f n


import Data.IntSet(IntSet)
import qualified Data.IntSet as IS

main = readLn >>= putStrLn.solve

solve :: Int -> String
solve n = if any (\x -> IS.member (n-x) tnumSet) tnumList
             then "YES" else "NO"
   where tnumList = takeWhile(<=n).map(\x->x*(x+1)`div`2)$[1..]
         tnumSet = IS.fromList tnumList


import Data.List
main :: IO ()
main = do
    n <- getLine
    input <- getLine
    let xs = map read (words input)
    putStrLn $ show $ solve xs
    return ()

{-solve :: [Int]->Int
solve xs
    |(length n ) == 1 =0
    |(length n ) == 2 =abs(n!!0 - n!!1)
    |(length n ) == 3 = let s = sort n in
                     if s!!0-s!!1==s!!1-s!!2 then s!!2-s!!1 else -1
    |otherwise =-1
    where n = nub xs-}
solve :: [Int]->Int
solve xs
    |(length n) == 1 =0
    |(length n) == 2 =if odd (abs(n!!0 - n!!1)) then abs(n!!0 - n!!1) else div (abs(n!!0 - (n!!1))) 2
    |(length n) == 3 = let s = sort n in
                     if s!!0-s!!1==s!!1-s!!2 then s!!2-s!!1 else -1
    | otherwise      = -1
    where n = nub xs


digitCount s = digitCount' s 0 where digitCount' s a = if s == 0 then a else digitCount' (s`div`10) (a+1)

addDigits a b = addDigits' a b 0
  where
    addDigits' 0 0 c = c
    addDigits' a b c = addDigits' (a`div`10) (b`div`10) (c+(a`mod`10)+(b`mod`10))

main = do
  n <-  getLine >>= return . (\x -> read x :: Integer)
  let tens = 10 ^ (digitCount n - 1)
      a = pred $ (*tens) $ (`div` tens) $ n
  print $ addDigits a (n-a)


import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Tuple

data Action = Ignore | Assign | Use deriving (Enum, Eq)

type Vertex = Int

type Graph = Array Vertex [Vertex]

reachable g vs = runST $ do
		bs <- newArray (bounds g) False :: ST s (STArray s Vertex Bool)
		mapM_ (search bs) vs
		getElems bs
	where
		search bs v = do
			b <- readArray bs v
			if b
				then return ()
				else do
					writeArray bs v True
					mapM_ (search bs) (g ! v)

getWords =  map (fst . fromJust . B.readInt) . B.words <$> B.getLine

build range edges = accumArray (flip (:)) [] range edges

solve actions edges =
		zipWith (&&) (reachable' g1 Assign) (reachable' g2 Use)
	where
		n = length actions
		actions' = listArray (1, n) actions

		reachable' g action = reachable g $ filter ((== action) . (actions' !)) [1..n]

		edges' = filter (\(i,j) -> actions' ! i /= Assign) $ map swap edges

		g1 = build (1, n) edges
		g2 = build (1, n) edges'

main = do
	[n, m] <- getWords
	actions <- map toEnum <$> getWords
	edges <- replicateM m $ (\[x, y] -> (x, y)) <$> getWords

	let r = solve actions edges
	mapM_ print $ map fromEnum r


sq x = p * p
	where p = x - 2
main = interact $ show . sq . read


{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
--import qualified Data.Vector as V
import qualified Data.Set as S
import Data.List
--import Debug.Trace
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

main = do
  [a,b,c] <- fmap (map read . words) getLine
  putStrLn $ if solve a b c then "YES" else "NO"

solve a b c
    | b == a = True
    | c == 0 = False
    | b >= a && c >= 0 = mod (b - a) c == 0
    | b >= a && c < 0 = False
    | b < a && c >= 0 = False
    | b < a && c < 0 = mod (a - b) (-c) == 0
    | otherwise = error "ASD"


isPrime 2 = True
isPrime x = and $ map (\i -> (x `rem` i) /= 0) (2:(takeWhile (\i -> (i*i) <= x) [3,5..]))
primes = 2:f [3] [3,5..]
         where f (x:xs) ys = let (ps,qs) = span (<x^2) ys
                             in ps ++ f (xs ++ ps) [z | z<-qs,mod z x /= 0]
main = do
  w0 <- getLine
  let n = read w0::Int
  if isPrime n
  then putStrLn $ "1\n"++(show n)
  else if isPrime (n-3)
       then putStrLn $ "2\n3 "++(show (n-3))
       else do
          let p = head [x|x <- primes,isPrime (n-x-3)]
          putStrLn $ "3\n3 "++(show p) ++ " " ++ (show (n-p-3))


{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}

main = do
  contents <- getContents
  let (a:b:c:d:e:f:_) = map read $ words contents
  print $ maximum [x * e + minimum [b, c, d - x] * f | x <- [0..min a d]]


import Data.List
import Control.Monad

main = do
    let solution [a,b,x,y] = let hcf = gcd x y
                             in  minimum $ zipWith div [a,b] $ map (`div`hcf) [x,y]
        int x =  read x ::Integer
    as <- getLine >>=  return . take 4 . map int . words
    print $ solution as


import Control.Monad
import qualified Data.Set as Set

toTuples xs = map (\[a,b] -> (a,b)) xs

buildSet :: [Int] -> [Int] -> Set.Set (Int,Int)
buildSet xs ys = let mp = (mx,my)
                          where mx = xs !! 1
                                my = ys !! 1
                     fset = [(a,b) | a <- xs, b <- ys, (a,b) /= mp]
                 in Set.fromList fset

check pts = let pset = Set.fromList pts
                xset = Set.toList $ Set.fromList $ map (\(a,b) -> a) pts
                yset = Set.toList $ Set.fromList $ map (\(a,b) -> b) pts
            in if (length xset /= 3) || (length yset /= 3)
               then False
               else pset == buildSet xset yset

main = do
         points <- forM [1..8] (\a -> do
                   st <- getLine
                   return (map (\w -> (read w :: Int)) $ words st))
         if check $ toTuples points then putStrLn "respectable"
         else putStrLn "ugly"


main = do
  s <- getLine
  print $ (fromEnum $ last s `elem` "13579" :: Int)


main = do
	d<-getLine
	let [a,b]= map read $ words d
	putStrLn $ show $ solve a b 0

solve::Integer->Integer->Integer->Integer
solve a b acc
  | a==b || b<=0 = acc
  | otherwise = solve (ma) (mi) (acc+div a b)
  where ma = max b (a-d*b)
        mi = min (a-d*b) b
        d = div a b


main = interact $ show . solve . read
solve n | odd n = 0
        | otherwise = 2 ^ (n `div` 2)


main =do
      e<-getLine
      e2<-getLine
      let n=read e::Integer
          (x:y:[])=map read (words e2)::[Integer]
          a=max (y-1) (x-1)
          b=max (n-y) (n-x)
      putStrLn $ if a<=b then "White" else "Black"


import List

main = do
	n <- fmap read getLine
	putStrLn $ show' $ null $ ([0 .. n - 1]\\) $ take (n+n) $ map (`mod` n) $ scanl1 (+) [0 ..]

show' True = "YES"
show' False = "NO"


main=interact$unwords.map show.f.map read.words
f(n:m:bs)=foldl step (replicate n 0) bs
   where
     step xs x = ys ++ (zeros>>[x]) ++ ws
      where
        (ys,zs) = splitAt(x-1)xs
        (zeros,ws) = span (0==) zs


module Main where

import Control.Applicative
import Control.Monad
import Data.List
import qualified Data.Map as M

type Airport = String
type Ticket = (Airport, Airport)
data Result = Home | Contest deriving (Show)

solve :: String -> [Ticket] -> Result
solve home tickets = if location == home then Home else Contest
    where update balance (from, to) = addTo to . addFrom from $ balance
          addFrom from balance = M.insertWith (+) from (-1) balance
          addTo to balance = M.insertWith (+) to 1 balance

          cities = zip (concatMap (\(f, t) -> [f, t]) tickets) (repeat 0)
          base = M.fromList $ cities ++ [(home, 1)]
          balance = foldl' update base tickets

          location = fst . head . filter ((== 1) . snd) $ M.toList balance

main :: IO ()
main = do
  n <- read <$> getLine
  home <- getLine
  tickets <- replicateM n $ do
               ticket <- getLine
               return (take 3 ticket, drop 5 ticket)
  case (solve home tickets) of
    Home -> putStrLn "home"
    Contest -> putStrLn "contest"


main = fmap (map read . words) getLine >>= print . solve
solve [k,n,w] = max 0 $ k*w*(w+1) `div` 2 - n


import Data.List
import Data.Char

main :: IO ()
main = do
    cubes <- getContents >>= return . map (map read) . map words . drop 1 . lines
    let Just ans =  findIndex (==False) $ map (makeNum cubes) $ map show [1, 2..]
    print ans

makeNum :: [[Int]] -> String -> Bool
makeNum _ "" = True
makeNum [] _ = False
makeNum cubes (d:ds) = any tryEachCube [0, 1..length cubes - 1]
    where
    tryEachCube :: Int -> Bool
    tryEachCube i = (ord d - ord '0') `elem` (cubes !! i) && makeNum (deleteAt i cubes) ds

deleteAt :: Int -> [a] -> [a]
deleteAt pos xs = let (ms, ns) = splitAt pos xs in ms ++ tail ns


module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

  readInt :: String -> Int
  readInt s = read s :: Int

  readInteger :: String -> Integer
  readInteger s = read s :: Integer

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  -- data Point = Point { x :: Int, y :: Int } deriving (Ord, Eq)
  couldWin :: Char -> String -> Bool
  couldWin x (a:b:'.':_) = x == a && x == b
  couldWin x (a:'.':b:_) = x == a && x == b
  couldWin x ('.':a:b:_) = x == a && x == b
  couldWin x _ = False

  lineCouldWin :: Char -> String -> Bool
  lineCouldWin a (x:xs) = couldWin a (x:xs) || couldWin a xs

  diagonalCouldWin :: Char -> [String] -> Bool
  diagonalCouldWin c [(x1:x2:x3:_), (y1:y2:y3:_), (z1:z2:z3:_)]
    | x1 == '.' && y2 == z3 && c == y2 = True
    | x3 == '.' && y2 == z1 && c == y2 = True
    | z1 == '.' && y2 == x3 && c == y2 = True
    | z3 == '.' && y2 == x1 && c == y2 = True
    | y2 == '.' && x1 == z3 && c == x1 = True
    | y2 == '.' && x3 == z1 && c == x3 = True
    | otherwise = False

  yesNo :: Bool -> String
  yesNo True = "YES"
  yesNo _ = "NO"

  to3x3 :: [String] -> [[String]]
  to3x3 (a:b:c:d:_) = [
          map (take 3) (a:b:c:[]),
          map (take 3) (b:c:d:[]),
          map (drop 1) (a:b:c:[]),
          map (drop 1) (b:c:d:[])
        ]

  main :: IO()
  main = do
    tics <- readMultilineInput 4 return
    let alltics = intercalate [] tics
        ticsAlter = transpose tics
        playCount = length $ filter (=='.') alltics
        diagonals = to3x3 tics
        c = case playCount `mod` 2 of
              0 -> 'x'
              1 -> 'o'
        result1 = any (lineCouldWin c) tics
        result2 = any (lineCouldWin c) ticsAlter
        result3 = any (diagonalCouldWin c) diagonals
    -- print $ c
    -- print $ map (lineCouldWin c) tics
    -- forM_ ticsAlter print
    -- print $ map (lineCouldWin c) ticsAlter
    putStrLn $ yesNo $ result1 || result2 || result3


module Main where

import Control.Monad

type A2D = [(Int, Int)]

cnt :: Int -> Int -> Int -> Int -> A2D -> Int
cnt i1 j1 i2 j2 a = length $ do
	x <- [i1..i2]
	y <- [j1..j2]
	guard $ (x, y) `elem` a
	return (x, y)

solve :: Int -> Int -> Int -> Int -> A2D -> Int
solve r c n k a = length $ do
	i1 <- [1..r]
	j1 <- [1..c]
	i2 <- [i1..r]
	j2 <- [j1..c]
	guard $ (cnt i1 j1 i2 j2 a >= k)
	return ()

tuplify2 :: [a] -> (a, a)
tuplify2 [x, y] = (x, y)

tuplify4 :: [a] -> (a, a, a, a)
tuplify4 [x, y, z, w] = (x, y, z, w)

readInts :: [String] -> [Int]
readInts = map read

readMusicians :: [String] -> A2D
readMusicians = map (\x -> tuplify2 . readInts $ words x)

parse :: String -> String
parse x = do
	let (l:ls) = lines x
	let (r, c, n, k) = tuplify4 . readInts . words $ l
	let music = readMusicians ls
	show $ solve r c n k music

main = interact $ parse


main = do
    [n,k] <- (map read).words <$> getLine
    print $ n + (n + 1) + (n - 1) + (min (k-1) (n-k))


calcRes :: [Integer] -> [Integer] -> Integer
calcRes (m:n:_) (x:y:z:_) = (max 0 (2 * x + y - m)) + (max 0 (3 * z + y - n))
calcRes _ _ = 0

readInts :: IO [Integer]
readInts = fmap (map read.words) getLine

main = do
    a <- readInts
    b <- readInts
    putStrLn . show $ calcRes a b


digs :: Integer -> [Integer]
digs 0	= []
digs n	= digs (n `quot` 10 ) ++ [n `rem` 10]

isLucky :: Integer -> Bool
isLucky n = (length . filter (\x -> x == 4 || x == 7) . digs $ n) == (length . digs $ n) && (length . digs $ n) /= 0

answer :: Integer -> String
answer n
	| isLucky $ foldl (\acc x -> if x == 4 || x == 7 then acc + 1 else acc) 0 (digs n) = "YES"
	| otherwise  = "NO"

main :: IO()
main = do
    [n] <- (map read . words) `fmap` getLine
    putStrLn $ answer n


-- -*- compile-command: "ghc -o main -O specialolympics.hs" -*-
import System.IO
import Data.List
import Data.Char
import qualified Data.ByteString.Char8 as SS

readDouble :: String -> Double
readDouble = read

validCircle :: (Double, Double, Double) -> Double -> Bool
validCircle (a,r,rr) d
  | r >= d+a = True
  | rr+d <= a = True
  | d >= a+rr = True
  | otherwise = False

validCircles :: Double -> [(Double,Double,Double)] -> Int
validCircles d ls = foldl helper 0 ls
  where helper c x = case validCircle x d of
                   True -> c+1
                   False -> c

main = do
     (x1:y1:r1:rr1:_) <- (map readDouble . words) `fmap` getLine
     (x2:y2:r2:rr2:_) <- (map readDouble . words) `fmap` getLine
     let d = sqrt $ (x1-x2)^2+(y1-y2)^2
     print $ validCircles d [(r1,r2,rr2),(rr1,r2,rr2),(r2,r1,rr1),(rr2,r1,rr1)]


readInts :: IO [Int]
readInts = map read . words <$> getLine

main :: IO ()
main = do
  n <- read <$> getLine
  [a1, a2, a3] <- readInts
  [b1, b2, b3] <- readInts
  let
    s1 = min a1 b2
    s2 = min a2 b3
    s3 = min a3 b1
    maxScore = s1 + s2 + s3
    t1 = max 0 $ a1 + b2 - n
    t2 = max 0 $ a2 + b3 - n
    t3 = max 0 $ a3 + b1 - n
    minScore = t1 + t2 + t3
  putStrLn . unwords $ map show [minScore, maxScore]


import Data.Functor
import Data.List

main :: IO ()
main = do
  [n, a, b] <- map read . words <$> getLine
  putStrLn . show $ (n * 100 + a + b - 1) `mod` n + 1


nextSimple :: Int -> Int
nextSimple n0 = head (filter (\n -> length (filter (\m -> mod n m == 0) [1..n]) == 2) [(n0+1)..])

solve :: Int -> Int -> String
solve n m = if m == nextSimple n then "YES" else "NO"

main = do
    s <- getLine
    let [n, m] = map (read::(String -> Int)) (words s)
    putStr (solve n m)


import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST

main = interact $ output . solve . map read . words

output :: Bool -> String
output True = "YES"
output _ = "NO"

solve :: [Int] -> Bool
solve [n,k] = let pr = primes n in (>=k) . length . filter (==True) . map (flip elem pr . (+1)) $ zipWith (+) pr (tail pr)

primes :: Int -> [Int]
primes = fst . unzip . filter ((==0) . snd) . assocs . sieve

sieve :: Int -> Array Int Int
sieve n = runSTArray build
		where build :: ST s (STArray s Int Int)
		      build = newArray (2,n) 0 >>=
					  \arr -> forM_ (takeWhile (\x -> x*x <= n) [2..n]) (\i -> readArray arr i >>=
					  \p -> if p == 0
						    then forM_ [i*i,(i+1)*i..n] (\j -> writeArray arr j 1)
							else return ()) >> return arr


main = do
  x <- read `fmap` getLine :: IO Integer
  putStrLn $ show $ solve x

solve :: Integer -> Integer
solve x
  | x `mod` 5 /= 0  = x `div` 5 + 1
  | otherwise = x `div` 5


main = do
	n <- getLine
	stones <- getLine
	let res = foldl (\prev i -> if stones !! i == stones !! (i - 1)
								then prev + 1
								else prev) 0 [1..length stones - 1]

	putStrLn $ show res


import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe

main = do
		[x,y,z,t1,t2,t3]<- map read <$> words <$> getLine::IO [Int]
		let w = abs(x-y) * t1
		let e = abs(z-x) *t2 + t3+t3 + t2 * abs (x-y) +t3
		putStrLn $ if e>w then "NO" else "YES"


main = interact $ solve . read
solve n = case n `mod` 4 of 0 -> "1 A"
                            1 -> "0 A"
                            2 -> "1 B"
                            3 -> "2 A"


import Data.List
import Data.Array
import Data.Ord
import Data.Char

rd x = read x::Integer
getNumbers=map rd.words
extract (x:xs)=map rd $ take (read x::Int) xs

solve x
	|length num==2 && half x= unlines ["YES",unwords [show (num!!0),show (num!!1)]]
	|otherwise = "NO"
	where
		num = nub x
		half x = length (filter (==num!!0) x) == length (filter (==num!!1) x)

main=interact$solve.extract.lines


import Prelude hiding (sqrt)

sqrt :: Int -> Int
sqrt n  =  head $ [x | x <- [0..], x*x == n]

solve :: [Int] -> Int
solve [ab, ac, bc]  =  4 * (a + b + c)
  where
    a  =  sqrt (div (ab*ac) bc)
    b  =  div ab a
    c  =  div ac a

main :: IO ()
main  =  fmap (map read . words) getLine >>= print . solve


main :: IO ()
main = interact $ show . solve . map read . words

solve :: [Int] -> Int
solve (w1:h1:w2:h2:_) = 4+2*(h1+h2)+2*w1


import Control.Applicative
import Control.Monad
import Data.List
import Data.Monoid
import Data.Maybe

main :: IO ()
main = do
  n <- readLn
  print $ (!! (n-1)) [1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0]


import Data.List
main = interact $ show . solve . map read . words
solve (n:as) = max b (n-a-1) where
  [a,b] = findIndices (`elem` [1,n]) as


import Data.Array

maxn = 1000 :: Integer

primes' :: Integer -> Array Integer Bool -> [Integer]
primes' n outside
    | n-1 >= maxn = []
    | outside ! n = primes' (n+1) outside
    | otherwise   = n : primes' (n+1) outside'
    where
        outside' = outside // (map (\i->(i,True)) [n,2*n..maxn])
primes :: [Integer]
primes = primes' 2 $ listArray (2,maxn) (repeat False)

primefacs' :: [Integer] -> Integer -> [Integer]
primefacs' [] _ = []
primefacs' pps@(p:ps) i
    | mod i p == 0 = p : primefacs' pps (div i p)
    | otherwise    = primefacs' ps i
primefacs :: Integer -> [Integer]
primefacs i = primefacs' primes i

solve' ::  Integer -> [Integer] -> [Integer]
solve' mult factormult
    | null factormult || (mult-1)*nextprime < nmult = factormult ++ [mult]
    | otherwise = nfactormult
    where
    nextprime = primes !! length factormult
    nmults = map (\(expo,pri) -> pri^(expo*mult - expo)) (zip factormult primes)
    (nmult,primeindx) = minimum (zip nmults [0..])
    (prevs,curr:nxts) = splitAt primeindx factormult
    nfactormult = prevs ++ (curr*mult):nxts

solve :: Integer -> Integer
solve i = let
    expos = foldr solve' [] (primefacs i)
    in product $ zipWith (\a b -> a^(b-1)) primes expos

main :: IO ()
main = do
    i <- readLn :: IO Integer
    print $ solve i

{-
La cantidad de divisores de un número es la cantidad de formas que se tienen de tomar un multiconjunto diferente de sus factores primos, para cada factor primo, si se repite k veces, se pueden tomar k+1 veces de maneras diferentes, así, por ejemplo:

40 = 2^3 * 5^1  tiene  (3+1)*(1+1)  divisores.

Si se quiere un número con n divisores, n se descompone en sus factores primos de menor a mayor, luego, se debe encontrar un conjunto de exponentes de factores primos de manera que los sucesores de estos exponentes, multiplicados, den n.

De forma voraz, se va construyendo el menor número m con dicha cantidad de factores primos, operando con el siguiente factor primo r de n. Lo que hace es ver qué aumenta menos el número m, si modificar uno de los exponentes de su descomposición en factores primos, de manera que la cantidad de veces que se pueda tomar sea r veces más o agregar el siguiente factor primo con un exponente r - 1.

Luego se calcula el número m.

-}


import List
myhead ::[[Int]] -> [Int]
myhead [] = []
myhead a = head a
hasNotSame ::[Int] -> Bool
hasNotSame a = length(nub a)==(length a)
getAns ::[Int] -> [Int]
getAns [r1,r2,c1,c2,d1,d2] = myhead [[x,y,w,z]|x<-[1..9],y<-[1..9],w<-[1..9],z<-[1..9],hasNotSame[x,y,w,z],r1 == (x+y),r2 == (w+z),c1 == (x+w),c2 ==(y+z),d1==(x+z),d2==(y+w)]
toS ::[Int]->String
toS [] = "-1"
toS [x,y,w,z] = concat [(show x)," ",(show y),"\n",(show w)," ",(show z) ]
main=interact$toS.getAns.map read.words


import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
-- import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = map (read . B.unpack) . B.words <$> B.getLine
getIntList :: IO [Int]
getIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

solve :: [[Int]] -> Int
solve a = length [() | i <- a, j <- a, head i == j !! 1]

main :: IO ()
main = do
        n <- read <$> getLine
        a <- replicateM n getIntList
        print $ solve a


-- import Debug.Trace

-- cubes n i cnt
--   | n < cnt = trace (show cnt) i
--   | otherwise = trace ("cnt  " ++ (show cnt) ++ "   i  " ++ (show i)) cubes n (i+1) (cnt + sq i 0 0)

-- sq n ind ret
--   | n == ind = ret
--   | otherwise = trace ("\n" ++ (show ret)) sq n (ind + 1) (ret + ind)

cubes n i cnt
  | n < cnt = i
  | otherwise = cubes n (i+1) (cnt + sq i 0 0)

sq n ind ret
  | n == ind = ret
  | otherwise = sq n (ind + 1) (ret + ind)

main = do
  ff <- getLine
  let ss = (read ff)::Int
      ans = cubes ss 0 0
  putStrLn (show (ans-3))


n (y:x:_) = [((y + ((x + 1) `div` 60)) `mod` 24), ((x + 1) `mod` 60)]
c :: Int -> Int
c x = ((x `mod` 10) * 10) + (x `div` 10)
ok :: [Int] -> Bool
ok (y:x:_) = y == (c x)
s x = (show (x `div` 10)) ++ (show (x `mod` 10))
p (x:y:_) = (s x) ++ ":" ++ (s y)
main = do
  s <- getLine
  let s3 = read (take 2 s) :: Int
  let s4 = read (reverse . (take 2) . reverse $ s) :: Int
  putStrLn $ p $ head $ filter ok $ tail $ iterate n [s3, s4]


module Main where

import Control.Applicative
import Data.List

rest = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leaps = 31 : 29 : rest
ordinary = 31 : 28 : rest

months = ordinary ++ ordinary ++ leaps ++ ordinary ++ ordinary

substrings :: [a] -> Int -> [[a]]
substrings as n = filter ((== n) . length) . map (take n) $ tails as

solve :: [Int] -> Bool
solve ds = case find (== ds) (substrings months n) of
             Just _ -> True
             _      -> False
    where n = length ds

test0 = [31, 31, 30, 31] :: [Int]
test1 = [30, 30] :: [Int]

main :: IO ()
main = do
  _ <- getLine
  ds <- map read . words <$> getLine
  putStrLn $ if solve ds then "Yes" else "No"


-- hm i'm not sure how to rigorously prove this solution. basically you expand the fraction to continued fraction and take all the pluses (and the last denominator).
-- like 43/30 = 1 + 1 / (2 + 1 / (3 + 1 / 4)) -> 1+2+3+4 = 10. indeed "43 30" gives output "10".
computeResult :: (Integer, Integer) -> Integer
computeResult (_, 0) = 0
computeResult (a, b) = (+) (div a b) (computeResult (b, mod a b))

-- ok i lied a bit. this function also swaps the arguments if the first is smaller. but it's still handle input blargh whatever
handleInput :: [String] -> (Integer, Integer)
handleInput (x:y:[]) = let a = read x; b = read y in if (a < b) then (b, a) else (a, b)

-- the main function just so i can test it without resorting to cygwin and compiling the function
mainFunction :: String -> String
mainFunction = show . computeResult . handleInput . words

-- the "actual" main function which handles all the IO stuff
main = do
    s <- getLine
    putStrLn $ mainFunction s


{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign hiding (newArray)
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array.Base hiding ((!))
import Data.Array
import Data.Char
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int64 where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

sieve :: Int64 -> UArray Int64 Bool
sieve n = runSTUArray $ do
            t <- newArray (0,n) True
            unsafeWrite t 0 False
            unsafeWrite t 1 False
            mapM_ (\i -> unsafeWrite t i False) [4,6..fromIntegral n]
            let sqn = (floor.sqrt.fromIntegral) (n::Int64)
            mapM_ (\i -> (mapM_ (\j -> unsafeRead t i>>=(flip when) (unsafeWrite t j False)) [i*i,i*(i+2)..fromIntegral n])) [3,5..sqn]
            return t

isPrime n = if n==2 then True else let sqn = ceiling.sqrt.fromIntegral $ n in all (\x -> mod n x /= 0) (2:[3,5..sqn])

solve :: Int64 -> String
solve n | trace (show n) True = if n==1 || isPrime n then "1\n0" else if null l then "2" else "1\n"++(show.(\(a:b:_) -> a*b) $ l)
    where
      sqn = ceiling.sqrt.fromIntegral $ n
      sve = sieve sqn
      l = rec 0 n 2 []
      rec counter m i l = if counter == 2 then l
                          else
                              if i>=sqn then []
                              else
                                  if sve UB.! i then
                                      if mod m i == 0 then
                                          rec (counter+1) (div m i) i (i:l)
                                      else
                                          rec counter m (i+1) l
                                  else
                                      rec counter m (i+1) l

main = (scan :: IO Int64) >>= putStrLn.solve


module Main where

import Data.Maybe
import Data.Array
import Data.List
import Data.Char

import Data.Time.Calendar

main = interact (show . solve . map read . words)

solve :: [Int] -> Int
solve (a : x : y : _) = if got then aim else -1 where
    got = if y `mod` a == 0
        then False
        else if y < a
            then hitOne a x
            else let y' = (y - a) `mod` (2 * a) in
                (y' < a && hitOne a x) || (a < y' && hitTwo a x)

    aim = number a x y

hitOne :: Int -> Int -> Bool
hitOne a x = -a < 2 * x && 2 * x < a

hitTwo :: Int -> Int -> Bool
hitTwo a x = (-a < x && x < 0) || (0 < x && x < a)

number :: Int -> Int -> Int -> Int
number a x y = if y < a
    then 1
    else 1 + number' a x (y - a)
number' a x y = 3 * (y `div` (2 * a)) + amongThree a x (y `mod` (2 * a))

amongThree a x y = if y < a
    then 1
    else if x < 0
        then 2
        else 3


p x=x`div`4*2+min(x`mod`4)2
s[n,m]=maximum[p n*p m,m,n,(n*m+1)`div`2]
main=interact$show.s.map read.words


main=interact$show.f.map read.words
f(n:x)=sum[1|i<-[1..5],(i+sum x)`mod`(n+1)/=1]


import Data.List
main = interact $ show . solve . map read . tail . words
solve as = sum ps - sum ns
  where (ps,ns) = partition (>= 0) as


check s =
  go 'a' s
  where go c "" = "YES"
        go c (x:xs) = if c == x
                      then go (succ c) (filter (/= c) xs)
                      else "NO"

main = do
   s <- getLine
   putStrLn $ check s


-- Codeforces 865A

import Control.Applicative

main :: IO ()
main = do
    x <- read <$> getLine :: IO Int
    putStrLn $ show (2 * x - 1) ++ " " ++ "2"
    putStrLn "1 2"


import List
import Maybe
main = interact solve
solve input = output where
  inputs = sort $ zip ( lines input ) "FMS"
  i0 = map fst inputs
  output
    | i0 == ["paper","rock","rock"]       = [fromJust $ lookup "paper" inputs]
    | i0 == ["paper","paper","scissors"]  = [fromJust $ lookup "scissors" inputs]
    | i0 == ["rock","scissors","scissors"] = [fromJust $ lookup "rock" inputs]
    | otherwise                           = "?"


main = print . solve . map read . words =<< getLine
solve [n,a,b] = min (n-a) (b+1)


{-# LANGAGE BangPatterns #-}

import Data.Int
import Data.List

powers2 = 1 : (map (*2) powers2)

solve :: String -> Int64
solve xs = foldl' go 0 (zip xs powers2)
  where
    go a ('B',p) = a+p
    go a ('R',p) = a

main = do
  n <- read `fmap` getLine
  line <- (take n) `fmap` getLine
  print $ solve line


import System.IO
import Data.Char
import Data.Int (Int64)
import Data.List
import qualified Data.Set as S

divisores :: Int64 -> [Int64]
divisores b = loop 2 b
  where
    loop n b | n*n > b = [b]
                  | n*n == b = [n, b]
                  | b `mod` n == 0 = (n:(b `div` n):result)
                  | otherwise = result
      where result = loop (n+1) b

main= do
    line <- getLine
    let b = (read line :: Int64)
    print $ length (S.fromList(1:divisores b))


main = do
  [h1, h2] <- fmap (map read . words) getLine :: IO [Int]
  [a, b] <- fmap (map read . words) getLine

  let
    find d h
      | h <= h2 && h2 <= h + (22-14)*a = d
      | h' <= h2 && h2 <= h' + (14-10)*a = d+1
      | h'' <= h = -1
      | otherwise = find (d+1) h''
      where
        h' = h + (22-14)*a - 12*b
        h'' = h' + (14-10)*a

  print $ find 0 h1


main=do n<-readLn;print.head$[x::Integer|x<-[max(r n-99)1..r n],x*(x+sum[read[c]|c<-show x])==n]++[-1]
r=floor.sqrt.fromIntegral


main = do
    lines <- sequence [getLine,getLine]
    let a = read (lines !! 0) :: Int
        b = read (lines !! 1) :: Int
    if a < 31
    then
        putStrLn $ show $ b `mod` (2^a)
    else
        putStrLn $ show b


import Data.List

main :: IO ()
main = print . minimum . zipWith (\x y -> y `div` x) [1, 1, 2, 7, 4] . map read . words =<< getLine


main = interact $ show . solve . read
solve n = (n+1) `div` 2 - 1


main :: IO ()
main =
    do cs <- getContents
       (putStr.show.solve.parseIn) cs

parseIn::String->Int
parseIn = read.head.lines

solve::Int->Int
solve i = divlistCps i 2 i
    where
      divlistCps n k ret =
          if (n==1)
          then
              ret
          else
              if ((mod n k) == 0)
              then
                  divlistCps (div n k) k ((div n k)+ret)
              else
                  divlistCps n (if (k==2) then 3 else k+2) ret


import Data.Char

getInt :: IO Int
getInt = do
  line <- getLine
  return (read line :: Int)

main = do
  n <- getInt
  let x = div n 3
  let y = mod n 3
  let z = if y == 2 then x + 1 else x
  let w = div z 12
  let v = mod z 12
  print w
  print v


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

import Debug.Trace

parseInput = do
    limit <- (,) <$> readInteger <*> readInteger
    k <- readInt
    from <- (,) <$> readInteger <*> readInteger
    to <- (,) <$> readInteger <*> readInteger
    return (limit, k, from, to)
  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 = print =<< solve . evalState parseInput <$> BS.getContents

add0 len str | length str > len = replicate len 'F'
add0 len str | length str < len = replicate (len - length str) '0' ++ str
add0 len str = str

maxn = 16 :: Int

solveCase (h, m) k (h', m') = searchH (0, False, False, 0, 0)
  where
    hUpper = listArray (0, hLen - 1) $ map digitToInt $ show (h - 1) :: UArray Int Int
    mUpper = listArray (0, mLen - 1) $ map digitToInt $ show (m - 1) :: UArray Int Int

    hUpper' = listArray (0, hLen - 1) $ map digitToInt $ add0 hLen $ show h' :: UArray Int Int
    mUpper' = listArray (0, mLen - 1) $ map digitToInt $ add0 mLen $ show m' :: UArray Int Int

    hLen = length $ show (h - 1)
    mLen = length $ show (m - 1)

    searchH :: (Int, Bool, Bool, Int, Int) -> Integer
    searchH = (cache!)
      where
        bnds = ((0, False, False, 0, 0), (maxn, True, True, maxn, maxn))
        cache = listArray bnds $ map go $ range bnds :: Array (Int, Bool, Bool, Int, Int) Integer

        go (pos, ltH, ltH', consec9, count0) | pos < hLen = sum lst
          where
            lst = [ searchH ( pos + 1
                            , ltH || digit < (hUpper ! pos)
                            , ltH' || digit < (hUpper' ! pos)
                            , if digit == 9 then consec9 + 1 else 0
                            , count0 + if digit == 0 then 1 else 0
                            )
                  | digit <- [0..9]
                  , ltH || digit <= (hUpper ! pos)
                  , ltH' || digit <= (hUpper' ! pos)
                  ]

        go (pos, ltH, ltH', consec9, count0)
            | not ltH   = searchM (0, (False, ltH'), 0, 0, hLen - count0)
            | otherwise = searchM (0, (False, ltH'), 0, 0, consec9 + 1)

    searchM :: (Int, (Bool, Bool), Int, Int, Int) -> Integer
    searchM = (cache!)
      where
        bnds = ((0, (False, False), 0, 0, 0), (maxn, (True, True), maxn, maxn, maxn))
        cache = listArray bnds $ map go $ range bnds :: Array (Int, (Bool, Bool), Int, Int, Int) Integer

        go (pos, (ltM, ltM'), consec9, count0, changeH) | pos < mLen = sum lst
          where
            lst = [ searchM ( pos + 1
                            , (ltM || digit < (mUpper ! pos) , ltM' || digit < (mUpper' ! pos))
                            , if digit == 9 then consec9 + 1 else 0
                            , count0 + if digit == 0 then 1 else 0
                            , changeH
                            )
                  | digit <- [0..9]
                  , ltM || digit <= (mUpper ! pos)
                  , ltM' || digit <= (mUpper' ! pos)
                  ]

        go (pos, (ltM, ltM'), consec9, count0, changeH)
            | not ltM'  = 0
            | not ltM   = if mLen - count0 + changeH >= k then 1 else 0
            | otherwise = if consec9 + 1 >= k then 1 else 0

solve (limit, k, from, to)
    | from <= to = count to - count from
    | otherwise  = (count limit - count from) + count to
  where
    count = solveCase limit k

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

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


answer = [1, 3, 15, 133, 2025, 37851, 1030367, 36362925]

solve :: Int -> Integer
solve n = if n `mod` 2 == 0
          then 0
          else answer !! (n `div` 2) * product [1..fromIntegral n] `mod` (1000000000 + 7)

main = interact work where
    work = show . solve . (\x -> read x :: Int)


main=putStrLn.slv.map read.words=<<getLine
slv (0:_) = "YES"
slv [x,t,a,b,da,db]
 |or [(a - n*da + b - m*db == x) || a - n*da == x || b - n*db == x
        |  n <- [0..t-1], m <- [0..t-1]] = "YES"
 | True = "NO"


import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array

check y = (length y) == (length ( group ( sort y)))

process a b | x==[] = "-1"
	    | otherwise = head x
	where x = take 1 $ filter check $ map show [a..b]

main::IO ()
main=do
  [a,b]<-  map read <$> words <$> getLine::IO [Int]
  putStrLn $ process a b


import Data.List

main = getLine >> getLine >>= putStrLn . solve

solve [x] = [x]
solve (x:y:xs)
    | isvowel x && isvowel y = solve (x:xs)
    | otherwise = x : solve (y:xs)
    where isvowel = (`elem` "aeiouy")


module Main (main) where

looser :: [(a, Int)] -> Int -> a
looser participans s = fst $ head $ filter ((< 0). snd) $ history $ concat $ repeat participans
  where history x = zip (fmap fst x) $ tail $ scanl step s $ fmap snd x
        step a x  = a - gcd x a

main :: IO ()
main = do cont <- getContents
          let [a, b, n] = fmap read $ words cont
          print $ looser [(1, a), (0, b)] n


main = getContents >>= print . solve 0 1 . map read . words

solve ans c (a:b:_)
  | b < a = solve ans c (b:a:[])
  | a == b = ans
  | b - a == 1 = ans + c
  | otherwise = solve (ans + 2 * c) (c + 1) (a + 1 : b - 1 :[])


main = getLine >>= putStrLn . solve . map read . words

solve [n,a,b]
    | b < a = answer (solve' [0,n,b,a]) $ log2 n
    | otherwise = answer (solve' [0,n,a,b]) $ log2 n
    where log2 1 = 0
          log2 n = 1 + (log2 $ n `div` 2)
          solve' [m,n,a,b]
              | middle < a = solve' [middle,n,a,b]
              | middle >= b = solve' [m,middle,a,b]
              | otherwise = log2 $ n - m
              where middle = (m + n) `div` 2
          answer a b
              | a == b = "Final!"
              | otherwise = show a


import Control.Applicative
import Data.List

main= do
	s<-getLine
	let sh = read $ take 2 s ::Int
	let sm = read $ drop 3 s ::Int
	t<-getLine
	let th = read $ take 2 t ::Int
	let tm = read $ drop 3 t ::Int
	let qm = mod (sm-tm) 60
	let qh = mod ((sh-th)   - (if tm>sm then 1 else 0)) 24
	let ans1 = if qh <10 then '0':(show qh) else show qh
	let ans2= if qm <10 then '0':(show qm) else show qm
	putStrLn $ ans1++":" ++ ans2


import Data.List

solve n = head [x | x<-[n+1..], length (nub (show x))==4]

main = do
	n<-getLine
	putStrLn $ show $ solve (read n)


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Data.Ord
import Text.Printf

main :: IO ()
main = do
  let readData :: IO [Integer]
      readData = map read . words <$> getLine
  n : m : s : _ <- readData
  let a = (n - 1) `rem` s + 1
      b = (m - 1) `rem` s + 1
      c = (n - 1) `quot` s + 1
      d = (m - 1) `quot` s + 1
      answer = a * b * c * d
  printf "%d\n" answer


--import Control.Monad.ST
--import Data.Array.ST
import Control.Monad(liftM)

swaps :: Int -> String -> String
swaps _ [] = []
swaps 0 a = a
swaps k a = minc: swaps (k - kmin) after
    where
        kmin = negate $ snd $ maximum $ take (k + 1) $ zip a [0,-1..]
        after = take kmin a ++ drop (kmin + 1) a
        minc = a !! kmin

main :: IO ()
main = do
    [as, ks] <- words `liftM` getLine
    let k = read ks :: Int
    putStr $ swaps k as


main = getLine >> getLine >>= print . minimum . map solve . rotations . map read . words
  where
  solve = minimum . map (\s -> abs $ (360 :: Int) - 2 * s) . scanl1 (+)
  rotations xs = take (length xs) $ iterate (\(x:xs) -> xs ++ [x]) xs


import Data.List
z n m k
 |k<n=(n`div`(k+1))*m
 |k>m+n-2= -1
 |1>0=m`div`(1+(k-(n-1)))
s[n,m,k]=max(z n m k)(z m n k)
main=interact$show.s.map read.words


import Data.List

readInts :: IO [Int]
readInts = fmap (map read.words) getLine

g :: Bool -> Int -> Int -> Int
g True a _ = a
g False _ a = a

f :: Int -> Int -> [Int] -> Int
f n curr xs
    | n==1 = 0
    | curr==0 =   min (xs!!0) (xs!!1) + f (n - 1) (g (min (xs!!0) (xs!!1) == (xs!!0)) 1 2) xs
    | curr==1 =   min (xs!!0) (xs!!2) + f (n - 1) (g (min (xs!!0) (xs!!2) == (xs!!0)) 0 2) xs
    | otherwise = min (xs!!1) (xs!!2) + f (n - 1) (g (min (xs!!1) (xs!!2) == (xs!!1)) 0 1) xs

main = do
    (n:_) <- readInts
    (a:_) <- readInts
    (b:_) <- readInts
    (c:_) <- readInts
    print( f n 0 [a,b,c])


module Main (main) where

import Control.Monad
import Control.Applicative

type GroupCount = (Int, Int, Int, Int, Int)

countGroups :: [Int] -> GroupCount
countGroups = foldl f (0, 0, 0, 0, 0)
    where
        f (a, b, c, d, e) 1 = (a+1, b, c, d, e)
        f (a, b, c, d, e) 2 = (a, b+1, c, d, e)
        f (a, b, c, d, e) 3 = (a, b, c+1, d, e)
        f (a, b, c, d, e) 4 = (a, b, c, d+1, e)
        f (a, b, c, d, e) 5 = (a, b, c, d, e+1)

solve :: [Int] -> [Int] -> Int
solve as bs = if canSolve then answer else -1
    where
        (a, b, c, d, e) = countGroups as
        (p, q, r, s, t) = countGroups bs

        diffs = [ a - p
                , b - q
                , c - r
                , d - s
                , e - t
                ]

        canSolve = all even diffs
        answer = sum (map abs diffs) `quot` 4

main :: IO ()
main = do
    n <- readLn
    as <- readInts n
    bs <- readInts n
    print (solve as bs)

readInts :: Int -> IO [Int]
readInts n = map read . words <$> getLine


{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array
-- import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import System.IO
-- import Debug.Trace

getInts = fmap (map read . words) getLine
-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  [v1, v2] <- getInts
  [t, d] <- getInts

  print $ sum [min (v1 + d*i) (v2 + d*(t-i-1)) | i <- [0..t-1]]


import Control.Monad (liftM)

--------------------------------------------------------------------------------
{-
import HUnit

testInput :: Test
testInput  =  TestList "TestInput"
  [
    Test "#1" $ assertEq 2 $ solve 2 6 12 11,
    Test "#2" $ assertEq 4 $ solve 2 3 5 1,
    Test "#3" $ assertEq 1 $ solve 3 6 81 9
  ]

test :: IO ()
test  =  mapM_ run
  [
    testInput
  ]
-}
--------------------------------------------------------------------------------

next :: Int -> Int -> Int -> Int -> Int
next a b m r  =  (a * r + b) `mod` m

nexts :: Int -> Int -> Int -> Int -> [Int]
nexts a b m r  =  iterate (next a b m) r

solve :: Int -> Int -> Int -> Int -> Int
solve a b m r0  =  solve' 1 (head ns) (tail ns)
  where
    ns  =  drop m $ nexts a b m r0
    solve' n x0 (x:xs)
      | x == x0  =  n
      | otherwise  =  solve' (n+1) x0 xs

main :: IO ()
main  =  do
    [a, b, m, r0]  <-  liftM (map read . words) getLine
    print $ solve a b m r0


import Data.List
import System.IO

main = do
  _  <- fmap read getLine :: IO Int
  xs <- fmap (fmap read . words) getLine :: IO [Int]
  print $ solve xs

solve :: [Int] -> Int
solve xs = length xs * foldr1 gcd xs


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

import Data.List
import qualified Data.IntSet as IS
import Data.Array.Base

main=interact$show.f.map read.words
f :: [Int] -> Int
f[a,b,n]=foldl'(+%)0.map(comb n)$filter isGood[0..n]
   where
     goods :: IS.IntSet
     !goods = IS.fromList.map read$concat[mapM(const[ca,cb])[1..i]|i<-[1..9]]
     isGood k = IS.member ((a-b)*k+b*n) goods
     !ca = show a !! 0
     !cb = show b !! 0

bigPrime :: Int
bigPrime = 1000000007

infixl 7  *%, /%
infixl 6  +%, -%

(+%) :: Int -> Int -> Int
x +% y = case x+y of
           xy | xy < bigPrime -> xy
              | otherwise     -> xy-bigPrime

(-%) :: Int -> Int -> Int
x -% y = case x-y of
           xy | xy >= 0   -> xy
              | otherwise -> xy+bigPrime

(*%) :: Int -> Int -> Int
x *% y = fromInteger $ toInteger x * toInteger y `rem` toInteger bigPrime

(/%) :: Int -> Int -> Int
x /% y = x *% (fst (extGcd y bigPrime) `mod` bigPrime)

{-# INLINE (+%) #-}
{-# INLINE (-%) #-}
{-# INLINE (*%) #-}
{-# INLINE (/%) #-}

extGcd :: Int -> Int -> (Int,Int)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b

permmemo :: UArray Int Int
permmemo = listArray(0,1000000)$scanl(*%)1[1..1000000]

perm :: Int -> Int -> Int
perm n k = foldl' (*%) 1 [n -% k +% 1..n]

fact :: Int -> Int
fact n = perm n n

comb :: Int -> Int -> Int
comb n 0 = 1
comb n k = (unsafeAt permmemo n) /% ((unsafeAt permmemo (n-k)) *% (unsafeAt permmemo k))


pocet n = poc n 3
poc n d
    | d > n             = 1
    | n `mod` d == 0    = poc n (d*3)
    | otherwise         = n `div` d + 1

main = do
    n <- readLn
    print (pocet n)


import Data.List.Split
import Data.List

makeIntArray :: [Char] -> [Int]
makeIntArray y = map  (\x -> read x :: Int) $ (splitOn " ") y

getSum :: [[Int]] -> Int
getSum arr = div (arr!!0!!1 + 2* arr!!0!!2 + 2*arr!!1!!2 + arr!!1!!0) 2

replaceZero :: [Int] -> Int -> [Int]
replaceZero (x:xs) y
  | x == 0 = (y:xs)
  | otherwise = (x: replaceZero xs y)

main::IO()
main = do
  input1 <- getLine
  input2 <- getLine
  input3 <- getLine
  let arr = map makeIntArray [input1, input2, input3]
  let sum = getSum arr
  let ans = [(replaceZero (arr!!0)  (sum - (arr!!0!!1 + arr!!0!!2))), (replaceZero (arr!!1) ( sum - (arr!!1!!0 + arr!!1!!2))), (replaceZero (arr!!2) ( sum - (arr!!2!!0 + arr!!2!!1)))]
  mapM_ putStrLn $ map  (intercalate " ") $ map (map show) ans


-- Codeforces 1040A
import Data.List

zipWithPrice :: [Int] -> Int -> Int -> [Int]
zipWithPrice dancers priceA priceB = zipWith func dancers (reverse dancers)
    where func 0 1 = -1
          func 2 1 = priceB
          func 2 0 = priceA
          func 2 2 = min priceA priceB
          func _ _ = 0

computePrice :: [Int] -> Int -> Int -> Int
computePrice dancers priceA priceB = if (-1) `elem` priceList then -1
                                     else sum priceList
    where priceList = zipWithPrice dancers priceA priceB

main :: IO ()
main = do
    [n, a, b] <- getLine >>= return . (map read) . words :: IO [Int]
    dancers <- getLine >>= return . (map read) . words :: IO [Int]
    putStrLn $ show $ computePrice dancers a b


import Data.List

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

diff k = last(k) - head(k)

solve n f result | length (f) <= n = min result (last (f) - head(f))
                 | otherwise = solve n (tail f) (min result (diff (take n f)))

parse x y = putStrLn $ show $ solve (head (readNumbers x)) (sort (readNumbers y)) 1008
main = getLine >>= (\x -> getLine >>= parse x)


import Data.List
import Data.Ord
g x = head $ maximumBy (comparing length) (group . sort $ fn x)
fn [x,y]   = [[x,y]]
fn (x:y:xs) = [x,y] : (fn $ y:xs)
main = do
  _ <- getLine
  a <- getLine
  putStrLn $ g a


main :: IO()
main = print . solve . map read . words =<< getLine

solve :: [Integer] -> Integer
solve [n, k] = let m = max (n - 2 * k) 0
               in n * (n - 1) `div` 2 - m * (m - 1) `div` 2


{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Control.Applicative
import Control.Arrow
import Data.List
import Data.Array
import Data.Array.IO.Safe
import Data.Array.ST.Safe
import Data.IORef
import Data.STRef
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.IntMap as IM
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import qualified Data.Sequence as Sq
import Data.Tuple
import Data.Function
import Text.Printf
import Numeric

readIntBS = fst . fromJust . BS.readInt

main = do
  [n,m] <- map read . words <$> getLine :: IO [Integer]
  let x = minimum [i | i<-[0..n], i*(i-1)`div`2 >= m]
  printf "%d %d\n" (max 0 (n-2*m)) (n-x)


main = do
    a <- fmap (map read . words) getLine :: IO [Int]
    b <- fmap (map read . words) getLine :: IO [Int]
    putStrLn $ if null $ filter (\x->fst x==snd x) $ zip a b then "NO" else "YES"


main :: IO ()
main  =  do
    [a, b, r]  <-  fmap (map (read :: String -> Int) . words) getLine
    if 2*r > a || 2*r > b
        then putStrLn "Second"
        else putStrLn "First"


import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

main :: IO ()
main = do
	a <- getLine
	b <- getLine
	c <- getLine
	let
		[xa, ya] = map (\x -> read x :: Integer). words $ a
		[xb, yb] = map (\x -> read x :: Integer). words$  b
		[xc, yc] = map (\x -> read x :: Integer). words$  c
		x1 = xb - xa
		y1 = yb - ya
		x2 = xb - xc
		y2 = yb - yc
	if x1*y2 == y1*x2 then
		putStrLn "TOWARDS"
		else if x1*y2 - y1*x2 < 0 then
			putStrLn "LEFT"
			else
				putStrLn "RIGHT"


import Data.Int
g a b m
    | b >= m - 1 = "2"
    | length list == 0 = "2"
    | otherwise = "1 " ++ (p . show . head) list
    where p s = if (length s) == 9 then s else p ('0':s)
          mul = mod 1000000000 m
          list = filter (\x -> (m - (mul * x)) `mod` m > b) [0..(min m a)]
main = do [a, b, mod] <- fmap ((map (read::String->Int64)) . words) getLine
          putStrLn $ g a b mod


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

import qualified Data.ByteString.Char8 as B
readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

solve :: String -> Bool
solve s = (not (any (\(a, b) -> c a && d b) (zip s (tail s)))) && (not (c (last s)))
        where c = not . (flip elem) "aeioun"
              d = not . (flip elem) "aeiou"

main :: IO ()
main = do
    s <- getLine
    -- print $ solve "auuaoonntanonnuewannnnpuuinniwoonennyolonnnvienonpoujinndinunnenannmuveoiuuhikucuziuhunnnmunzancenen"
    -- print $ solve "ninja"
    -- print $ solve "codeforces"
    -- print $ solve "sumimasen"
    -- print $ solve "necnei"
    -- print $ solve "a"
    -- print $ solve "ab"
    putStrLn $ if solve s then "YES" else "NO"


module Main where
import Data.Bool
import Data.List
main = getLine >> getLine >>= putStr . bool "No" "Yes" . solve
solve xs = xs /= "0" && (\g -> notElem "00" [head g, last g] && all (`elem` ["0", "1", "00"]) g) (group xs)


main=interact$show.f.map read.words
f[n,m,z]=sum[1|c<-[n,n+n..z],rem c m<1]


--http://rextester.com ghc 7.10
main=interact(unwords.a.map read.words)
a[0,0]=["0 0"]
a[0,_]=["Impossible"]
a[b,c]=map show[max b c,if c/=0 then c+b-1 else b]


-- Codeforces Round #320 (Div. 2) [Bayan Thanks-Round] - Problem A: Raising Bacteria (https://codeforces.com/problemset/problem/579/A)
solve 1 = 1
solve n | n `mod` 2 == 0 = solve (n `div` 2)
        | otherwise      = 1 + solve (n `div` 2)

main = do
    n <- readLn :: IO Int
    print $ solve n


import Control.Applicative
import Data.List

main=do
	[n,x]<-map read.words <$> getLine:: IO [Int]
	print $ length [1|i<-[1..n], mod x i ==0, div x i <=n]


main :: IO ()
main = interact $ show . solve . map read . words

solve :: [Integer] -> Integer
solve [m, n, k]
  | n >= (k - 1) * c = (2 * k * (exp2 d - 1) + e) `rem` p
  | otherwise = n
  where
  c = (m - n + 1)
  (q, r) = (n - (k - 1) * c) `quotRem` k
  d = q + min 1 r
  e = n - d * k

exp2 :: Integer -> Integer
exp2 0 = 1
exp2 x
  | even x = y * y `rem` p
  | otherwise = y * y * 2 `rem` p
  where
  (q, r) = x `quotRem` 2
  y = exp2 q

p :: Integer
p = 1000000009


answer 0 = 1
answer x = (3 ^ (x - 1)) `mod` 1000003
main = do v <- getLine
          putStrLn $ show $ answer (read v::Integer)


import Data.List

main = interact $ show . phi . (+(-1)) . read

fact n = map (\l -> (head l, length l)) . group $ divf n 2
         where divf 1 _ = []
               divf n' p | p^2 <= n  = if n'`mod`p == 0
                                       then p:(divf (n'`div`p) p)
                                       else divf n' (p+1)
                         | otherwise = [n']

phi n = foldl' (\r (p,k) -> r * phiPrime p k) 1 (fact n)
        where phiPrime p k = p^(k-1) * (p-1)


import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Ord
import Data.Char
import Data.Array.IO
import Data.Array
import Text.Printf

main :: IO ()
main = do
  n <- readLn
  s <- reverse . take (2 * n) <$> getLine
  let a =  listArray (1, 2 * n) $ map (toInteger . digitToInt) s :: Array Int Integer
  table <- newArray ((0, 0), (n, n)) 0 :: IO (IOArray (Int, Int) Integer)
  route <- newArray_ ((0, 0), (n, n)) :: IO (IOArray (Int, Int) Char)
  let initValue i = read . reverse $ take i s
  forM_ [0 .. n] $ \i -> do
    forM_ [0 .. n] $ \j -> do
      unless (i == 0 && j == 0) $ do
        let sumPrize idx x = (a ! idx) * 10 ^ (x - 1)
        h <- do
          if i > 0
            then (+ sumPrize (i + j) i) <$> readArray table (i - 1, j)
            else return 0
        m <- do
          if j > 0
            then (+ sumPrize (i + j) j) <$> readArray table (i, j - 1)
            else return 0
        writeArray table (i, j) $ max h m
        writeArray route (i, j) $ case () of
          _ | i == 0    -> 'M'
            | j == 0    -> 'H'
            | otherwise -> if h >= m then 'H' else 'M'
  let getOrder = f (n, n) where
        f (0, 0)     = return ""
        f idx@(i, j) = do
          c <- readArray route idx
          if c == 'H'
            then (c :) <$> f (i - 1, j)
            else (c :) <$> f (i, j - 1)
--  printArray table
  getOrder >>= putStrLn

printArrayWith :: (Show a) => Int -> IOArray (Int, Int) a -> IO ()
printArrayWith width table = do
  ((l1, c1), (l2, c2)) <- getBounds table
  forM_ [l1 .. l2] $ \l -> do
    forM_ [c1 .. c2] $ \c -> do
      v <- readArray table (l, c)
      printf "%-*s " width (show v)
    putChar '\n'
  putChar '\n'

printArray :: (Show a) => IOArray (Int, Int) a -> IO ()
printArray = printArrayWith 10


-- import Debug.Trace
-- import System.IO.Unsafe
-- import Text.Printf
import System.IO
import Control.Monad
import Data.List

glwr = fmap (map read . words) getLine

main = do
  hSetBuffering stdout NoBuffering
  solve

solve :: IO ()
solve = do
  m:n:_ <- glwr

  print $ domino m n

domino :: Int -> Int -> Int
domino m n = (m * n) `div` 2


{-# OPTIONS_GHC -funbox-strict-fields #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Ord
import Text.Printf

main :: IO ()
main = do
  let readDoubles = map read . words
  l : d : v : g : r : _ <- readDoubles <$> getLine
  let epsilon = 1e-9
      t = last . takeWhile (negate epsilon <=)
        $ zipWith (-) (repeat $ d / v) [0, g + r ..]
      waitTime = if t < g - epsilon
                   then 0
                   else g + r - t
      answer = l / v + waitTime :: Double
  printf "%.7f\n" answer


import Data.Char
import Control.Monad

readIntImpl :: Int -> Bool -> IO Int
readIntImpl x flag = do
    c <- getChar
    if c `elem` ['0'..'9']
        then do
            let d = digitToInt c
            y <- readIntImpl (x*10+d) True
            return y
    else if flag
        then
            return x
        else do
            y <- readIntImpl x False
            return y

readInt = readIntImpl 0 False
readArr n readFunc = replicateM n readFunc

f [] [] = []
f (x:xs) (y:ys) = do
    if x < y then
        []
    else
        y:(f xs ys)

main = do
    x <- getLine
    y <- getLine
    let z = f x y
    let ans = if length z < length x then "-1" else z
    putStrLn ans


import Data.List (sort)
import Control.Monad (filterM)
powerset = filterM (const [True, False])
solve (l:r:x:c) = length $ filter acc (powerset $ sort c)
    where acc ps = let s = sum ps in length ps >= 2 && (maximum ps - minimum ps) >= x && s <= r && s >= l
main = putStrLn.show.solve.map read.tail.words =<< getContents


import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array

main = do
		getLine
		a<-map read <$> words <$> getLine ::IO [Int]
	 	print $ max 0 ((maximum a) - 25)


main = do
    n_ <- readLn
    as_ <- return . map read . words =<< getLine
    let lrs = map (`splitAt` as_) [1..n_]
	check (l,r) = sum l /= 0 && sum r /= 0
	twoSplits = filter check lrs
	total = sum as_
    if total /= 0
      then do
	putStrLn "YES"
	print 1
	putStr $ (show 1) ++ " " ++ (show n_)
      else case twoSplits of
	[] -> putStr "NO"
	(l,r):_ -> do
	    putStrLn "YES"
	    print 2
	    let szL = length l
	    putStrLn $ (show 1) ++ " " ++ (show szL)
	    putStr   $ (show$szL+1) ++ " " ++ (show n_)


run c m ans n | n == m = c:ans
              | n < m = run (succ c) 1 (succ c:ans) n
              | n > m = run c (m + 1) (c:ans) (n - m)
main = getLine >>= putStrLn . run 'a' 0 [] . read


check p1 p2 p3 p4 x = if ((((x `mod` p1) `mod` p2) `mod` p3) `mod` p4) == x
                      then 1
                      else 0

count p1 p2 p3 p4 x b | x == b = check p1 p2 p3 p4 x
                      | otherwise = (check p1 p2 p3 p4 x) + (count p1 p2 p3 p4 (x+1) b)

brute (f:fs) ts a b = (brute (fs) (ts ++ [f]) a b) -- + (brute (fs ++ [f]) ts a b)

brute [] (p1:p2:p3:p4:[]) a b = count p1 p2 p3 p4 a b

solve l a b = brute l [] a b

main = do
        line <- getLine
        let (p1:p2:p3:p4:a:b:[]) = map read (words line) :: [Int]
        putStrLn $ show $ solve [p1, p2, p3, p4] a b
        return ()


-- Codeforces Round 380 (Div. 2)
-- ID:  Problem A. Interview with Oleg
-- URL: http://codeforces.com/contest/738/problem/A

getInt = read `fmap` getLine :: IO Int

main = do
    n <- getInt
    s <- getLine
    putStrLn (ogoFilter s)

ogoFilter s = case split s of
    ([], []) -> []
    ([], r:rest) -> r : ogoFilter rest
    (ogo, rest) -> "***" ++ ogoFilter rest

split [] = ([], [])
split (c:cs)
    | c == 'o' && length go /= 0 = ('o' : go, drop (length go) cs)
    | otherwise = ([], c:cs)
    where
        go = f cs []
        f ('g':'o':s) acc = f s ('g':'o':acc)
        f s acc = acc


modulus = 1000000007 :: Integer

factorial :: Integer -> Integer
factorial n = product [1..n]

nCr :: Integer -> Integer -> Integer
nCr n r = div (factorial n) $ (factorial r) * (factorial (n - r))

main :: IO ()
main = do
    [n, x, p] <- map read . words <$> getLine
    print $ solve n x p `mod` modulus

solve :: Integer -> Integer -> Integer -> Integer
solve n x p
          | (smallCount < smallPositions) || (bigCount < bigPositions) = 0
          | otherwise = product [nCr bigCount bigPositions, nCr smallCount smallPositions, factorial smallPositions, factorial bigPositions, factorial (n - bigPositions - smallPositions - 1)]
          where (smallPositions, bigPositions) = getBigSmallPos 0 n p
                (smallCount, bigCount) = (x - 1, n - x)

getBigSmallPos :: Integer -> Integer -> Integer -> (Integer, Integer)
getBigSmallPos s e p
                     | s >= e = (-1, 0)
                     | m <= p = let (a, b) = getBigSmallPos (m + 1) e p in (a + 1, b)
                     | otherwise = let (a, b) = getBigSmallPos s m p in (a, b + 1)
                     where m = (s + e) `div` 2


import Control.Applicative

canBeBad :: Char -> Int
canBeBad '0' = 2 -- 0, 8
canBeBad '1' = 7 -- 0, 1, 3, 4, 7, 8, 9
canBeBad '2' = 2 -- 2, 8
canBeBad '3' = 3 -- 3, 8, 9
canBeBad '4' = 3 -- 4, 8, 9
canBeBad '5' = 4 -- 5, 6, 8, 9
canBeBad '6' = 2 -- 6, 8
canBeBad '7' = 5 -- 0, 3, 7, 8, 9
canBeBad '8' = 1 -- 8
canBeBad '9' = 2 -- 8, 9

main = do x <- getLine
          print $ foldl (*) 1 $ map canBeBad x


import Control.Monad
import Data.List

nextmeet vp vd f x =
    let t = x / vd + f
        x' = x + t * vp
    in x' + x' / (vd - vp) * vp :: Double

solve vp vd t f c | vd <= vp = 0
solve vp vd t f c =
    let firstmeet = t * vp + t * vp / (vd - vp) * vp
        meets = iterate (nextmeet vp vd f) firstmeet
    in length $ takeWhile (< c - 1e-10) meets

main = do
    [vp, vd, t, f, c] <- replicateM 5 $ liftM read getLine
    print $ solve vp vd t f c


import           Control.Applicative

pillowsTo :: Integral t => t -> t -> t
pillowsTo i k = let a = max (i - k + 1) 0 in (a + i) * (i - a + 1) `quot` 2

totalPillows :: Integral a => a -> a -> a -> a
totalPillows i k n = pillowsTo i k + pillowsTo i (n - k + 1) - i

diho::Integer->Integer->Integer->Integer
diho n m k = go start end where
  start = 0
  end = m - n + 1
  go s e = let mid   = (s + e) `quot` 2
               total = totalPillows mid k n
               good  = total <=  m - n
               found = e - s <= 1
           in if found then s + 1 else if good then go mid e else go s mid

main :: IO ()
main = do
  [n, m, k] <- fmap read . words <$> getLine
  print $ diho n m k


main = do
  s <- getLine
  putStrLn (normalize s)

normalize :: String -> String
normalize = normalize'' . normalize'

normalize' :: String -> String
normalize' (x:o@(y:_)) = if and [x == '/', y == '/'] then normalize' o else x:normalize o
normalize' x = x

normalize'' :: String -> String
normalize'' [] = []
normalize'' [x] = [x]
normalize'' x = if last x == '/' then init x else x


{-# LANGUAGE TypeApplications #-}

import Data.List

main :: IO ()
main = do
  _ <- getLine
  a <- fmap (map (read @ Int) . words) getLine
  print $ run $ sort a

run :: [Int] -> Int
run [] = 0
run (x:xs) = 1 + run (filter (\e -> e `mod` x /= 0) xs)


import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array
import qualified Data.Map as M

main = do
		[a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		print $ (c+ (min a b))*2 + if a==b then 0 else 1


import Data.List (transpose)

-- Calculates the value of shortest route

shortest (i,j,0) g = g !! (i-1) !! (j-1) -- Transition value from graph
shortest (i,j,k) g = min (shortest (i,j,k-1) g) $
                         (shortest (i,k,k-1) g) + (shortest (k,j,k-1) g)

main = interact $ show . f . g . lines

g :: [[Char]]->(Int,[[Int]])
g (x:xs) = (read x, readGraph ( unlines xs))

f (n,x) = maximum [shortest (a,b,n) x |  a<-[1..n], b<-[1..n]]

readGraph = str2int . map words . lines
str2int = map.map $ fromIntegral . (\xs -> read xs :: Int)


{-# LANGUAGE BangPatterns #-}
module Main where

import Data.Maybe
import Control.Applicative

import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

readInts = map (fst . fromJust . BS8.readInt) . BS8.words

getInts = readInts <$> BS.getLine

solve k2 k3 k5 k6 =
    max (256 * n256 + 32 * n32After256) (32 * n32 + 256 * n256After32)
    where
        n32  = minimum [k2, k3]
        n256 = minimum [k2, k5, k6]

        n32After256 = min n32 $ max 0 (k2 - n256)
        n256After32 = min n256 $ max 0 (k2 - n32)

main = do
    [!k2, !k3, !k5, !k6] <- getInts
    print $ solve k2 k3 k5 k6


main = do
    s <- getLine
    let [n,k,l,c,d,p,nl,np] = map read $ words s
    print $ solve n k l c d p nl np
solve n k l c d p nl np = minimum [water k l nl, lime c d, salt p np] `div` n
water k l nl = k*l `div` nl
lime c d = c*d
salt p np = p `div` np


import Control.Applicative
import Data.List

main= do
	n<-  read   <$> getLine ::IO Integer
	k<-  read   <$> getLine ::IO Integer
	let s= takeWhile (<=k) $ iterate (*n) n
	putStrLn $ if s/= [] && last s ==k then "YES\n" ++ show (length s -1) else "NO"


fi=fromIntegral
f n=n*(n+1) `div` 2
x n = (sqrt (1+8*(fi n))-1)/2

find a n
	|f a>n && ((odd (f a) && odd n) || ( even (f a) && even n ))= a
	|otherwise = find (a+1) n

solve n
	|nn == f a = a
	|otherwise = find a nn
	where
		nn = abs n
		a = floor $ (x nn)
		b = f a

main=do
	a<-getLine
	putStrLn (show $ solve (read a::Int))


import Control.Applicative
import Data.List

repl 'q' = -9
repl 'r' = -5
repl 'b' = -3
repl 'n' = -3
repl 'p' = -1
repl 'Q' = 9
repl 'R' = 5
repl 'B' = 3
repl 'N' = 3
repl 'P' = 1
repl x = 0

main=do
	a<-   getContents
	let b = sum $ map repl a
	putStrLn $ if b>0 then "White" else if b==0 then "Draw" else "Black"


import Data.List
import Data.Char

main :: IO ()
main = getContents >>= solve

solve :: String -> IO ()
solve input = do
        let temp = dropWhile (/= '1') input
        if temp == []
        then putStrLn "no"
        else if (length $ filter (== '0') temp ) >= 6 then putStrLn "yes"
        else  putStrLn "no"


solve :: Integer -> [Integer] -> Integer -> Integer
solve n [] t
  | n == 0 = t
  | otherwise = 10000000
solve n (x:xs) t =
  min a b
  where
    ps = toInteger (length (x:xs) :: Int)
    l = n `div` x
    h = (n + x - 1) `div` x
    a = solve (n - l * x) xs (t + ps * l)
    b = solve (h * x - n) xs (t + ps * h)

go :: Integer -> Integer
go n =
  let
    vals = reverse . take 16 $ iterate (\x -> 10 * x + 1) 1
  in
    solve n vals 0

main = do
  n <- fmap read getLine
  putStrLn $ show $ go n


import Data.List
main = interact $ f . map read . words
f [0,0] = "infinity"
f [0,_] = "0"
f [a,b]
  | a == b = "infinity"
  | a < b = "0"
  | otherwise = show . length . filter (>b) . foldl (\xs ys -> [x*y | x <- xs, y <- ys]) [1] . map (scanl (*) 1) . group $ h 2 (a-b)
h a b
  | mod b a == 0 = a:h a (div b a)
  | a*a <= b = h (a+1) b
  | b > 1 = [b]
  | otherwise = []


f::String->String
f ""=""
f ('.':xs)='0':f xs
f ('-':'.':xs)='1':f xs
f ('-':'-':xs)='2':f xs

main = do
       e<-getLine
       putStrLn $ f e


fu n b| sum [1..n] < b = b - sum[1..n] | sum [1..n] == b = 0 | sum [1..n] > b = fu (n-1) b
solve [n,b] | sum [1..n] < b = solve [n,x] | sum [1..n] == b = 0 | sum [1..n] > b = fu n x
    where x = b `mod` sum [1..n]
main = interact $ show . solve . map read . words


import Data.List
main = interact $ show.helper.(map read).words

helper (a:b:c:d:[]) =  (f y x) + (f z y)
        where   s = [a,b,c]
                [x,y,z] = sort s
                f k l =  max (d - (k -l)) 0


import Control.Monad.State
import Data.Map as Map
import qualified Data.ByteString.Char8 as C

type S = Map (Int, Int, Int) Integer

small :: [[Int]] -> Int -> Int -> Int -> State S Integer
small _ 0 _ _ = return 0
small cost n a c = do
  map <- get
  case Map.lookup (n,a,c) map of
    Just ret -> return ret
    Nothing -> do
      let b = 3-a-c
      mab <- small cost (n-1) a b
      mac <- small cost (n-1) a c
      mbc <- small cost (n-1) b c
      mca <- small cost (n-1) c a
      let costac = fromIntegral $ cost!!a!!c
      let costab = fromIntegral $ cost!!a!!b
      let costbc = fromIntegral $ cost!!b!!c

      let ret = min (mab+costac+mbc) (mac+costab+ mca+costbc+mac)
      modify (insert (n,a,c) ret)
      return ret

getInts :: IO [Int]
getInts = do
  line <- C.getLine
  return $ fmap read $ words $ C.unpack line

main = do
  cost <- sequence [getInts, getInts, getInts]
  n <- fmap read getLine :: IO Int
  let (ret, _) = runState (small cost n 0 2) Map.empty
  print ret


{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}

digsum 0 = 0
digsum n = (mod n 10) + (digsum $ div n 10)

interesting n = mod (digsum n) 4 == 0

inspect n = if interesting n
  then print n
  else inspect $ n + 1

main = do
  line <- getLine
  inspect $ read $ line


{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

-- getInts = fmap (map read . words) getLine
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  getLine
  s <- getLine

  let
    b = or $ map f $ tails s
      where
        f t = or $ map f' [1..length t]
          where
            f' k = isPrefixOf "*****" hs
              where
                hs = map head $ takeWhile (not . null) $ iterate (drop k) t

  putStrLn $ if b then "yes" else "no"


isReverse :: String -> Bool
isReverse s  =  s == (reverse s)

solve :: String -> String
solve s  =  maximum $ filter isReverse $ solve' s
  where
    solve' []  =  []
    solve' (x:xs)  =  [x] : ((map ((:) x) res) ++ res)
      where
        res  =  solve' xs

main :: IO ()
main  =  getLine >>= putStrLn . solve


import Control.Monad
import Data.Char

ispretty :: String -> Bool
ispretty "0" = True
ispretty (x:xs) | x == '0' = False
                | otherwise = read (x:xs) <= 1000000

run cs = do i <- [1..(length cs - 1)]
            let (sub1, subs) = splitAt i cs
            guard (ispretty sub1)
            j <- [1..(length subs - 1)]
            let (sub2, sub3) = splitAt j subs
            guard (ispretty sub2)
            guard (ispretty sub3)

            return $ sum [read s | s <- [sub1, sub2, sub3]]

main = do s <- getLine
          print $ maximum (-1:run s)


import Data.List
import Data.Char

main = interact foo

foo :: String -> String
foo inp =
    let ss = (!! 1) . lines $ inp
        cs = filter (/= "") . myBreak isUpper $ ss
    in show $ maximum . (++[0]) . map (length . nub) $ cs

myBreak :: (a -> Bool) -> [a] -> [[a]]
myBreak _ [] = []
myBreak p ll = let (a, b) = break p ll
               in a : if null b then [] else myBreak p (tail b)


import Data.List (sort)
import Control.Arrow (second)
main = putStrLn . unwords . map show . sort . solve . map read . words =<< getLine
solve [n,m] = map friends [ [(1,n-m+1),(m-1,1)]
                          , [ (n `mod` m,(n+m-1) `div` m)
                            , (m - n `mod` m,n `div` m) ] ]
friends = sum . map (uncurry (*) . second pairs)
pairs n = n * (n-1) `div` 2


import Data.List
main = interact $ show . foo . tail . map read . words

foo :: [Int] -> Int
foo x
    |(head x) == (maximum x) && not (elem (head x) (tail x)) = 0
    |otherwise = 1 + (foo $ (1 + head x) : (bar (maximum x) (tail x)))
        where
            bar a [] = []
            bar a as
                |a == head as = a - 1 : tail as
                |otherwise = (head as) : bar a (tail as)


main = do
    [n, k] <- fmap (fmap read . words) getLine
    putStrLn $ if [n `mod` i | i <- [1..k]] == [0..(k-1)] then "Yes" else "No"


import qualified Data.ByteString.Lazy.Char8 as BS
import Data.List

type Cup = (Integer, Integer)

readInt :: BS.ByteString -> Integer
readInt x = case BS.readInteger x of Just (i, _) -> i
                                     Nothing -> error "Unparsable Int"

toPref :: [Cup] -> [Cup]
toPref ((x, y):(a, b):xs) = (x, y):toPref((a+x, b+y):xs)
toPref xs = xs

f :: Integer -> [Cup] -> [Cup] -> Integer
f _ _ [] = 0
f _ [] _ = 0
f k (x:xs) (y:ys) | (snd x) + (snd y) > k = f k (x:xs) ys
                  | otherwise = let now = (fst x) + (fst y)
                                  in max now $ f k xs (y:ys)
cupCmp :: Cup -> Cup -> Ordering
cupCmp (a, b) (x, y) | a > x = GT
                     | x > a = LT
                     | a == x = if y > b then GT else LT

main = do
    (l:ls) <- fmap BS.lines BS.getContents
    let (n:m:k:[]) = map readInt $ BS.split ' ' l
        (as, bs) = splitAt (fromIntegral n) $ take (fromIntegral (n+m)) ls
        xs = map ((\[x, y] -> (x, y)) . map readInt . BS.split ' ') as
        ys = map ((\[x, y] -> (x, y)) . map readInt . BS.split ' ') bs
        xs' = reverse $ sortBy cupCmp xs
        ys' = reverse $ sortBy cupCmp ys
        xs'' = toPref xs'
        ys'' = reverse $ toPref ys'
     in print $ f k xs'' ys''


{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Data.List

count :: Eq a => a -> [a] -> Int
count a b = length $ elemIndices a b

solve :: [Int] -> String
solve l@[a,b,c,d,e,f]
  | count a l >= 4 = if e == f then "Elephant" else "Bear"
  | count b l == 4 = "Bear"
  | count c l >= 4 = if a == b then "Elephant" else "Bear"
  | otherwise = "Alien"

main :: IO ()
main = do
  a <- sort <$> (map read <$> (words <$> getLine))
  putStrLn $ solve a


import Data.Char

-- Read a token from standard input
getToken :: IO String
getToken = do t <- go
              if t == "" then getToken else return t
                where go = do c <- getChar
                              if isSpace c then return "" else
                                 go >>= (\s -> return (c:s))

-- Read an integer from standard input
getInteger :: IO Integer
getInteger = getToken >>= (\t -> return (read t :: Integer))

-- Repeat a monadic function n times
repeatM_ :: Monad m => Integer -> m a -> m ()
repeatM_ 0 f = return ()
repeatM_ n f = f >> repeatM_ (n - 1) f

gasInterval a f = f:go (2 * f) (2 * (a - f))
  where go f1 f2 = f2:f1:go f1 f2

step gi b k c
  | k <= b = c
  | otherwise = let delta = go gi b 0
                      where go gi@(g:gs) b d = let b' = b - g in
                                                 if b' < 0 then (d, gi) else
                                                   go gs b' (d + g)
                in
                  if fst delta == 0 then -1 else
                    step (snd delta) b (k - fst delta) (c + 1)

main = do
  a <- getInteger
  b <- getInteger
  f <- getInteger
  k <- getInteger
  print (step (gasInterval a f) b (a * k) 0)


{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeSynonymInstances #-}

import Control.Monad

import Data.IORef
import System.IO.Unsafe

import Data.List
import Data.Ord
import Data.Ratio

import Debug.Trace

solve = do n <- cin :: IO Integer
           m <- cin
           cs' <- replicateM m $ do
             ai <- cin
             bi <- cin
             return (ai,bi)
           let cs = reverse $ sortBy (comparing snd) cs'
           return . show $ f 0 cs n
  where
    f s [] _ = s
    f s _ 0 = s
    f s ((a,b):cs) capa = let n = min a capa
                          in f (s+n*b) cs (capa-n)

main = putStrLn =<< solve

class Read' a where
  read' :: String -> a

instance Read' Integer where
  read' = read

instance Read' Int where
  read' = read

instance Read' Double where
  read' = read

instance Read' Char where
  read' (c:[]) = c
  read' cs = error $ cs ++ " cannot read' as the type of Char."

instance Read' String where
  read' cs = cs

cin :: forall a. Read' a => IO a
cin = do (x:xs) <- readIORef input
         writeIORef input xs
         return $ read' x

input :: IORef [String]
input = unsafePerformIO $ getContents >>= newIORef . words


import Data.Bits

main :: IO()
main = print . solve . read =<< getLine

solve :: Int -> Int
solve n = num
    where
        nums1 = map (\x -> compose1 x 0 0) [1..9]
        nums2 = map (\(x, y) -> compose2 x y 0 0 0) [(x, y) | x <- [0..8], y <- [(x+1)..9]]
        num = sum $ map (length . filter (<=n)) ([1000000000]:(nums1 ++ nums2))

compose1 :: Int -> Int -> Int -> [Int]
compose1 _ num 9 = [num]
compose1 x num i = case i of 0 -> longer
                             _ -> num:longer
                   where longer = compose1 x (num * 10 + x) (i + 1)

compose2 :: Int -> Int -> Int -> Int -> Int -> [Int]
compose2 _ _ num 9 3 = [num]
compose2 _ _ num 9 _ = []
compose2 x y num i s | num == 0 && x == 0 = compose2 x y y (i + 1) (s .|. 2)
                     | otherwise = case s of 3 -> num:longer
                                             _ -> longer
                                   where longer = (compose2 x y (num * 10 + x) (i + 1) (s .|. 1)) ++
                                                  (compose2 x y (num * 10 + y) (i + 1) (s .|. 2))


import Data.Char

main = interact $ unlines . map (\s -> if foldl(\acc c -> if isUpper c then acc else False) True $ tail s then map (\c -> if isUpper c then toLower c else toUpper c) s else s) . lines


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.ST

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readNInts = readInt >>= flip replicateM readInt

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	( n : poss ) <- readInts
	let
		[ a, x, b, y ] = map pred poss
	putStrLn $ which "YES" "NO" $ solve n a x b y

solve n a x b y
	| a == b = True
	| a == x = False
	| b == y = False
	| otherwise = solve n a' x b' y
	where
		a' = succ a `mod` n
		b' = ( pred b + n ) `mod` n


import Data.List (intercalate)
import Data.Functor ((<$>))

solve' :: Int -> Int -> Maybe [Int]
solve' a b  | a == b = Just [a]
            | a >  b = Nothing
            | even b = (b:) <$> solve' a (b `div` 2)
            | b `mod` 10 == 1 = (b:) <$> solve' a (b `div` 10)
            | otherwise = Nothing

solve :: Int -> Int -> Maybe [Int]
solve a b = reverse <$> solve' a b

main :: IO()
main = do
    line <- getLine
    let x = map read . words $ line :: [Int]
    case solve (x !! 0) (x !! 1) of
        Just y  -> do
            putStrLn "YES"
            putStrLn $ show . length $ y
            putStrLn $ intercalate " " (map show y)
        Nothing -> putStrLn "NO"


process :: [Int] -> Int
process xs = maximum xs - minimum xs

readInt :: String -> Int
readInt = read

main = do
    xs <- fmap (map readInt.words) getLine
    print $ process xs


import Control.Applicative( (<$>))

main = do
    let
	readLine =  map read . words <$> getLine
    [n_, m_, k_] <- readLine
    as <- readLine
    let
	(pre,rightSide) = splitAt m_ as

	leftSide = tail . reverse $ pre

	zip' [] [] = []
	zip' [] (e:es) = let
			    mb = if 0<e && e<=k_
				    then Just e
				    else Nothing
			in
			    (Nothing,mb):zip' [] es
	zip' (e:es) [] = let
			    mb = if 0<e && e<=k_
				    then Just e
				    else Nothing
			in
			    (mb, Nothing):zip' es []
	zip' (e1:es1) (e2:es2) = let
			    mb1 = if 0<e1 && e1 <= k_
				    then Just e1
				    else Nothing
			    mb2 = if 0<e2 && e2 <= k_
				    then Just e2
				    else Nothing
			in
			    (mb1, mb2): zip' es1 es2

	search k d (p:pairs) = case p of
	    (Nothing, Nothing) -> search k (d+10) pairs
	    _			-> d

    print $ search k_ 10 $ zip' leftSide rightSide


import Text.Printf
import Control.Monad

main = do
  n <- readLn
  ns <- replicateM n readLn
  let ans = maximum $ zipWith (/) (scanl1 (+) ns) [1..]
  printf "%.12f\n" $ (ans :: Double)


import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

getIntArray :: B.ByteString -> [Int]
getIntArray = map fst . mapMaybe B.readInt . B.words

main = interact $ unlines . map (unwords . map show) . getAns . map read . words

getAns :: [Integer] -> [[Integer]]
getAns (n:a:b:_) = if a * b >= n * 6 then [[a * b], [a, b]]
					else findAns a b n

findAns a b n
	| a <= b = findMax [a .. (ceiling . sqrt . fromInteger . (*6)) n] b n
	| otherwise = let (x:(newa:newb:_):_) = findAns b a n
					in [x, [newb, newa]]

findMax :: [Integer] -> Integer -> Integer -> [[Integer]]
findMax [] b n = [[n * 10], []]
findMax (x:xs) b n = let newb = ceiling ((fromInteger (n * 6)) / (fromInteger x));
						 area = newb * x;
						 pans = findMax xs b n
					 in if (newb >= b && area <  (head . head) pans) then [[area], [x, newb]] else pans


import Control.Monad
import qualified Data.List as L

main :: IO ()
main = do
    [n,m,k] <- getLine >>= return . map read . words
    l <- getLine >>= return . map read . words
    putStrLn . show $ solve n m k l

solve :: Int -> Int -> Int -> [Int] -> Int
solve n m k l = judge . L.foldl' f (k,0) . L.reverse . L.sort $ l
    where
        judge (x,i) = if x < m then -1 else i
        f (k,i) x = if k < m then (k+x-1,i+1) else (k,i)


read_int :: String -> Int
read_int = read

fib_n :: (Num a) => Int -> a -> a -> a
fib_n 0 a b = a
fib_n 1 a b = b
fib_n 2 a b = a+b
fib_n n a b = fib_n (n-1) b (a+b)

solve :: [Int] -> Int
solve (x:y:z:_) = fib_n z x y

main = interact $ show . solve . (map read_int) . words


{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}
{-# LANGUAGE BangPatterns #-}
{-(c) gorlum0 [at] gmail.com-}
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.Array
import Debug.Trace (trace)
import Data.Maybe (fromJust)
import Text.Printf (printf)

readNum = fst . fromJust . BS.readInt
--- debug = flip trace
debug x = trace (show x) x
debug2 msg x = trace (printf "%s: %s" msg $ show x) x

splitEvery _ [] = []
splitEvery n xs = ys : splitEvery n xs'
    where (ys, xs') = splitAt n xs

solve ([n,m,c0,d0]:xss) = maximum [dp!(k,m) + (n-k)`div`c0 * d0| k <- [0..n]]
    where
    yss = transpose xss
    bnds1 = (1,m)
    [a, b, c, d] = map (array bnds1 . zip [1..]) yss

    bnds2 = ((0,0), (n,m))
    dp = array bnds2 [(ij, f ij) | ij <- range bnds2]

    f (_,0) = 0
    f (i,j) = maximum [dp!(i-(c!j)*k, j-1) + (d!j)*k |
                        k <- [0..(a!j)`div`(b!j)], i-(c!j)*k >= 0]

body [] = []
body xs@(n:m:_) = solve yss : body xs'
    where
    (ys, xs') = splitAt ((m+1)*4) xs
    yss = splitEvery 4 ys

main = do
    ws <- BS.words `fmap` BS.getContents
    let xs = map readNum ws
    mapM_ print $ body xs


import Data.List

addLists :: [Int] -> [Int] -> [Int]
addLists a b = map (\(x, y) -> x + y) $ zip a b

getBest :: [(Int, Int)] -> Int -> Int
getBest [] _ = 400000000
getBest ((a, b) : tail) sz = if sz > a then min b $ getBest tail sz else getBest tail sz

solve :: [Int] -> [Int] -> [(Int, Int)] -> [Int]
solve [] [] [] = []
solve (a : tailA) (b : tailB) c = (getBest c a) : solve tailA tailB ((a, b) : c)
solve _ _ _ = []

main = do
    s <- getLine
    let [x, y] = map (read :: String -> Int) $ words s
    putStrLn $ if or [(x == y), and [x == 2, y == 4], and [x == 4, y == 2]]
                then "="
            else if fromIntegral y * logBase 2 (fromIntegral x) < fromIntegral x * logBase 2 (fromIntegral y)
                then "<"
            else ">"


import Control.Applicative
import Control.Monad
import Data.List

main = do
		n<- map read <$> words <$> getLine::IO [Int]
		let s = sum n
		let m1 = maximum n
		let m2 = (minimum n)
		let m =m1+m2
		putStrLn $ if m+m==s then "YES" else if m1+m1==s then "YES" else  "NO"


import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

getIntArray :: B.ByteString -> [Integer]
getIntArray = map fst . mapMaybe B.readInteger . B.words

main = B.interact $ B.unlines . map (B.unwords . map (B.pack . show)) . getAns . getIntArray

digitSum :: Integer -> Integer
digitSum x
	| x == 0 = 0
	| x > 0 = (digitSum (x `div` 10)) + x `mod` 10
	| otherwise = digitSum $ negate x

getAns :: [Integer] -> [[Integer]]
getAns (a:b:c:_) = let tans = filter (\(a, b) -> a == digitSum b && b >= 1 && b <= 1000000000) $ map (\x -> (x, x^a * b + c)) [1..81]
					in [[fromIntegral $ length tans], map snd tans]


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE ViewPatterns      #-}
#ifndef DEBUG
{-# LANGUAGE Safe              #-}
#endif

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.State.Strict
import qualified Data.Array                 as A
import qualified Data.Array.Unboxed         as UA
import qualified Data.Array.ST.Safe         as MA
import           Data.Bool
import qualified Data.ByteString.Builder    as B
import qualified Data.ByteString.Char8      as C
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict         as IM
import qualified Data.IntSet                as IS
import qualified Data.List                  as L
import qualified Data.List.NonEmpty         as NL
import           Data.Monoid
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import           Data.Ratio
import           Data.Semigroup
import qualified Data.Set                   as S
import           Data.Tuple
import           Foreign
import qualified System.IO                  as IO
#ifdef DEBUG
import           Debug.Trace
#endif

#define MOD 1000000007

main :: IO ()
main = do
  [n, m] <- map read.words <$> getLine
  print $ solve n m

solve :: Int -> Int -> IntMod
solve n m | m < n = solve m n
solve 1 1 = 2
solve n m = resM * 2 - 2 + resN * 2
  where
    !resN = last . take n $ go 1 2
    !resM = last . take m $ go 1 2
    go !x !y = x : go y z
      where
        !z = x + y
-------------------------------------------------------------------------------
-- Data.IntMod.Safe
-------------------------------------------------------------------------------

modulus :: (Num a) => a
modulus = MOD
{-# INLINE modulus #-}

infixr 8 ^%
infixl 7 *%, /%
infixl 6 +%, -%

(+%) :: Int64 -> Int64 -> Int64
x +% y = case x + y of
    r | r < MOD -> r
      | otherwise -> r - MOD
{-# INLINE (+%) #-}

(-%) :: Int64 -> Int64 -> Int64
x -% y = case x - y of
    r | r < 0 -> r + MOD
      | otherwise -> r
{-# INLINE (-%) #-}

(*%) :: Int64 -> Int64 -> Int64
x *% y = x * y `rem` MOD
{-# INLINE (*%) #-}

-- |
-- >>> 1 /% 0
-- 0
(/%) :: Int64 -> Int64 -> Int64
x /% y = go y MOD 1 0
  where
    go !a !b !u !v
        | b > 0 = case a `quot` b of
            q -> go b (a - q * b) v (u - q * v)
        | otherwise = x * (u + MOD) `rem` MOD
{-# INLINE (/%) #-}

(^%) :: Int64 -> Int -> Int64
x ^% n
    | n > 0 = go 1 x n
    | n == 0 = 1
    | otherwise = go 1 (1 /% x) (-n)
  where
    go !acc !y !m
        | m .&. 1 == 0 = go acc (y *% y) (unsafeShiftR m 1)
        | m == 1 = acc *% y
        | otherwise = go (acc *% y) (y *% y) (unsafeShiftR (m - 1) 1)

newtype IntMod = IntMod{getIntMod :: Int64} deriving (Eq, Ord)

intMod :: (Integral a) => a -> IntMod
intMod x = fromIntegral $ mod (fromIntegral x) MOD
{-# INLINE intMod #-}

intModValidate :: IntMod -> Bool
intModValidate (IntMod x) = 0 <= x && x < MOD
{-# INLINE intModValidate #-}

instance Show IntMod where
    show (IntMod x) = show x

instance Bounded IntMod where
    minBound = IntMod 0
    maxBound = IntMod $ MOD - 1

instance Enum IntMod where
    toEnum = intMod
    fromEnum = fromIntegral

instance Real IntMod where
    toRational (IntMod x) = toRational x

instance Integral IntMod where
    quotRem x y = (x / y, x - x / y * y)
    toInteger (IntMod x) = toInteger x

instance Num IntMod where
    (IntMod x) + (IntMod y) = IntMod (x +% y)
    (IntMod x) - (IntMod y) = IntMod (x -% y)
    (IntMod x) * (IntMod y) = IntMod (x *% y)
    abs = id
    signum = const (IntMod 1)
    fromInteger x = IntMod . fromInteger $ mod x modulus

instance Fractional IntMod where
    (IntMod x) / (IntMod y) = IntMod (x /% y)
    fromRational q = fromInteger (numerator q) / fromInteger (denominator q)


main = interact $ show . solve . map read . words

solve :: [Integer] -> Integer
solve [n,m]
  | m >= n = n
  | otherwise = (bsrch 0 n) + m
  where bsrch l r
          | l + 1 >= r = r
          | now > 0 && now - m > 0 = bsrch mid r
          | otherwise = bsrch l mid
          where mid = (l + r) `div` 2
                now = n - mid * (mid + 1) `div` 2

stupid [n,m] = stupid_ 0 n
  where stupid_ d c
          | c - d <= 0 = d
          | otherwise = stupid_ (d + 1) (min n $ c - d + m)


main =do
      e<-getLine
      let (a:b:[])=map read (words e)::[Integer]
      print $ if a==b then a else 1


import Control.Monad

main = interact program

program :: String -> String
program input =
    let cs:ns:_ = lines input
        _:k:_ = map read $ words cs :: [Int]
        numbers = map read $ words ns :: [Int]
        result = solve (k - 1) numbers
    in show result

solve :: Int -> [Int] -> Int
solve k ns =
    let h = ns !! k
        filtered = takeWhile (\n -> (n >= h) && (n /= 0)) ns
    in length filtered


main = getLine >>= print . solve . read

solve :: Integer -> Integer
solve n = (n - 3) * 9 * 4 ^ (n - 3) + 6 * 4 ^ (n - 2)


-- Packages installed: split text hashtables vector
-- vector-algorithms parsec bytestring unordered-containers
-- hashable scientific random async stm aeson
-- Run using: runghc file.hs
import Control.Applicative

main = do
  x <- getLine
  inp <- fmap (map read . words) getLine
  putStrLn $ if solve inp then "YES" else "NO"

correctSeq = f <$> [[LT], []] <*> [[EQ], []] <*> [[], [GT]]
  where
    f  x y z = x ++ y ++ z

solve :: [Int] -> Bool
solve inp = norm `elem` correctSeq
  where
    norm = compress Nothing norm'
    compress m [] = maybe [] (:[]) m
    compress Nothing (x:xs) = compress (Just x) xs
    compress (Just x) (a:as) | x == a = compress (Just a) as
                             | otherwise = x:compress (Just a) as
    norm' = zipWith compare inp (tail inp)


import Control.Monad
import Control.Applicative

f n
  | n <= 2 = 1
  | otherwise = f (n - (f (n-1))) + (f (n - (f (n-2))))

a n = n - (floor $ (fromIntegral n + 1)/3)

main = do
  n <- readLn :: IO Int
  print $ a n


module Main (main)
    where

import Data.List (group, sort)

main :: IO ()
main = putStrLn . chat . isGirl =<< getLine
    where isGirl = (0==) . (`mod` 2) . length . group . sort
          chat True  = "CHAT WITH HER!"
          chat False = "IGNORE HIM!"


import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
import Data.Int
import Data.Bits
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy.Char8 as B

readInts :: IO String -> IO [Int]
readInts = fmap (map (foldl' (\x y -> 10*x + digitToInt y) 0) . words)

readInts64 :: IO String -> IO [Int64]
readInts64 = fmap (map (foldl' (\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words)

stringFromList :: Show a => [a] -> String
stringFromList = unwords . map show

main :: IO()
main = do
    input1 <- getLine
    n:_ <- readInts getLine
    str <- fmap words getContents
    let p1  = input1!!0
        p2  = input1!!1
        (a,b,c) = foldl' (\(x1,x2,x3) (f:l:_) ->
            let y1 = if f==p1 && p2==l then 1 else 0
                y2 = if f==p2          then 1 else 0
                y3 = if l==p1          then 1 else 0
                in (x1+y1,x2+y2,x3+y3) ) (0,0,0) str
    if a>0 || (b>0&&c>0)
        then putStr "YES"
        else putStr "NO"