{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -XStrict -XStrictData #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bifunctor
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.IORef
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Tuple
import qualified Data.IntSet as IS
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import Data.STRef.Strict
import System.IO
import System.IO.Unsafe

(><) a b = a Seq.>< b

deb name s e = seq s unsafePerformIO $! do
    hPutStrLn stderr $ " " ++ name ++ " = " ++ show s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

modifyArray f a i = readArray a i >>= \v -> writeArray a i (f v)

mdRef = unsafePerformIO $ newIORef 0

setMod = writeIORef mdRef

md :: Int64
md = unsafePerformIO (readIORef mdRef)

newtype MInt = MInt Int64 deriving Eq

instance Show MInt where
    show (MInt a) = show a

instance Num MInt where
    (MInt a) + (MInt b) =
        let r = a + b in
            MInt $ if r >= md then r - md else r
    (MInt a) * (MInt b) = MInt $ (a * b) `mod` md
    abs = id
    signum (MInt a) = MInt $ signum a
    fromInteger a = MInt $ fromInteger (a `mod` fromIntegral md)
    negate (MInt 0) = 0
    negate (MInt a) = MInt $ md - a

instance Fractional MInt where
  recip a = a ^ (md - 2)
  fromRational x =
        let a = numerator x `mod` fromIntegral md
            b = denominator x `mod` fromIntegral md
        in
            MInt (fromInteger a) / MInt (fromInteger b)

main = do
    [n,md'] <- map parseInt . BS.words <$> BS.getLine
    setMod (fromIntegral md')
    let makeMInt = MInt md
        c = runSTArray $ do
            c <- newArray ((0,0),(n,n)) 0 :: ST s (STArray s (Int,Int) MInt)
            forM_ [0..n] $ \i -> do
                writeArray c (i,0) 1
                writeArray c (i,i) 1
                forM_ [1..i-1] $ \j -> do
                    a <- readArray c (i-1,j-1)
                    b <- readArray c (i-1,j)
                    writeArray c (i,j) (a+b)
            return c
        p2 = listArray (0,n) $ map (2^) [0..n] :: Array Int MInt
    let f = runSTArray $ do
            f <- newArray ((0,0),(n,n)) 0 :: ST s (STArray s (Int,Int) MInt)

            writeArray f (0,0) 1
            writeArray f (1,0) 1
            forM_ [2..n] $ \i -> do
                writeArray f (i,0) (p2 ! (i-1))
                forM_ [1..i `div` 2] $ \j -> do
                    r <- sum <$> forM [1..i-2] (\k -> do
                        let v1 = p2 ! (k-1)
                        v2 <- readArray f (i-k-1,j-1)
                        let v3 = c ! (i-j,k)
                        return $ v1 * v2 * v3)
                    writeArray f (i,j) r
            return f
    let r = sum [f ! (n,i) | i <- [0..n]]
    print r


{-# LANGUAGE BlockArguments #-}

import Control.Arrow
import Data.List

main = do { x <- getLine; putStrLn $ (read >>> solve) x }

solve :: Integer -> String
solve x | x `mod` 2 == 1 = "Ehab"
        | x `mod` 2 == 0 = "Mahmoud"


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

main = do ts <- map read . words <$> getLine
          print $ solve ts

solve ts = minimum $ map (\t -> calc t ts) ts

count _ [] = 0
count x (l:ls)
    | x == l = 1 + count x ls
    | otherwise = count x ls

calc t ts = if 2 <= count t ts
            then foldl (+) 0 ts - t * min 3 (count t ts)
            else foldl (+) 0 ts


import Data.List

main = do
  _ <- getLine
  inp <- fmap (map read . words) getLine
  x <- fmap (map read . words) getLine
  putStrLn $ solve inp x

solve :: [Int] -> [Int] -> String
solve inp x = if not (sort res' == res') then "Yes" else "No"
    where
      res' = res inp (sortBy (flip compare) x)
      res (0:a) (b:bs) = b:res a bs
      res (a:as) bs = a:res as bs
      res [] [] = []


main = interact $ show . f . read
f x = div x 2 - if odd x then x else 0


solve a b c =
    let items = minimum [a, b `div` 2, c `div` 4]
    in items * 7

main :: IO ()
main = do
    a <- getLine
    b <- getLine
    c <- getLine
    print $ solve (read a) (read b) (read c)


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

import Control.Monad
import Text.Printf

import Data.IORef
import System.IO.Unsafe

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

import Debug.Trace

solve = do a <- cin :: IO Integer
           b <- cin
           x <- cin
           y <- cin
           let x' = x `div` (gcd x y)
               y' = y `div` (gcd x y)
               a' = a - a `mod` x'
               b' = b - b `mod` y'
               xs = [(a',a'*y'`div`x'), (b'*x'`div`y',b')]
           return . g (x,y)
             . maximumBy (comparing area) $ filter ((a*b>=).area) xs
  where
    area (x,y) = x*y
    g (x,y) s@(a,b)
      | area s < 1 = (0,0)
      | True        = s

main = solve >>= \(x,y) -> printf "%d %d\n" x y

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

instance Read' Rational where
  read' = toRational . (read :: String -> Integer)

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


s :: String -> [Double]
s str = [hour' * 30 + min * 0.5, min * 6]
    where (pre, suf) = break (== ':') str
          (hour, min) = (read pre, read (tail suf))
          hour' | hour >= 12 = hour - 12
                | otherwise = hour

main = interact $ unwords . map show . s


main = do
    [a, b] <- fmap (map read . words) getLine :: IO [Integer]
    let nt = a `div` b
    putStrLn $ if odd nt then "YES" else "NO"


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

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

solve :: Int -> Int -> Int -> String
solve n a b = show min ++ " " ++ show max
    where min = (n - a) + (sum $ take a $ iterate (*2) 1)
          x   = last $ take b $ iterate (*2) 1
          max = (n - b) * x + (sum $ take b $ iterate (*2) 1)

main :: IO ()
main = do
    [n, a, b] <- readInts
    putStrLn $ solve n a b


import Data.Char
import Control.Applicative

main = do [a,b] <- map read . words <$> getLine
          print $  solve a b

solve :: Int -> Int -> Int
solve a b
  | a < b = b
  | otherwise = head $ filter f [(a+1)..]
   where f c = (b'==) . filter (flip elem [4,7]) . map digitToInt . show $ c
         b' = map digitToInt . show $ b


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Char8 as B

main = do
  [l, r] <- fmap readInts B.getLine
  print $ solve l r

solve l r
  | l == r = l
  | otherwise = 2

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words


import Control.Applicative
import Data.Array

main= do
	n<- read  <$>getLine::IO Integer
	let s1 = sum $ map (div n) [2,3,5,7, 30,42,70,105]
	let s2 = sum $ map (div n) [6,10,14,15,21,35,210]
	print $ n-s1+s2


solve [x] = x+15
solve (x:y:s) =
            if y-x > 15 then x+15
            else solve (y:s)
main = interact $ show . min 90 . solve . (0 :) . map read . tail . words


readTokenLine :: Read a => IO [a]
readTokenLine = do
  s <- getLine
  return $ read <$> words s

maybeDiv :: Integral a => a -> a -> Maybe a
maybeDiv a b | a `mod` b == 0 = Just $ a `div` b
             | otherwise      = Nothing

exGCD :: Integer -> Integer -> (Integer, Integer, Integer)
exGCD a b | a == 0    = (b, 0, 1)
          | otherwise = (gcd, y - (b `div` a) * x, x)
            where
              (gcd, x, y) = exGCD (b `mod` a) a

diofantine :: Integer -> Integer -> Integer -> Maybe (Integer, Integer)
diofantine a b d = do
  let (gcd, preX, preY) = exGCD a b
  c <- d `maybeDiv` gcd
  let x = preX * c
      y = preY * c
      dx = b `div` gcd
      dy = a `div` gcd
      m = y `div` dy
  return (x + dx * m, y - dy * m)

solve :: Integer -> Integer -> Integer -> Integer -> [Integer]
solve n p w d = case diofantine w d p of
  Nothing     -> [-1]
  Just (x, y) -> if x + y > n || x < 0 || y < 0 then [-1] else [x, y, n - x - y]

main :: IO ()
main = do
  [n, p, w, d] <- (readTokenLine :: IO [Integer])
  let result = solve n p w d
  putStrLn . unwords $ show <$> result


primes = sieve [2..]
sieve (x:xs) = x : sieve (filter (\i -> i `mod` x /= 0) xs)

main = do
  n <- readLn
  let ans = filter f [1..n]
  print $ length ans

f n = (length $ filter (\i -> n`mod`i == 0) $ takeWhile (<=n) primes) == 2


import Control.Applicative
import Text.Printf

newtype Fixed = Fixed Double deriving (Read)

eps = 1e-9
instance Eq Fixed where
	Fixed a == Fixed b = abs (a - b) < eps
instance Ord Fixed where
	Fixed a <= Fixed b = a <= b + eps

data Result = Result Fixed Int Int

instance Eq Result where
	Result t1 x1 y1 == Result t2 x2 y2 = t1 == t2 && x1 == x2 && y1 == y2
instance Ord Result where
	Result t1 x1 y1 <= Result t2 x2 y2 = t1 < t2 || t1 == t2 && x1 + y1 > x2 + y2

main = do
	ws <- words <$> getLine
	let [t1, t2, _, _, t0] = map read ws
	let [_, _, x1, x2, _] = map read ws
	if t1 == t2
	then
		printf "%d %d" x1 x2
	else
		let
			rs = (Result (Fixed t2) 0 x2) : [Result (Fixed t) y1 y2 | y1 <- [1..x1],
				let y2 = ceiling $ ((fromIntegral y1)*(t0-t1)) / (t2-t0),
				y2 <= x2,
				let t = (t1*(fromIntegral y1) + t2*(fromIntegral y2)) / fromIntegral (y1+y2),
				t >= t0]
			(Result _ y1 y2) = minimum rs
		in
		 	 printf "%d %d" y1 y2


--fonk k a = a
fonk k [] = "NO"
fonk k (s:str)
    |s =='G' || s == 'T'= "YES"
    |s =='#' = "NO"
    |otherwise = fonk k (drop (k-1) str)

helper2 k (s:str) =
    if s =='G' || s=='T'
    then fonk k (drop (k-1) str)
    else helper2 k str

helper (a:b:c:_) = helper2 (read b) c
--helper (a:b:c:_) = b
main = interact $ helper.words


{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit

main :: IO ()
main = do
  [n,b] <- map readI64 . words <$> getLine
  let factlist = factors b
      pows = map (\(p,e) -> (`quot` e) $ sum $ takeWhile (> 0)
                   $ iterate (`quot` p) (n `quot` p)) factlist
  print $ minimum pows

factors :: Int64 -> [(Int64, Int64)]
factors n = go2 n 0
  where
    go2 n !acc | not (testBit n 0) = go2 (n `shiftR` 1) (acc+1)
               | acc == 0          = go n (sqrtInt n) 3
               | otherwise         = (2,acc) : go n (sqrtInt n) 3
    go !n !till !p | n == 1 = []
                   | p > till = [(n,1)]
    go !n !till !p | r /= 0 = go n till (p+2)
                   | otherwise = count q 1
      where
        (q,r) = divMod n p
        count !n1 !acc | r1 /= 0 = (p,acc) : go n1 (sqrtInt n1) (p+2)
                       | otherwise = count q1 (acc+1)
          where
            (q1,r1) = divMod n1 p

sqrtInt = ceilI64 . sqrt . toDouble

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N


import Data.List (intercalate)

tri = [n * (n + 1) `div` 2 | n <- [1..]]  -- sequence of triangular numbers
trii = zip [1..] tri  -- tri with index

solve n = [1..(m-1)] ++ [n - sum [1..(m-1)]]
  where
    (m, t) = last $ takeWhile (\(i, t) -> t <= n) trii

infixr 2 >>>
(>>>) a b = b . a

main =
  getLine >>= (read :: String -> Int) >>> \n ->
  let result = solve n in
  putStrLn (show (length result)) >>
  putStrLn (intercalate " " (map show result))


import Data.Char

main = do getLine >>= print . (\x -> sum (gao x) - if ok x then 1 else 0)  . map digitToInt

ok [a] = True
ok (a:b:c) = abs (a - b) <= 1 && ok (b:c)

gao [a] = take 10 $ repeat 1
gao (a:b:c) = [d!!j + if odd (i + b) then d!!(j+1) else 0 | i <- [0 .. 9], j <- [div (i + b) 2]] where
	d = gao (b:c)


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

solve :: [Int] -> Int
solve (a:b:c:_:e:_) = (a + b + c) ^ 2 - a ^ 2 - c ^ 2 - e ^ 2


--ghc 7.10

voteResult :: (Num a, Ord a) => a -> a -> a -> String
voteResult x y z
    | x > y && x-y-z > 0 = "+"
    | x < y && x-y+z < 0 = "-"
    | x == y && z == 0 = "0"
    | otherwise = "?"

main = do
    line <- getLine
    let [x,y,z] = map read . words $ line :: [Int]
    putStrLn $ voteResult x y z


-- 846A

import Data.List (group)

rle = map length . group

main = getLine >> (interact $ show . program . rle . input)
  where input xs = '0' : filter (\x -> (x=='0')||(x=='1')) xs ++ "1"

program xs = maximum [g l r | i <- [1..(length xs)], let (l, r) = splitAt (i-1) xs] - 2

f []     = 0
f (x:xs) = x + (f (drop 1 xs))

g xs ys = f xs + f (reverse ys)


{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad

solve :: Int -> [(Int, Int)] -> Int
solve !n ((pages, dayOfWeek) : xs)
  | n - pages <= 0 = dayOfWeek
  | otherwise      = solve (n - pages) xs

main :: IO ()
main = do
  n   <- readLn
  xs  <- map read . words <$> getLine
  print $ solve n $ cycle (zip xs [1 ..])


-- Vicfred
-- https://codeforces.com/problemset/problem/189/A

import Data.Array

solve :: Int -> [Int] -> Int
solve n ls = memo ! n
    where
        dyn :: Int -> Int
        dyn 0 = 0
        dyn n = 1 + maximum (minBound : [memo ! (n - x) | x <- ls, n-x >= 0])
        memo = listArray (0,n) (map dyn [0..n])

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


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.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

-- best result only selecting numbers <= i
solve :: Integer -> Integer -> Integer
solve 1 10 = -1
solve n t = base + (t - base `mod` t)
    where base = 10 ^ (n - 1)

main :: IO ()
main = do
    [a, b] <- getIntList
    print $ solve (toInteger a) (toInteger b)


main :: IO()
main = do
    line <- getLine
    let (x1:y1:x2:y2:[]) = map (\x -> read x :: Integer) $ words line
        xDiff = (x2 - x1 + 2) `div` 2
        yDiff = (y2 - y1 + 2) `div` 2
        xDiff2 = xDiff - 1
        yDiff2 = yDiff - 1
        result = (xDiff * yDiff) + (xDiff2 * yDiff2)
    putStrLn $ show $ result


import Control.Applicative
import Data.List

main = do
    [n, k] <- map (read :: String -> Int) <$> words <$> getLine
    tmp <- map (read :: String -> Int) <$> words <$> getLine
    let (a, ind) = unzip . sort $ zip tmp [1..]
    let xs = map (\(x, y, z) -> y) $ takeWhile ((<= k) . (\(x, y, z) -> z)) (zip3 a ind (scanl1 (+) a))
    putStrLn $ show . length $ xs
    putStrLn $ concat . (intersperse " ") . (map show) $ xs


module Main where

import Control.Applicative
import Data.Int

pow :: Int64 -> Int64 -> Int64
pow a 0 = 1
pow a n | even n = c * c
        | otherwise = c * c * a
    where m = n `div` 2
          c = pow a m

countWays :: Int64 -> Int64 -> Int64
countWays _ 0 = 0
countWays n sum | amax >= amin = amax - amin + 1
                | otherwise = 0
    where amin = max 1 (sum - n)
          amax = min n ((sum - 1) `div` 2)

countSum :: Int64 -> Int -> Int64
countSum n 0 = n * (n - 1) `div` 2
countSum n nines = sum [countWays n (base * k - 1) | k <- [1 .. 9]]
    where base = pow (fromIntegral 10) (fromIntegral nines)

solve :: Int64 -> Int64
solve n = head . filter (/= 0) $ [countSum n nines | nines <- [9, 8 .. 0]]

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


main :: IO()
main = do
    input <- getLine
    input <- getLine
    let list = getList input
    putStrLn $ answer list

getList :: String -> [Int]
getList x = map read $ words x

answer :: [Int] -> String
answer [] = "no"
answer [x] = "no"
answer list = solve [init] (tail list)
    where init = sortPair (head list) (head $tail list)

sortPair :: Int -> Int -> (Int, Int)
sortPair x y =
    if x < y then (x, y) else (y, x)

-- this function is mapping everything O(N^2)
solve :: [(Int, Int)] -> [Int] -> String
solve ps [] = "no"
solve ps [x] = "no"
solve ps xs =
    if inter then "yes" else solve (pair : ps) (tail xs)
    where inter = or $ map (intersects pair) ps
          pair = sortPair (head xs) (head $ tail xs)

intersects (aL, aR) (bL, bR) =
    if aL <= bL then
        if bL < aR then
            if aR < bR then (aL /= bL)
            else if aR == bR then (aL == bL)
            else False
        else False
    else
        if aL < bR then
            if aR <= bR then False
            else True
        else False


toint s = (read s) :: Int

solve::String -> String
solve sss =
  let (n:ss) = map toint $ words sss in
  let x = take n ss in
  let y = take n $ drop n ss in
  if (sum x) >= (sum y) then
    "Yes\n"
  else
    "No\n"

main = interact solve


import Data.List

getNextString :: String -> Int -> String
getNextString s pos = take pos s ++ [next (s !! pos)]
        ++ replicate (length s - pos - 1) 'a'
    where
        next :: Char -> Char
        next 'z' = 'z'
        next c = succ c

solve :: String -> String -> [String]
solve s t =
    filter (\ x -> s < x && x < t) (map (getNextString s) [0..length s - 1])

main = do
    s <- getLine
    t <- getLine
    let res = solve s t
    if null res then
        putStrLn "No such string"
    else
        putStrLn $ head res


import Data.List

getPermut :: [Integer] -> Integer -> Integer -> [Integer]
getPermut ls 0 0 = ls
getPermut ls ps pn
    | pn `mod` 2 == 0 =  getPermut ([ps] ++ ls)(ps - 1)(pn `quot` 2)
    | pn `mod` 2 == 1 =  getPermut (ls ++ [ps])(ps - 1)(pn `quot` 2)

solve :: Integer -> Integer -> [Integer]
solve ps pn = getPermut [ps] (ps - 1) (pn - 1)

main :: IO ()
main = do
    [ps, pn] <- fmap (map read . words) getLine
    putStrLn (intercalate " " (map show (solve ps pn)))


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function
import           Text.Printf
-- import           Data.ByteString (ByteString)
-- import qualified Data.ByteString.Char8 as C
-- import           Data.ByteString.Char8 ()
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))
-- import qualified Data.Sequence as S

myread = read :: String -> Int
main = do
  [hh,mm] <- map myread . (\xs -> [take 2 xs, drop 3 xs]) <$> getLine
  m <- readLn
  solve hh mm m

solve :: PrintfType r => Int -> Int -> Int -> r
solve hh mm m = printf "%02d:%02d\n" nh nm where
  nh = mod (hh+(div (mm+m) 60)) 24
  nm = mod (mm+m) 60


import Data.Functor

getInts :: IO [Int]
getInts = map read <$> words <$> getContents

main = getInts >>= putStrLn . (\b -> if b then "YES" else "NO") . solve

solve (a1:b1:a2:b2:a3:b3:[]) = or [
    check a1 b1 (a2 + a3) (max b2 b3),
    check a1 b1 (a2 + b3) (max b2 a3),
    check a1 b1 (b2 + a3) (max a2 b3),
    check a1 b1 (b2 + b3) (max a2 a3)]

check a1 b1 a2 b2 = or [a2 <= a1 && b2 <= b1, a2 <= b1 && b2 <= a1]


module Main where

import Data.Char
import Data.Functor
import Text.Printf

solve :: Int -> Int -> Int
solve 1 _ = 0
solve n b =
  {- trace str -} ans
  where
    arr = takeWhile (<= n). map (2^) $ [1..]
    k = last. takeWhile (<= n). map (2^) $ [1..]
    couples = k `div` 2
    playersAdvanced = couples + n-k
    --str = printf "n = %d, arr = %s, k = %d, couples = %d, curAns = %d" n (show arr) k couples curAns
    curAns = k*b + couples
    ans = curAns  + solve playersAdvanced b

main :: IO ()
main = do
  [n, b, p] <- map read. words <$> getLine
  printf "%d %d" (solve n b) (n*p)


import Control.Monad

main :: IO ()
main = do
    n <- read <$> getLine
    print $ product (2:[1..(n-1)]) `div` n


{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import Data.List

readInt = fst . M.fromJust . C.readInt

run 0 xs | 0 `elem` xs = 1 | otherwise = 0
run x xs | x `elem` xs = 1 + (x - length [y | y <- xs, y < x])
         | otherwise = x - length [y | y <- xs, y < x]

main = do
    (map readInt . C.words -> [n, x]) <- B.getLine
    (map readInt . C.words -> xs) <- B.getLine
    print $ run x xs


import Data.List
gao '>' = 8
gao '<' = 9
gao '+' = 10
gao '-' = 11
gao '.' = 12
gao ',' = 13
gao '[' = 14
gao ']' = 15

main = interact $ show.foldr (\x acc -> ((gao x) + acc * 16) `mod` 1000003) 0.reverse.head.words


{-# OPTIONS_GHC -O2 #-}
--import Data.Array
import Data.Array (Array(..))
import Data.Array.Base
readPair = fmap ((\[x,y] -> (x,y)).map read.words) getLine :: IO (Integer,Integer);
main = do {
    (w,h) <- readPair;
    if w > 1 && h > 1 then do {
    let
    {
        nw x = min x $ w-x;
        nh y = min y $ h-y;
        aw = listArray (1,w-1) $ map nw [1..w-1] :: Array Integer Integer;
        ah = listArray (1,h-1) $ map nh [1..h-1] :: Array Integer Integer;
        a = array (1,(w-1)*(h-1)) [ (((x-1)*(w-1) + y), (aw!x) * (ah!y)) | x <- [1..w-1], y <- [1..h-1]]
             :: Array Integer Integer;
        aSum = sum' aw * sum' ah
        --ans = map (\(x,y) -> nw x * nh y) [(x,y) | x <- [1..w-1], y <- [1..h-1]];
    };
    print aSum;
    }
    else do {
    print 0
    };
    };
sum' arr = s' (fromIntegral $ (length.indices $ arr)) 0
    where
        s' 0 acc = acc
        s' i acc = s' (i-1) (acc + arr ! i)


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception hiding (mask)
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, runSTArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.IntMap.Strict as IM
import qualified Data.Set as S
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, STArray, Ix(..))
import Debug.Trace

bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep n f=foldr((>>).f)(return())[0..n-1]
rev n f=foldr((>>).f.negate)(return())[1-n..0]
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for a b f=foldr((>>).f)(return())[a..b]
{-# INLINE rep #-}
{-# INLINE rev #-}
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

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

solve :: Int -> Int -> Int
solve n m = go 0 n m
   where
     go !res n m
       | m < n = go res m n
       | n > 0 && m > 1 = go (res+1) (n-1) (m-2)
       | otherwise = res


-- Codeforces 909B

import Control.Applicative

main :: IO ()
main = do
    n <- read <$> getLine :: IO Int
    print $ (n `div` 2 + 1) * ((n + 1) `div` 2)


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.Int
import Data.Bits
import Data.Ratio
import Data.IORef
import Data.Array.IO
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map              as Map
import qualified Data.Set              as Set
import Text.Printf
import Debug.Trace
import System.Exit

getint :: IO Int
getint  = head <$> getints

getints :: IO [Int]
getints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine

getnums :: Num a => IO [a]
getnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine

getstr = getLine

outCount a b c m = t
  where
    k = max 0 $ (b + c + m - a + 1) `div` 2
    t = if k <= m then (m - k + 2) * (m - k + 1) `div` 2 else 0

solve a b c l m
  | m > l = 0
  | otherwise = t + solve a b c l (m + 1)
  where
    t = (m + 2) * (m + 1) `div` 2 - ka - kb - kc
    ka = outCount a b c m
    kb = outCount b c a m
    kc = outCount c a b m

main = do
  [a, b, c, l] <- getnums :: IO [Int64]
  putStrLn . show $ solve a b c l 0


module Main where

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
    n <- readLn :: IO Int
    let ans = solve n
    print ans

solve :: Int -> Int
solve n = seek n 1 1
    where
        seek n k v
            | w > n          = v
            | n `mod` w == 0 = seek n (k+1) w
            | otherwise      = seek n (k+1) v
            where
                w = (2^k-1)*(2^(k-1))


import Data.List
import Data.Map hiding(map,filter)

toInts = map (charToInt!)
	where charToInt = fromList$zip (['0'..'9']++['A'..'Z']) [0..]

toInt radix = foldl step 0.toInts
	where step a b = a*radix+b

check (h,m) r = toInt r h < 24 && toInt r m < 60

result t@(h,m)
	| check t 60 = [-1]
	| not(check t start) = [0]
	| otherwise = filter (check t) [start..59]
	where start = 1 + maximum (toInts h++toInts m)

parse = remove.break (==':')
	where remove (h,hm:tm) = (h,tm)

main=interact$unwords.map show.result.parse.head.lines


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

main = do
    l <- getLine
    print (mod (solve l) 1000000007)

solve :: String -> Integer
solve l | i < 0 = 0
        | otherwise = 2^i*(2^(2*n) + (solve l')*2)
    where
        i  = fromMaybe (-1) (elemIndex '1' l)
        l' = drop (i+1) l
        n  = fromIntegral $ length l'


main :: IO ()
main = getLine >>= putStrLn . showFraction . solve . read
showFraction :: (Integer, Integer) -> String
showFraction (a, b) = show (div a g) ++ "/" ++ show (div b g)
    where g = gcd a b
          gcd x y = if y == 0 then x else gcd y (mod x y)

cal :: Integer -> Integer -> (Integer, Integer)
cal n r = if r >= n
    then (0, r-n)
    else let (c, r2) = cal n (r*2) in (c+1, r2)

solve :: Integer -> (Integer, Integer)
solve n = if mod n 2 == 0
    then let (a, b) = solve (div n 2) in (a + b, b)
    else if n == 1 then (0, 1) else let (a, b) = go n 1 in (a, b-1)

go :: Integer -> Integer -> (Integer, Integer)
go n r = let (c, r2) = cal n r
             p = 2 ^ c
             cur = p * r * c
  in if r2 == 1
       then (cur, p)
       else let (a, b) = go n r2 in (a+cur*b, b*p)


factors :: Integer -> [Integer]
factors n' = aux n' 2 [] 1
  where aux n _   acc 1 | n == 1           = acc
        aux n lst acc 1 | lst*lst > n      = n:acc
        aux n lst acc p | n `mod` lst == 0 = aux (n `div` lst) lst acc (p * lst)
        aux n lst acc p                    = aux n (lst+1) (if p > 1 then p:acc else acc) 1

trySplit :: [Integer] -> Integer
trySplit xs' = aux xs' 1 1
  where aux [] l r = max l r
        aux (x:xs) l r = min (aux xs (x*l) r) (aux xs l (x*r))

go :: Integer -> IO ()
go n = putStrLn $ show cost ++ " " ++ show (n `div` cost)
  where cost = trySplit $ factors n

main :: IO ()
main = read <$> getLine >>= go


import Data.List (sort)

process :: Integral a => [a] -> [a] -> [a]
process xs ys = f (sort xs) (sort ys)
    where
        f xs [] = replicate (length xs) 1
        f [] ys = replicate (length ys) 2
        f xs@(x:xs') ys@(y:ys')
            | x < y = 1:(f xs' ys)
            | x > y = 2:(f xs ys')
            | otherwise = 1:(f xs' ys')

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,a,b] <- fmap (map readInt.words) getLine
    xs <- fmap (map readInt.words) getLine
    ys <- fmap (map readInt.words) getLine
    putStrLn.unwords.map show $ process xs ys


import Control.Applicative( (<$>))

main = do
    [l_, r_, x_, y_, k_] <- map (read::String->Integer) . words <$> getLine
    let
	search::[Integer]->Bool
	search []		= False
	search (i:is)
	  | i < l_		= search is
	  | i <= r_		= True
	  | otherwise		= False

    putStr $ if search ((k_*) <$> [max x_ (l_`quot`k_)..y_])
		then "YES"
		else "NO"


{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit
import Data.Char

main :: IO ()
main = do
  [c1,c2,c3,c4] <- replicateM 4 $ readInt <$> getLine
  print $ if c1 == c4 && (c3 == 0 || c1 > 0) then 1 else 0

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N


import Data.List
import Control.Monad

convert2 :: String -> String
convert2 ('r':'u':[]) = '.':'r':'u':[]
convert2 ('r':'u': xs) = '.':'r' : 'u' : '/' : xs
convert2  (x:xs) = x : convert2 xs

convert :: String -> String
convert s
   | "http" `isPrefixOf` s = "http://" ++ [s !! 4] ++  (convert2 $ drop 5 s)
   | "ftp" `isPrefixOf` s =  "ftp://" ++ [ s!! 3] ++ (convert2 $ drop 4 s)

main :: IO()
main = getLine >>= ( \x -> putStrLn $ convert x)


adjust _ _ [] = []
adjust 0 _ xs = xs
adjust n c (x:xs)
    | c == x    = x : adjust n c xs
    | otherwise = c : adjust (n - 1) c xs

solve xs = show n ++ "\n" ++ ms where
    ys = filter (=='x') xs
    zs = filter (=='X') xs
    diff = length ys - length zs
    n = abs (diff `div` 2)
    c = if diff < 0 then 'x' else 'X'
    ms = adjust n c xs

main = do
    input <- getContents
    let xs = last $ lines input
    putStrLn $ solve xs


import Control.Arrow
import Data.Maybe
import Data.List
import Data.Foldable

{-
import System.IO.Unsafe

debug :: (Show x) => x -> ()
debug = unsafePerformIO . print
-}

main :: IO ()
main = do
  _ <- getLine
  string <- getLine
  putStrLn $ show $  solve3 string

solve3 :: String -> Int
solve3 string = solve3' (foldl1 max string) string
  where
    solve3' :: Char -> String -> Int
    solve3' maxElem string =
      let maxElemIdx = elemIndices maxElem string
          removableIdx = filter (canDel string) maxElemIdx
      in  step removableIdx maxElem string
    step :: [Int] -> Char -> String -> Int
    step [] 'a' _ = 0
    step [] maxElem string = solve3' (pred maxElem) string
    step removableIdx maxElem string = (length removableIdx) + (solve3' maxElem $ foldl delIdx string $ sortBy (flip compare) removableIdx)

{-
solve2 :: String -> Int
solve2 string =
  let idx = [0..(length string - 1)]
      validIdx = filter (canDel string) idx
      maxElem:elems = sortBy (flip compare) $ nub string
  in  fromMaybe 0 $ asum $ flip map elems $ \elem ->
     let elemIdx = elemIndices elem string
         lookAtIdx = intersect validIdx elemIdx
     in  (debug (string, elem, lookAtIdx)) `seq` foldl max Nothing $ Just . succ . solve2 . delIdx string <$> lookAtIdx

solve :: String ->  Int
solve string =
  let idx = [0..(length string - 1)]
      validIdx = filter (canDel string) idx
  in  foldl max 0 $ succ . solve . delIdx string <$> validIdx
-}

atm :: [t] -> Int -> Maybe t
atm xs i
  | i < 0 = Nothing
  | i >= length xs = Nothing
  | otherwise = Just $ xs !! i

delIdx :: [t] -> Int -> [t]
delIdx xs = flip splitAt xs >>> id *** tail >>> uncurry (++)

canDel :: String -> Int -> Bool
canDel string i =
  let lookee = pred $ string !! i
      canDelPred = fromMaybe False $ (== lookee) <$> string `atm` (pred i)
      canDelSucc = fromMaybe False $ (== lookee) <$> string `atm` (succ i)
  in canDelPred || canDelSucc


main = getLine >>= putStrLn . solve 'a'

solve '{' remain = remain
solve _ [] = "-1"
solve ch (x:xs)
    | x <= ch = concat' ch $ solve (succ ch) xs
    | otherwise = concat' x $ solve ch xs
    where concat' ch str
              | str /= "-1" = ch : str
              | otherwise = str


import Data.Bits

main = do
  [n, p] <- map read . words <$> getLine
  print $ solve n p

solve :: Int -> Int -> Int
solve n p = go 1
  where go s
          | s == 32        = -1
          | n - s * p < s  = go (s + 1)
          | popCount (n - s * p) <= s = s
          | otherwise      = go (s + 1)


import Data.List
main = do
	a <- getLine
	let b = length.filter (=='4') $ a
	let c = length.filter (=='7') $ a
	putStrLn $ if max b c == 0
			then "-1"
			else if b >= c
				then "4"
				else "7"


import Data.Word

solve [n, a, b, p, q] =
    n `div` a * p + n `div` b * q - n `div` (a `div` gcd a b * b) * min p q :: Word64

main = interact $ unlines . map (show . solve . map read . words) . lines


{-# LANGUAGE TypeApplications #-}
main = interact $ show . solve . map (read @Int) . tail . words
solve (k:as) = length ls + length rs where
  (ls,as') = break (> k) as
  rs = takeWhile (<= k) (reverse as')


import Data.Maybe
import Control.Monad
main = interact $ show . solve . map read . tail . words
solve (k:as) = minimum $ mapMaybe (\a -> let (d,r) = k `divMod` a in guard (r == 0) *> pure d) as


import Data.List
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
main=   readsolveprint
readsolveprint::IO()
readsolveprint = interact $ unlines.solve. map digitToInt.head.lines
solve :: [Int]-> [String]
solve (x:xs) = slv2 $ slv1 x xs
slv1 0 [] =[]
slv1 0 (x:xs) = slv1 x xs
slv1 x xs = [[1]++map (\a->if a==0 then 0 else 1) xs] ++ slv1 (x-1) (map (\a->if a==0 then 0 else a-1) xs)
slv2 xss = [show $ length xss] ++ [unwords $ map (map intToDigit) xss]


import Control.Applicative
import Data.List

main= do
	  [n,c]<- map read. words <$> getLine::IO [Int]
	  s<- map read. words <$> getLine ::IO [Int]
	  let m = maximum $ zipWith (-) s (tail s)
	  print $  max 0 (m-c)


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Data.Int

readInt = maybe undefined (fromIntegral . fst) . B.readInteger
readInts = fmap readInt . B.words

solve n k = (d, c, n - c - d)
  where
    d = n `div` 2 `div` (k + 1) :: Int64
    c = k * d

main = do
  [n, k] <- fmap readInts B.getLine
  let (a, b, c) = solve n k
  putStr $ show a ++ " " ++ show b ++ " " ++ show c

{-
c = kd
2*d*(k + 1) < n
-}


eqDigit :: Int -> Int -> Bool
eqDigit x y  =  eqDigit' (show x) (show y)
  where
    eqDigit' xs ys  =  any (flip elem xs) ys

solve :: Int -> Int
solve n  =  length $ concatMap solve' (takeWhile (\x -> x*x <= n) [1..])
  where
    solve' x
      | x * x == n  =  if eqDigit n x then [x] else []
      | otherwise  =  x1 ++ x2
      where
        x1  =  if mod n x == 0 && eqDigit n x then [x] else []
        x2  =  if mod n x == 0 && eqDigit n y then [y] else []
        y  =  div n x

main :: IO ()
main  =  readLn >>= print . solve


{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace

----- <Solution> --------------------------------------------------------------
data TC = TC {n :: Int, m :: Int64}

type Output = Int64

input :: Scanner TC
input = do
  n <- int
  m <- int64
  return TC {..}

solve :: TC -> Output
solve TC {..} = tot -% nonamb
  where
    n' = min 40 n
    m' = m `mod` modv
    tot = iterate (*% m') m' >$> take n >>> foldl1 (+%)
    nonamb =
      [if i `elem` primes then fi i else 1 | i <- [1 .. n']]
        >$> scanl1 (*)
        >>> map (m `div`)
        >>> map (`mod` modv)
        >>> scanl1 (*%)
        >>> foldl1 (+%)

primes :: [Int]
primes = [i | i <- [2 .. 40], all ((0 /=) . (i `mod`)) [2 .. i - 1]]

output :: Int -> Output -> C.ByteString
output _ = showB

----- </Solution> -------------------------------------------------------------

main :: IO ()
main = C.interact $ runScanner input >>> solve >>> output 0

-- main = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1..] >>> map (uncurry output) >>> C.unlines

----- Template ----------------------------------------------------------------
fi :: (Integral a, Num b) => a -> b
fi = fromIntegral

-- modular arith
modv :: Int64
modv = 998244353

(+%), (-%), (*%), (/%) :: Int64 -> Int64 -> Int64
a +% b = (a + b) `mod` modv
a -% 0 = a
a -% b = a +% (modv - b `mod` modv)
a *% b = (a * b) `mod` modv
a /% b = a *% inv b

inv :: Int64 -> Int64
inv a = a ^% fi (modv - 2)

(^%) :: Int64 -> Int -> Int64
a ^% 0 = 1
a ^% b =
  let (q, r) = b `divMod` 2
      u = a ^% q
      v = if r == 1 then a else 1
   in u *% u *% v

infixl 6 +%

infixl 6 -%

infixl 7 *%

infixl 7 /%

infixr 8 ^%

-- Debug
debug :: Show a => a -> a
debugV :: Show a => String -> a -> a

#ifdef ONLINE_JUDGE
debug = id
debugV _ = id
#else
debug a = trace (show a) a
debugV name a = trace (name <> " = " <> show a) a
#endif

-- helpers
(>$>) = flip ($)

infixl 0 >$>

-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str = C.unpack <$> bstr

readStr :: Read a => Scanner a
readStr = read <$> str

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show


main = interact (show . f . map read . words)
f [n, m] = (2 * (1 - expm m 3 n) `div` (1 - 3)) `mod` m

expm m b k = ex b k 1 where
    ex a k s
        | k == 0         = s
        | k `mod` 2 == 0 = ex (a * a `mod` m) (k `div` 2) s
        | otherwise = ex (a * a `mod` m) (k `div` 2) (s*a `mod` m)


import Control.Monad
main = do
	[x,y] <- readInts
	res <- return $ solve x (y-1)
	printList res
	return ()

readInts :: IO [Integer]
readInts = getLine >>= return . words >>= mapM readIO
printList :: Show a => [a] -> IO ()
printList xs = mapM_ (\x -> putStr (show x ++ " ") ) xs

fib = 1:1:zipWith (+) fib (tail fib)
fibN n = fib !! fromInteger (n-1)

solve :: Integer -> Integer -> [Integer]
solve n k
	| n == 0 = []
	| n == 1 = [1]
	| k < (fibN n) =
		1:( map (+1) $ solve (n-1) k)
	| otherwise =
		2 : 1 : (map (+2) $ solve (n-2) (k-(fibN n)))


    main :: IO ()
    main = do
     n <- readLn :: IO Integer
     putStrLn $ show $ solve n

    solve n = rec n 1

    rec n i
        | i >= n = 1
        | otherwise = 1 + (rec (n-i) (i*2))


main = do
	i <- getLine
	let n = read $ init i :: Integer;
		p = last i
	let ans = (((n - 1) `div` 4) * 2 + 1 - (n `mod` 2)) * 6 + ((n - 1) `div` 4) * 4 + 1 - (n `mod` 2)
	print $ ans + f p
	where
		f 'f' = 1
		f 'e' = 2
		f 'd' = 3
		f 'a' = 4
		f 'b' = 5
		f 'c' = 6


main::IO ()
main = fmap (map read . words) getLine >>= print . solution where
  solution [n,a] | mod a 2 == 0 =  1 + (n - a) `div` 2
                 | otherwise    =  (a + 1) `div` 2


parse = (map read) . words

solve all = maximum $ getAll
    where
        getAll = [calcMixed x all | x <- [0 .. 2]]
        calcMixed n all
            | check $ (deleteMixed n all) = n + calc n all
            | otherwise = 0
        calc n = greedy . (deleteMixed n)
        check = null . (filter (<0))
        deleteMixed n = map (\x -> x - n)
        greedy = sum . (map (`div` 3))

output = show

main = interact $ output . solve . parse


import Data.List

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

listLast :: [Int] -> Int
listLast [x] = x
listLast (_:xs) = listLast xs

f0 :: String -> Bool
f0 str
  | elem '0' str = (elem '1' str)||(elem '2' str)||(elem '3' str)
  | otherwise = False

f1 :: String -> Bool
f1 str
  | elem '1' str = (elem '9' str)||((elem '7' str)&&((elem '6' str)||(elem '3' str)))
  | otherwise = False

f3 :: String -> Bool
f3 str
  | elem '3' str = (elem '7' str)||((elem '9' str)&&((elem '4' str)||(elem '1' str)))
  | otherwise = False

f7 :: String -> Bool
f7 str
  | elem '7' str = ((elem '2' str)&&((elem '6' str)||(elem '9' str)))||((elem '6' str)&&(elem '1' str))
  | otherwise = False

f9 :: String -> Bool
f9 str
  | elem '9' str = ((elem '2' str)&&((elem '4' str)||(elem '7' str)))||((elem '4' str)&&(elem '3' str))
  | otherwise = False

main = do
  (k:_) <- readInts
  str <- getLine
  if (f0 str) || (f1 str) || (f3 str)||(f7 str)||(f9 str)
    then putStrLn "YES"
    else putStrLn "NO"


-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = interact $ solve . map read . words

solve xs = if null $ filter f $ map g ys then "NO" else "YES"
    where
        f = (sum xs ==)
        g = (2*) . sum . map (xs!!)
        ys = do
            a <- [0 .. 3]
            b <- [a+1 .. 4]
            c <- [b+1 .. 5]
            return [a, b, c]


main = interact $ show . solve . map read . words
solve [a1,a2] = go a1 a2 where
  go 0 _ = 0
  go _ 0 = 0
  go 1 1 = 0
  go a1 a2 | a1 > a2 = 1 + go (a1-2) (a2+1)
           | otherwise = 1 + go (a1+1) (a2-2)


import Data.List
import Data.Maybe
import Data.Char
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.map read. words. head.  lines
solve :: [Integer]->String
solve [1,0]= "0 0"
solve [x1,x2] =  unwords $ map (foldr (\ a b-> (show a) ++ b) "") $ if head (snd ff)/=0 || head (fst ff)==0 then [[-1],[-1]] else  [if head ffff ==0 then g ffff else  ffff,fff ] where
  g (a:as) = let (a1,a2:a2s)=break (/=0) as in [1]++a1++[a2-1]++a2s
  ffff =reverse fff
  fff=fst ff
  ff=splitAt (fromIntegral x1) $ (\ns-> zipWith (\a b-> a-b) ns (tail ns ++ [0])) $ scanl f x2 [1..x1]
  f b a = if b-9>0 then b-9 else 0


calc :: Integer -> Integer
calc a =
  if a == 1 then
    0
  else
    if a `mod` 2 == 0 then
      a `div` 2
    else
      a

main :: IO ()
main = do
  s <- getLine
  let a = read s :: Integer
  print $ calc (a + 1)


{-# LANGUAGE DeriveFunctor #-}
import Control.Applicative ((<$>))
import Data.Array hiding ((//))
iLn :: IO [Integer]
iLn = getLine >>= (return . fmap (read) . words)

main = do
  [k,pa,pb] <- iLn
  print (ex k pa pb)

re a = powMod 1000000007 a 1000000005

a // b = (a * re b) `mod` 1000000007
a .* b = (a * b) `mod` 1000000007

ex k pa pb = e 0 k
  where
    me = ((memoize e))
    e 0 k = me 1 k
    e n k = if n >= k
            then n+ab `mod` 1000000007
            else (a*(me(n+1)k)+b*(n+me n (k-n))) `mod` 1000000007
    a = pa//(pa+pb)
    b = pb//(pa+pb)
    ab= a//b

memoize f n k = ((array (0,1009) [(i,array (0,1009) [(j,f i j)|j<-[0..1009]])|i<-[0..1009]])!n)!k

powMod :: Integral a => a -> a -> a -> a
powMod _ _ 0 = 1
powMod m x 1 = x `mod` m
powMod m x n
    | even n = powMod m modSquare (n`div`2)
    | otherwise = (x * powMod m modSquare ((n-1)`div`2)) `mod` m
    where modSquare = x * (x `mod` m)


module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

divu a b = (a + b - 1) `div` b

solve n t k d = n2 >= n
  where
    t1 = (n `divu` k) * t
    n2 = ((t1 - t) `div` t + (t1 - d - 1) `div` t) * k

main = do
  n:t:k:d:_ <- readInts <$> B.getLine
  putStrLn $ if solve n t k d then "YES" else "NO"


import Array
import Data.List

isDivisor :: Integral a => a -> a -> Bool
isDivisor m n  =  m `rem` n == 0

primes :: [Int]
primes  =  2 : filter isPrime [3, 5 ..]

isPrime :: Int -> Bool
isPrime n  =  all (not . isDivisor n) (takeWhile (\x -> not $ x * x > n) primes)

factorize :: Int -> [Int]
factorize 0  =  []
factorize n  =  factorize' n primes
  where
    factorize' 1 _  =  []
    factorize' n (p:ps)
      | r == 0  =  p : factorize' q (p:ps)
      | q < p  =  [n]  -- i.e. p * p > n
      | otherwise  =  factorize' n ps
      where
        (q, r)  =  quotRem n p

factorizations :: Array Int [Int]
factorizations  =  listArray (1,100) $ map factorize [1..]

solve :: [Int] -> Int
solve [a, b, c]  =  sum' [solve' i j k | i <- [1..a], j <- [1..b], k <- [1..c]]
  where
    solve' i j k  =  solve'' $ concatMap (factorizations !) [i, j, k]
    solve''  =  product . map (+1) . map length . group . sort
    sum'  =  foldl' (+) 0

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


import Data.Char

main :: IO()
main = do interact (gao . filter isPrint . unlines . lines)
    where gao p
            | p == reverse p = "YES"
            | otherwise = "NO"


import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC

check box vas apos aneg

    | vas > box = apos
    | vas < 0 = aneg
    | otherwise = 0

main :: IO ()
main =
  do all <- BS.getContents
     let Just ((v1,v2,v3), r1) = readTuple3 all
     let Just ((rec1,rec2,rec3), r2) = readTuple3 r1
     let Just ((a1,a2,a3,a4,a5,a6), _) = readTuple6 r2
     let result = (check rec1 v1 a6 a5) + (check rec2 v2 a2 a1) + (check rec3 v3 a4 a3)
     putStr $ show result ++ "\n"
  where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readTuple3 s = do (x1, r1) <- readInt s
                          (x2, r2) <- readInt r1
                          (x3, r3) <- readInt r2
                          return ((x1,x2,x3),r3)
        readTuple6 s = do (x1, r1) <- readInt s
                          (x2, r2) <- readInt r1
                          (x3, r3) <- readInt r2
                          (x4, r4) <- readInt r3
                          (x5, r5) <- readInt r4
                          (x6, r6) <- readInt r5
                          return ((x1,x2,x3,x4,x5,x6),r6)


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 $ show . sol . map read . words

sol :: [Double] -> Double
sol (1:m:_) = 1
sol (n:1:_) = 1 / n
sol (n:m:_) = (n * m - 1 + (m - 1) * (n - 1)) / (n * n * m - n)


main = do
  m <- readLn
  print $ f2 m
f :: Int -> Int
f x = quot (product [x..(2*(x-1))]) (product [1..x-1]) -- binomial (2(x-1), x-1)
f2 :: Int -> Int
f2 x = if (x/=10) then quot (product [x..(2*(x-1))]) (product [1..x-1]) else 48620


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

poss :: Int -> [(Int, Int)]
poss n = [ (x,y) | x <- [0 .. n-1], y <- [0 .. n-1], x==y || (x+y)==(n-1) || x+1==mid' || y+1==mid']
  where mid' = (n `div` 2) + 1

positions :: Int -> [Int]
positions n = map flattered (poss n)
  where flattered (x,y) = (n * x) + y

sm :: [[Int]] -> Int -> Int
sm matrix n =
  foldl add' 0 poslist
  where poslist = positions n
        flatmatrix = foldl (++) [] matrix
        add' acc x = (flatmatrix !! x) + acc

main = do
  ns <- getLine
  let n = read ns :: Int
  slist <- replicateM n getLine
  let rint x = read x :: Int
  let imap = map rint . words
  let matrix = map imap slist
  print $ sm matrix n


import Control.Monad

main = getTwoLines >>= putStrLn . decide

getTwoLines :: IO (Int, String)
getTwoLines = liftM2 toTuple getLine getLine
  where toTuple a b = (read a, b)

decide :: (Int, String) -> String
decide (n, str) = decide' flightsCount
  where flightsCount = foldr count (0, 0) [1..n - 1]
        count i (sf, fs)
          | lst == 'F' && curr == 'S' = (sf, fs + 1)
          | lst == 'S' && curr == 'F' = (sf + 1, fs)
          | otherwise = (sf, fs)
          where lst = str !! (i - 1)
                curr = str !! i

decide' :: (Int, Int) -> String
decide' (sf, fs) = if sf > fs then "yes" else "no"


isSubseq :: String -> String -> Bool
isSubseq x [] = null x
isSubseq [] x = True
isSubseq xxs@(x:xs) (y:ys) = if x == y then isSubseq xs ys else isSubseq xxs ys
endings = map show [0,8..992]
solve num = case f of {[] -> "NO"; (h:_) -> "YES\n" ++ h}
    where f = filter (`isSubseq` num) endings
main = putStrLn.solve =<< getLine


import Data.List

calc :: Integer->Integer->Integer
calc n m = foldl1 f.genericReplicate n$m
	where f a b = (a*b)`mod`1000000007

result [n,m,k]
	| k == 1 = calc n m
	| k == n = calc (a+b) m
	| k > n = calc n m
	| even k = m
	| odd k = m*m
	where (a,b) = n `divMod` 2

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


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

solve (a:b:c:n:_) = if a < n && b < n && c <= a && c <= b && 0 < d && d <= n then d else -1
  where d = n - (a + b - c)


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

modulo :: Integer
modulo = 1000000009

testcase :: [Integer] -> Integer
testcase [n,m] = if start < n then 0 else ans
    where
        start :: Integer
        start = (2 ^ m - 1) `mod` modulo -- Got to love Haskell
        ans :: Integer
        ans = foldl (\a b -> (a * b) `mod` modulo) 1 $ take (fromInteger n) $ iterate pred start


{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

import Data.Ratio

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

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

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

main = do
	[ h, m, s, t1, t2 ] <- readInts
	let
		ss = s % 1
		mm = m % 1 + s % 60
		hh = ( ( h `mod` 12 ) % 1 + mm / 60 ) * 5
		gs = map ( ( min t1 t2 % 1 * 5 ) < ) [ ss, mm, hh ]
		ls = map ( ( < max t1 t2 % 1 * 5 ) ) [ ss, mm, hh ]
		ands = zipWith (&&) gs ls
	putStrLn $ which "YES" "NO" $ all ( head ands == ) ands


import Data.Array
import Control.Arrow
import Data.List
primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71]

change i l y = take i l ++ [y] ++ drop (i+1) l
go p l = map (:l) (takeWhile (<60) (iterate (*p) p)) ++ [change i l y|(i,x)<-zip [0..] l,y<-takeWhile(<60)(iterate (*p) (x*p))]

xx = map sort $ go 2 [] >>= go 3 >>= go 5 >>= go 7 >>= go 11 >>= go 13 >>= go 17 >>= go 19 >>= go 23 >>= go 29 >>= go 31 >>= go 37 >>= go 41 >>= go 43 >>= go 47 >>= go 53 >>= go 59 :: [[Integer]]

isOk l = all p l where
  p x = length (filter (\y -> gcd x y /= 1) l) == 1
isMaximal mx l = all p [2..mx] where
  p x = any (\y -> gcd x y /= 1) l

xxGood = all isOk xx && all (isMaximal 60) xx

-- main = print $ length xx
countBF = goOnes where
  goOnes nonOnes [] = (0, [])
  goOnes nonOnes (t : ts) = min ((+(t - 1)) *** (1:) $ goOnes nonOnes ts) (goNonOnes nonOnes (t : ts))
  goNonOnes nonOnes [] = (0, [])
  goNonOnes (no : nos) (t : ts) =
    min
    ((abs (no - t) +) *** (no:) $ goNonOnes nos ts)
    (goNonOnes nos (t : ts))
  goNonOnes [] (_ : _) = (1000000000, [])
count nonOnes target = second reverse $ dp ! (length nonOnes, length target)  where
  nonOnesArr = listArray (0, length nonOnes - 1) nonOnes
  targetArr = listArray (0, length target - 1) target
  -- key: number of nonOnes used or skipped; number of targets filled
  -- result: minimum sum of differences
  dp =
    array ((0, 0), (length nonOnes, length target))
    [ ((i,j),
       if j == 0 then (0, [])
       else
         if i == 0 then ((+(targetArr ! (j - 1) - 1)) *** (1 :) $ dp ! (i, j-1))
         else
         min
         (dp ! (i-1, j)) -- skip a non-one
         (((+ abs (nonOnesArr ! (i-1) - targetArr ! (j - 1))) *** (nonOnesArr ! (i-1) : )) $ dp ! (i-1, j-1)))
    | i<-[0..length nonOnes], (j,t)<-(0,undefined) : zip[1..] target]

prop1 x y = countBF x y == count x y

s target =  map snd $ sort $ zip indices sol where
  (target', indices) = unzip $ sort (zip target [0..])
  sol = snd $ minimum $ [count nonOnes target'|nonOnes<-xx]
main = interact $ unwords . map show . s . map read . tail . words


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

solve :: Int -> String
solve n | n < 20 = [ "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" ] !! n
        | n `mod` 10 == 0 = [ "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" ] !! div n 10
        | otherwise = solve (10 * div n 10) ++ "-" ++ solve (mod n 10)


module Main where
import Control.Applicative
import Control.Monad
import Data.Char
import Data.Ord
import Data.List
import Data.Maybe

main :: IO ()
main = do
  _ <- getLine
  ds <- getLine
  print $ sol ds

sol :: String -> Integer
sol = foldr1 (\i a -> i+10*a) . sort . concat .
  map (f . fromIntegral . flip (-) (ord '0') . ord)
  where
  f i = case i of
    0 -> []
    1 -> []
    4 -> [2,2,3]
    6 -> [3,5]
    8 -> [2,2,2,7]
    9 -> [2,3,3,7]
    _ -> [i]


import Data.List
import Debug.Trace

pow x 0 = 1
pow x y = x * pow x (y-1)

hantei 1 b t n = 1 + n * b <= t
hantei k b t n =
    t*(k-1) >= pow k n * ( k + b - 1) - b

solve k b n t =
    let m = head $ filter (not . hantei k b t) [0,1..n] ++ [n+1] in
        n - m + 1

main :: IO ()
main = do
    str <- getLine
    let [k,b,n,t] = map read $ words str in
        putStrLn $ show (solve k b n t)


main :: IO ()
main = getLine >>= putStrLn . unwords . map show . solve . map read . words

solve :: [Int] -> [Int]
solve [a, b] = [ length [ k | k <- [1..6], abs (k - a) <  abs (k - b) ],
                 length [ k | k <- [1..6], abs (k - a) == abs (k - b) ],
                 length [ k | k <- [1..6], abs (k - a) >  abs (k - b) ] ]
solve _ = undefined


import Data.List
solve [a,b,c] = maximum [a+(b*c),a*b*c,a+b+c,(a+b)*c,a*(b+c)]
main = interact $ show . solve . map read . words


{-(c) gorlum0 [at] gmail.com-}
import qualified Data.IntSet as S

main = do
    l <- getLine
    ws <- words `fmap` getLine
    let n = read l :: Int
        kinds = S.toAscList . S.fromList $ map read ws
        fits = or [b`div`a < 2 | (a, b) <- zip kinds $ tail kinds]
    putStrLn $ if fits then "YES" else "NO"


import Data.List

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

solve :: [Int] -> Int
solve (n:d:t) =
    let minTime = (sum t) + (n - 1) * 10
    in  if minTime > d then -1 else (n - 1) * 2 + (div (d - minTime) 5)


{-# LANGUAGE UnicodeSyntax #-}
{-# OPTIONS_GHC -O3 -optc-O3 -funbox-strict-fields #-}
import Control.Applicative
import Data.Array
import Data.Int

modulo :: Int
modulo = 10^9 + 7

a +. b = (a + b) `rem` modulo

build k = a
	where
		a = listArray (0, k) [listArray (0, k) [count' i j | j ← [0..k]] | i ← [0..k]]
		count' i j
			| j == 0 = 1
			| j <= i = (a ! (i-1) ! (j-1)) +. (a ! (i-1) ! j)
			| otherwise = 0

main = do
	[n, m, k] ← map read . words <$> getLine
	let a = build $ (max n m) - 1

	let c1 = if 2*k <= n-1 then a ! (n-1) ! (2*k) else 0
	let c2 = if 2*k <= m-1 then a ! (m-1) ! (2*k) else 0

	print $ (fromIntegral c1) * (fromIntegral c2) `rem` ((fromIntegral modulo) :: Int64)


main = interact $ unwords . map show . sol . map read . words

sol (l:r:_)
    | (odd l && r-l < 3) = [-1]
    | r-l < 2 = [-1]
    | odd l = [l+1, l+2, l+3]
    | otherwise = [l, l+1, l+2]


import Data.List
import Control.Monad

mod' :: Int
mod' = 1000000007

add :: Int -> Int -> Int
add a b = mod (a + b) mod'

solve :: [Int] -> Int
solve [n, k, d] = solve' n !! 1 !! 0
        where
              solve' 0 = [[1], [0]]
              solve' n = [a:dp1, (add (b-a) mod'):dp2]
                  where [dp1, dp2] = solve' (n - 1)
                        a = foldl add 0 $ take (d - 1) dp1
                        b = foldl add 0 $ concat $ map (take k) [dp1, dp2]

main = getLine >>= (putStrLn . show . solve . (map read) . words)


module Main where

import Data.List

main = do
    input <- getContents
    let pole = concat $ take 3 $ lines input
    putStrLn $ solve pole where

        solve pole = case stroke of
                "-" -> "illegal"
                _   -> case won of
                    "all" -> "illegal"
                    "-"   -> if filled then "draw"
                                       else stroke
                    _     -> if stroke == won then "illegal"
                                              else "the " ++ won ++ " player won"
            where

                -- заполнено ли поле полностью?
                filled = all (/='.') pole

                -- чей следующий ход?
                stroke = if countX == countO
                    then "first"
                    else if countX == (countO + 1) then "second"
                                                   else "-"
                countX = count 'X'
                countO = count '0'
                count c = length $ filter (==c) pole

                -- кто победитель (all/first/second/-)?
                won = if wonX && wonO
                    then "all"
                    else if wonX
                        then "first"
                        else if wonO then "second"
                                     else "-"
                wonX = isWinner 'X'
                wonO = isWinner '0'
                isWinner c =
                    -- по горизонтали
                    ((pole!!0) == c && (pole!!1) == c && (pole!!2) == c) ||
                    ((pole!!3) == c && (pole!!4) == c && (pole!!5) == c) ||
                    ((pole!!6) == c && (pole!!7) == c && (pole!!8) == c) ||
                    -- по вертикали
                    ((pole!!0) == c && (pole!!3) == c && (pole!!6) == c) ||
                    ((pole!!1) == c && (pole!!4) == c && (pole!!7) == c) ||
                    ((pole!!2) == c && (pole!!5) == c && (pole!!8) == c) ||
                    -- по диагонали
                    ((pole!!0) == c && (pole!!4) == c && (pole!!8) == c) ||
                    ((pole!!2) == c && (pole!!4) == c && (pole!!6) == c)


-- Codeforces 911C

{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as BC
import Data.List
import Data.Maybe

main :: IO ()
main = do
    [k1, k2, k3] <- (sort . map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getLine :: IO [Int]
    putStrLn $ if | k1 == 1 -> "YES"
                  | k1 == 2 && k2 == 2 -> "YES"
                  | k1 == 3 && k2 == 3 && k3 == 3 -> "YES"
                  | k1 == 2 && k2 == 4 && k3 == 4 -> "YES"
                  | otherwise -> "NO"


import Control.Applicative
import Data.List

process m [] [x] = snd x
process m s [] =  process m [] (reverse s)
process m s (x:xs) | fst x <=m = process m s xs
                   | otherwise = process m (((fst x-m),snd x):s) xs

main=do
	[n,m]<-map read.words <$> getLine:: IO   [Int]
	s<-map read. words <$> getLine:: IO [Int]
	print $ process m [] $ zip s [1..]


-- This solution uses generating functions to totally overkill the
-- problem, and uses Integer multiplication to perform the necessary
-- convolutions. Since that doesn't rely on any number theory tricks,
-- it works nicely with any modulus, and not just the classic
-- FFT-friendly prime 998244353 = 1 + 7 * 17 * 2^23.

-- Yes, I know there's an easier solution using Burnside's lemma
-- and derangements. But implementing this one is worth it, too.

-- My implementation is probably not that efficient. But the time
-- limit is rather large, so it might get AC anyway.

{-# LANGUAGE MagicHash, ScopedTypeVariables, UnboxedTuples #-}
{-# OPTIONS_GHC -Wno-unbanged-strict-patterns #-}

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed

import Data.Bits
import Data.Semigroup
import Data.Array.ST.Safe

import GHC.Exts
import GHC.Integer.GMP.Internals
import GHC.IO
import GHC.ST

mainFun :: SP Builder
mainFun = do
  n <- getInt
  k0 <- getInt
  let
    k = min n k0 -- no larger amount will help

    facts :: UArray Int Int
    facts = listArray (0, n) $ scanl' (*!) 1 [1 .. n]
    ifacts :: UArray Int Int
    ifacts = array (0, n) $ take (n + 1)
      $ iterate (\(i, v) -> (i - 1, v *! i)) (n, inv (facts ! n))
{-
    display :: Integer -> Builder
    display = putInts . map fromIntegral . snd . toWordList
-}
    inv' :: Int -> Int
    inv' x = ifacts ! x *! facts ! (x - 1)

    antideriv :: Integer -> Integer
    antideriv x = case  toWordList x  of
      (sz, ws) -> makeInteger (sz + 1) $ 0 : let
        div' i z = fromIntegral $ inv' i *! fromIntegral z
        in  zipWith div' [1..] ws

    g, gk1, eg :: Integer
    g = makeInteger (n + 1) $ 0 : tail (map fromIntegral $ elems ifacts)
    gk1 = calcPow (n - k) antideriv (g `shiftR` 128) (k + 1)
      `shiftL` (128 * (k + 1))
    eg = calcExp (n + 1) antideriv g

    hetero = if  k < n
      then  conv (n + 1) gk1 (fromIntegral $ 0 -! ifacts ! (k + 1))
      else  0
    integrand = conv n (inverse n eg) (derivative hetero)

    unG_soln = conv (n + 1) eg $ 1 + antideriv integrand

    unG_solnArr :: UArray Int Int
    unG_solnArr = listArray (0, n) $ case  toWordList unG_soln  of
      (_, li) -> zipWith (*!) (elems facts) $ map fromIntegral li ++ repeat 0

    ceilDiv x y = case  x `divMod` y  of
      (q, 0) -> q
      (q, _) -> q + 1

    toMobiusArr :: UArray Int Int
    toMobiusArr = array (1, n) [(i, unG_solnArr ! ceilDiv n i) | i <- [1..n]]

    ansArr = runSTUArray $ do
      arr :: STUArray s Int Int <- thaw toMobiusArr
      forM_ [n-1, n-2 .. 1] $ \i -> do
        pval <- readArray arr i
        nval <- (\fun -> foldM fun pval $ n : [2*i, 3*i .. n-1]) $ \acc j -> do
          nval <- readArray arr j
          pure $ acc -! nval
        writeArray arr i nval
      pure arr

    ans = if  k == 1 && n > 1
      then  1 -- only here are seed arrays of block size (> 1) needed
      else  ansArr ! 1
  pure $ putInts [ans]

-------------------------------------------------------------------------------
-- Modular arithmetic
-------------------------------------------------------------------------------

p :: Int
p = 998244353
{-
(+!) :: Int -> Int -> Int
infixl 6 +!
x +! y = x + y -! p
-}
(-!) :: Int -> Int -> Int
-- branchless subtraction modulo p
infixl 6 -!
x -! y = let
  raw = x - y
  in  raw + (p .&. shiftR raw 63)

(*!) :: Int -> Int -> Int
infixl 7 *!
x *! y = let
  I# raw = x * y
  in  I# (word2Int# (remP (int2Word# raw)))

quotP :: Word# -> Word#
quotP v = let
  (# hi, _lo #) = timesWord2# 9920937979283557439## v
    -- the magic number is ceiling(2^(64+29) / p)
    -- The approximation is accurate enough to calculate the exact
    -- quotient with one multiply and one shift for all valid Word#
  in  shiftRL# hi 29#

remP :: Word# -> Word#
remP v = let
  I# p# = p
  in  v `minusWord#` timesWord# (quotP v) (int2Word# p#)

remP2 :: Word# -> Word# -> (# Word#, Word# #)
remP2 hi lo = let
  -- This implementation cheats a bit in order to be a tiny bit
  -- faster. It assumes the high word should be at most 26_401_116_612,
  -- and gives a result in [0..2p-2] instead of [0..p-1].
  I# p# = p
  (# redHi, _ #)
    = int2Word# p# `timesWord2#` timesWord# 17223561541331522433## hi
  in  (# 0##, redHi `plusWord#` remP lo #)

newtype ModP = ModP { unModP :: Int }
instance Semigroup ModP where
  ModP x <> ModP y = ModP (x *! y)
  stimes = stimesMonoid
instance Monoid ModP where
  mempty = ModP 1

inv :: Int -> Int
inv = unModP . stimes (p - 2) . ModP

-------------------------------------------------------------------------------
-- Generating function / polynomial stuff
-------------------------------------------------------------------------------

normalizeP :: Int -> Integer -> Integer
normalizeP = normalize remP2

conv :: Int -> Integer -> Integer -> Integer
conv prec x y = normalizeP prec $ x * y

negateFields :: Int -> Integer -> Integer
negateFields = let
  I# p# = p
  negateOne hi lo = case  inline remP2 hi lo  of
    (# _, nlo #) -> (# 0##, int2Word# (p# `iShiftL#` 1#) `minusWord#` nlo #)
  in  normalize negateOne

inverse :: Int -> Integer -> Integer
-- Newton's method
inverse prec x = if  prec <= 1
  then  toInteger $ inv $ fromInteger x
  else  let
  subPrec = (prec + 1) `div` 2
  subAns = inverse subPrec (truncateAt subPrec x)
  approx = negateFields prec $ x * subAns
  in  normalizeP prec $ subAns * (2 + approx)

derivative :: Integer -> Integer
derivative x = case  toWordList x  of
  (n, ws) -> makeInteger (n - 1) $ do
    (i, xi) <- zip [1 ..] (tail ws)
    pure $ fromIntegral (i *! fromIntegral xi)

calcLog :: Int -> (Integer -> Integer) -> Integer -> Integer
calcLog prec antideriv x = let
  prec' = max 0 $ prec - 1
  in  antideriv $ conv prec' (derivative x) (inverse prec' x)

calcExp :: Int -> (Integer -> Integer) -> Integer -> Integer
calcExp prec antideriv x = if  prec <= 1
  then  1
  else  let
  subPrec = (prec + 1) `div` 2
  subAns = calcExp subPrec antideriv (truncateAt subPrec x)
  err = x + negateFields prec (calcLog prec antideriv subAns)
  in  conv prec subAns (1 + err)

calcPow :: Int -> (Integer -> Integer) -> Integer -> Int -> Integer
calcPow prec antideriv x k = let
  logx = calcLog prec antideriv x
  in  calcExp prec antideriv $ conv prec logx (fromIntegral k)

-------------------------------------------------------------------------------
-- Integer internals manipulation
-------------------------------------------------------------------------------

makeInteger :: Int -> [Word] -> Integer
-- Interprets a list of Words as a little-endian base-(2^128) Integer.
-- Uses internal ByteArray# interface to do it quickly, because sadly
-- 'GHC.Num.Integer.integerFromWordList' doesn't exist yet in 8.10.1.
{-# INLINE [1] makeInteger #-}
{-# ANN makeInteger "HLint: ignore Redundant lambda" #-}
-- 'step' is applied to only two arguments if this fuses
makeInteger (I# n) li = runST $ ST $ \(s0 :: State# s) -> let
  numBytes = iShiftL# n 4#
  (# s1, marr #) = newByteArray# numBytes s0
  s2 = setByteArray# marr 0# numBytes 0# s1
  step :: Word -> (Int# -> State# s -> State# s)
               ->  Int# -> State# s -> State# s
  step (W# val) cont = \off s3
    -> cont (off +# 2#) (writeWord64Array# marr off val s3)
  s4 = foldr step (\_ s -> s) li 0# s2
  (# s5, arr #) = unsafeFreezeByteArray# marr s4
  in  (# s5, importIntegerFromByteArray arr 0## (int2Word# numBytes) 0# #)

integerToMutableByteArray
  :: Int -> Integer -> State# RealWorld
  -> (# State# RealWorld, MutableByteArray# RealWorld, Int# #)
integerToMutableByteArray maxNumFields val s0 = let
  numInputBytes = sizeInBaseInteger val 256#
  numOrigFields = iShiftRL# (word2Int# numInputBytes +# 15#) 4#
  bufferSize = iShiftL# numOrigFields 4#
  (# s1, arr #) = newByteArray# bufferSize s0
  s2 = setByteArray# arr (bufferSize -# 16#) 16# 0# s1
  (# s3, _ #) = unIO (exportIntegerToMutableByteArray val arr 0## 0#) s2
  I# numFields = maxNumFields `min` I# numOrigFields
  (# s4, arr' #) = resizeMutableByteArray# arr numFields s3
  in  (# s4, arr', numFields #)

toWordList :: Integer -> (Int, [Word])
toWordList val = let
  (# n, arr #) = runRW# $ \s0 -> let
    (# s1, marr, numFields #) = integerToMutableByteArray maxBound val s0
    (# _, farr #) = unsafeFreezeByteArray# marr s1
    in  (# numFields, farr #)
  stopOff = iShiftL# n 1#
  in  (,) (I# n) $ build $ \cons nil -> let
  go off = if  isTrue# (off <# stopOff)
    then  W# (indexWord64Array# arr off) `cons` go (off +# 2#)
    else  nil
  in  go 0#

normalize
  :: (Word# -> Word# -> (# Word#, Word# #)) -> Int -> Integer -> Integer
-- If the Integer is understood as an array of Word128s, this uses
-- the first argument to update each field. This allows replacing
-- the rather slow 'quotRemWord2#' with something faster...
{-# ANN normalize "HLint: ignore Redundant lambda" #-}
{-# INLINE normalize #-} -- It should specialize, given only one arg!
normalize fun = \prec x -> runRW# $ \s0 -> let
  (# s1, marr, numFields #) = integerToMutableByteArray prec x s0
  go off s2 = if  isTrue# (off >=# 0#)
    then  let
    (# s3, hi #) = readWord64Array# marr (off +# 1#) s2
    (# s4, lo #) = readWord64Array# marr off s3
    (# nhi, nlo #) = fun hi lo
    s5 = writeWord64Array# marr (off +# 1#) nhi s4
    s6 = writeWord64Array# marr off nlo s5 -- copy-paste is dangerous...
    in  go (off -# 2#) s6
    else  s2
  s7 = go (iShiftL# (numFields -# 1#) 1#) s1
  (# _s8, arr #) = unsafeFreezeByteArray# marr s7
  numBytes = int2Word# numFields `shiftL#` 4#
  in  importIntegerFromByteArray arr 0## numBytes 0#

truncateAt :: Int -> Integer -> Integer
truncateAt prec x = runRW# $ \s0 -> let
  (# s1, marr, numFields #) = integerToMutableByteArray prec x s0
  (# _s2, arr #) = unsafeFreezeByteArray# marr s1
  numBytes = int2Word# numFields `shiftL#` 4#
  in  importIntegerFromByteArray arr 0## numBytes 0#

-------------------------------------------------------------------------------
-- My normal library/template
-------------------------------------------------------------------------------

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

--getNext :: Monad m => S m P.ByteString
--getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun inp
  P.putStr $ toLazyByteString outp


main :: IO ()
main = do
    input <- getContents >>= return.(map read).words :: IO [Int]
    let w  = input!!0
    let h  = input!!1
    let u1 = input!!2
    let d1 = input!!3
    let u2 = input!!4
    let d2 = input!!5

    let result = foldr f w [1..h]
            where f height weight
                    | height == d1 = max 0 $ weight + height - u1
                    | height == d2 = max 0 $ weight + height - u2
                    | otherwise    = weight + height

    putStrLn $ show $ max 0 result


import Ratio
main=interact$f.g.map read.words
g(0:b:s)=(b*9^99%1):g s
g(a:b:s)=(b%a):g s
g _=[]
f[x,y,z]|x*y*z>1%1||y>9^80||x*y>9^80="Ron"|1>0="Hermione"


import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
import Data.Int
--import qualified Data.HashTable.IO as B
import qualified Data.ByteString.Lazy.Char8 as B

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

textRepresentation :: Show a => [a] -> String
textRepresentation row = unwords . map show $ row

g [] _ = 0
g str@(_:xs) pat
    | isPrefixOf pat str = 1 + rec
    | otherwise = rec
    where rec = g xs pat

main :: IO ()
main = do
    str <- getLine
    let flag = foldl (+) 0 . map (g str) $ l
    if  flag == 1
        then putStr "YES"
        else putStr "NO"
    where l=["Danil", "Olya", "Slava", "Ann" , "Nikita"]

--индексиране на памет
-- $! синтаксис
--fmap
{-main :: IO ()
main = do
    print 3
    where gg=H.fromList-}


import Text.Printf

data Time = Time Int Int
    deriving Show

main :: IO ()
main = interact $ toString . stampToTime . solve . map (timeToStamp . toTime) . words

toTime :: String -> Time
toTime (h1:h2:':':m1:m2:[]) = Time (read [h1, h2]) (read [m1, m2])
toTime _                    = Time 0 0

toString :: Time -> String
toString (Time h m) = (printf "%02d" h) ++ ":" ++ (printf "%02d" m)

timeToStamp :: Time -> Int
timeToStamp (Time h m) = h * 60 + m

stampToTime :: Int -> Time
stampToTime stamp = Time (stamp `div` 60) (stamp `mod` 60)

solve :: [Int] -> Int
solve (s1:s2:[]) = (s2 - s1) `div` 2 + s1
solve _          = 0


import Data.List

main = do
	getLine
	s <- fmap sort getLine
	putStrLn $ if (length s == 1) || (any (uncurry (==)) $ zip s (tail s)) then "Yes" else "No"


import Control.Monad

process :: Int -> Int -> Int -> Int -> Bool -> String
process a b a' b' True
  | a < a'    = "Vladik"
  | otherwise = process (a - a') b (a' + 2) b' False
process a b a' b' False
  | b < b'    = "Valera"
  | otherwise = process a (b - b') a' (b' + 2) True

main :: IO ()
main = do
  [a, b] <- liftM (map read . words) getLine
  putStr $ process a b 1 2 True


inc = (-1 +) . (2 *)
analyze = length >>= (. (inc . (length . (filter (== 'a'))))) . min
main = getLine >>= putStrLn . show . analyze


module Main where
import qualified Data.ByteString.Char8 as B
import Data.Int
import Data.List
import Data.Maybe
import Data.Char

readInt = fst . fromJust . B.readInteger
readInts = fmap readInt . B.words

solve :: Int64 -> Int64 -> Int64
solve n s = max 0 $ (n + 1 - ) $ fromMaybe (n + 1) $ find (\x -> x - sum (map (fromIntegral . digitToInt) $ show x) >= s) [s..n]

main = do
  n:s:_ <-  fmap (map fromIntegral . readInts) B.getLine
  print $ solve n s


import Data.Ratio
--
main :: IO()
main = do
  a <- getLine
  putStrLn . solve . map read $ words a

solve :: [Integer] -> String
solve [x,y,n] = out $ near x y n
                where out (a,b) = (show a) ++ "/" ++ (show b)

solve _= undefined

near :: Integer -> Integer -> Integer -> (Integer, Integer)
near x y n = if n >= y then (x', y')
             else snd $ minimum [(abs $ x % y - a % b, (a, b)) | b <- [1..n], let m = b * x' `quot` y', a <- [m, m + 1]]
  where
    x' = numerator $ x%y
    y' = denominator $ x%y


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List

main = putStr . evalState app . B.words =<< B.getContents

data P = P !Int !Int !Int !Int !Int
data V = V !Int !Int !Int !Int !Int

app = (\xs -> unlines $ show (length xs):map show xs) `fmap` solve `fmap` (flip replicateM (liftM5 P poi poi poi poi poi) =<< poi)
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve = map fst . filter (\(i, (a, bs)) -> all (uncurry good) $ pairs $ map (vec a) bs) . zip [1..] . splits

splits = map (\(ys, x:xs) -> (x, ys ++ xs)) . init . liftM2 zip inits tails

pairs xs = [(a, b) | (a:bs) <- tails xs, b <- bs]

vec (P a b c d e) (P a' b' c' d' e') = V (a' - a) (b' - b) (c' - c) (d' - d) (e' - e)
good (V a b c d e) (V a' b' c' d' e') = a*a' + b*b' + c*c' + d*d' + e*e' <= 0


import Control.Monad (liftM)
import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: [Int] -> Int
solve [x, y]
  | x == 0 && y == 0  =  0
  | x > 0 && x+y <= 1  =  4 * abs y
  | x > 0 && x-y >= 0  =  4 * x - 3
  | x > 0  =  4 * y - 2
  | x+y >= 0  =  4 * y - 2
  | x-y <= 0  =  4 * abs x - 1
  | otherwise  =  4 * abs y

main :: IO ()
main  =  reads >>= print . solve


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

solve (n:pos:l:r:_)
    | 1 == l && n == r = 0
    | 1 == l && n /= r = 1 + abs (r - pos)
    | 1 /= l && n == r = 1 + abs (l - pos)
    | otherwise = 2 + r - l + (min (abs (l - pos)) (abs (r - pos)))


break' [] _ = False
break' _ [] = True
break' (x:xs) (y:ys)
  | x == y = break' xs ys
  | x /= y = break' xs (y:ys)

main = do
  aa <- getLine
  putStrLn $ if break' (aa++" ") "hello" then "YES" else "NO"


getans :: [Integer] -> Integer
getans (x:y:a:b:_)  = (div b (lcm x y)) - (div (a - 1) (lcm x y))

main = do
    input <- getLine
    putStr $ show $ getans (map read (words input) :: [Integer])


{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Array.IArray
import Data.STRef
import Data.Bits
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

getInts :: IO [Int]
getInts = map readInt . words <$> getLine

solve :: Integer -> Integer -> Int -> Integer -> Integer
solve n k l m
  | k >= toInteger (2 ^ l) = 0
  | m == 1 = 0
  | otherwise = L.foldl' (\a h -> (a * h) `mod` m) 1 [amount (testBit k i) | i <- [0..(l - 1)]]
  where
    np = (getNp (n - 1) m) `mod` m
    all = (getAll n m) `mod` m
    amount True = np
    amount False = all - np

type Mat = Array (Int, Int) Integer

-- 1 x 3
mStart :: Mat
mStart = listArray ((0, 0), (2, 0)) [0, 1, 1]

-- 3 x 3
mOnes :: Mat
mOnes = listArray ((0, 0), (2, 2))
  [ 1, 0, 0
  , 0, 1, 0
  , 0, 0, 1]

mTransform :: Mat
mTransform = listArray ((0, 0), (2, 2))
  [ 2, 1, 0
  , 0, 0, 1
  , 0, 1, 1
  ]

mmul :: Mat -> Mat -> Mat
mmul m1 m2 = listArray ((j0, i0), (j1, i1))
  [sum $ zipWith (*) (getRow m1 i) (getCol m2 j) | i <- [i0..i1], j <- [j0..j1]]
  where
    ((i0, _), (i1, _)) = bounds m1
    ((_, j0), (_, j1)) = bounds m2

getRow :: Mat -> Int -> [Integer]
getRow m i = [m ! (i, j) | j <- [j0..j1]]
  where
    ((_, j0), (_, j1)) = bounds m

getCol :: Mat -> Int -> [Integer]
getCol m i = [m ! (j, i) | j <- [j0..j1]]
  where
    ((j0, _), (j1, _)) = bounds m

mmod a m = amap (`mod` m) a

getNp :: Integer -> Integer -> Integer
getNp n m = ((loop n mTransform mOnes) `mmul` mStart) ! (0, 0)
  where
    loop :: Integer -> Mat -> Mat -> Mat
    loop 0 _ acc = acc
    loop n x acc =
      (loop (n `shiftR` 1)) ((x `mmul` x) `mmod` m) (if testBit n 0
        then ((acc `mmul` x) `mmod` m)
        else acc)

getAll :: Integer -> Integer -> Integer
getAll n m = loop n 2 1
  where
    loop :: Integer -> Integer -> Integer -> Integer
    loop 0 _ acc = acc
    loop n x acc = (loop (n `shiftR` 1)) ((x * x) `mod` m) (if testBit n 0
      then ((acc * x) `mod` m)
      else acc)

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


import Data.Ratio(numerator,denominator)

sumOfDigit :: Int -> Int -> Int
sumOfDigit n base | n < base = n
                  | otherwise = (mod n base) + sumOfDigit (div n base) base

solve :: Int -> Rational
solve n = theSums / theLength
    where theSums = toRational(sum (map (sumOfDigit n) [2..n-1]))
          theLength = toRational(length [2..n-1])

prettyPrint :: Rational -> [Char]
prettyPrint r = (show (numerator r)) ++ "/" ++ (show (denominator r))

main = do
       inputLine <- getLine
       let n = read inputLine :: Int
       putStrLn (prettyPrint (solve n))


{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List
import Data.Bits

main :: IO ()
main =  interact $  lines >>> drop 0 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (l : rest) = (itoline . solve . linetoi) l : tcio rest
  linetoi = read;
  itoline = show;

modExp :: Integer -> Integer -> Integer -> Integer
modExp b 0 m = 1
modExp b e m = t * modExp ((b * b) `mod` m) (shiftR e 1) m `mod` m
                   where t = if testBit e 0 then b `mod` m else 1

solve :: Int -> Integer
solve n = ((head. drop (n-1)) fib')  `moddiv` (modExp 2 (toInteger n) p) where
  fib' = 1:fib
  fib = zipWith (modadd) (0:1:fib) (1:fib)
  modadd x y = (x + y) `mod` p
  moddiv x y = (x * (modExp y (p-2) p)) `mod` p
  p = 998244353


import Control.Applicative
import Control.Monad

main = sol <$> readLn <*> getLine >>= print

sol :: Int -> String -> Int
sol n s = min (length s `div` 11) (length $ filter (== '8') s)


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

main = do
		[y,b,r]<- map read <$> words <$> getLine ::IO [Int]
		let c = minimum [y, b-1,r-2]
		print $ c*3+3


module Main where

solve [l1, r1, l2, r2, k] = max 0 $ r - l + 1 - (if l <= k && k <= r then 1 else 0)
  where r = min r1 r2; l = max l1 l2

test =  let solve x = 5 in solve 2

main :: IO ()
main = do
  input <- getLine
  print $ solve [read x | x <- words input]


import Data.List (sort)
import Debug.Trace

solve :: [Int] -> String
solve x
  | greatStart && greatEnd = "C"
  | greatStart = snd start
  | greatEnd = snd end
  | otherwise = "C"
  where
    track q = trace (show q) q
    vals = sort $ zip x ["A", "B", "C", "D"]
    start = head vals
    end = last vals
    greatStart = fst start <= fst (vals !! 1) `quot` 2
    greatEnd = track (fst end) >= fst (vals !! 2) * 2

main = do
  putStrLn . solve . map (length . tail . tail) . lines =<< getContents


-- import Debug.Trace

problems a b probs
  | (b == 0) = probs
  | (b < 0) = (probs-1)
  | a == (probs-1) = (probs-1)
  | otherwise = problems a (b - (5*(probs+1))) (probs+1)

main = do
  hh <- getLine
  let aa = (read (head (words hh)))::Int
      bb = (read (last (words hh)))::Int

  let ans = problems aa (240 - bb) 0
  putStrLn (show ans)


module Main where
import Data.List
import Control.Applicative

main = do
    getLine
    ts <- nub . map (read :: String -> Int) .words <$> getLine
    let yesno x = if x then "YES" else "NO"
    putStrLn $ yesno $ not $ null [1 | x<-ts , y <-ts , z<-ts , x/=y, y/=z, x/=z, abs(x-y)<=2, abs(x-z)<=2, abs(y-z)<=2]


import Control.Applicative ((<$>), (<*>))
import Data.Maybe (isJust)
import Data.Time.Calendar (fromGregorianValid)
import Data.List (permutations)

main :: IO ()
main = solve <$> getLine <*> getLine >>= putStrLn . yesno

solve :: String -> String -> Bool
solve xs ys = or [ check (map read $ split '.' xs) zs | zs <- permutations $ map read $ split '.' ys, valid zs ]
  where split x = words . map (\c -> if c == x then ' ' else c)

valid xs = isJust $ fromGregorianValid (fromIntegral y) m d
  where [d, m, y] = xs

check xs ys = by < yy - 18 || by == yy - 18 && (bm < mm || bm == mm && bd <= dd)
  where [dd, mm, yy] = xs; [bd, bm, by]  = ys

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


-- 2019-11-24 22:52:24.249280323 UTC
import Data.Maybe
import Data.Char
import Control.Monad
import Text.Read
nat_para :: Integral i => i -> a -> (i -> a -> a) -> a
nat_para i x f = np (abs i)
             where np 0 = x
                   np i = let i' = i - 1
                           in f i' (np i')
hd :: [a] -> a
hd ([]) = error "empty head"
hd (a : as) = a
tl = drop 1
nat_cata :: Integral i => i -> a -> (a -> a) -> a
nat_cata i x f = nc (abs i)
             where nc 0 = x
                   nc i = f (nc (i - 1))
iF :: Bool -> a -> a -> a
iF (True) t f = t
iF (False) t f = f
list_para :: [b] -> a -> (b -> [b] -> a -> a) -> a
list_para ([]) x f = x
list_para (y : ys) x f = f y ys (list_para ys x f)
magiciF :: Bool -> String
magiciF b = if b then "EASY" else "HARD"
uncurry' = id
parser :: String -> String
parser = head . lines
solve = \a -> map (\b -> iF ((\f_6989586621679053539 -> length . filter f_6989586621679053539) (\c -> isLower c) a >= (\f_6989586621679053539 -> length . filter f_6989586621679053539) (\c -> isUpper c) a) (toLower b) (toUpper b)) a
main = getContents >>= (\c -> putStrLn (uncurry' solve (parser c)))


import Control.Applicative
import Data.List

main= do
 	x<-sort . map read . words <$> getLine ::IO [Int]
	print $ 4-(length (group x))


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

main = do
		n<- read <$> getLine::IO Int
		k<- map read <$> words <$> getLine::IO [Int]
		let ma = maximum k
		let s = sum k
		print $ max ma ((div (s+s+1) n) + if (mod (s+s+1) n)==0 then 0 else 1)


main = do
   [k,n,s,p] <- return . map (read :: String -> Double ) . words =<< getLine
   print $ ceiling $ k * (fromIntegral $ ceiling $ n / s) / p


-- Codeforces 911B

{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

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

main :: IO ()
main = do
    [n, a, b] <- (map (fst . fromJust . BC.readInt) . BC.words) <$> BC.getLine :: IO [Int]
    print . maximum . map (\i -> min (a `div` i) (b `div` (n - i))) $ [max (n-b) 1 .. min (n - 1) a]


solve [a,b,e] [c,d,f]
  | a == 0 && b == 0 && e /= 0     = 0
  | c == 0 && d == 0 && f /= 0     = 0
  | det == 0 && x' == 0 && y' == 0 = -1
  | det == 0                       = 0
  | otherwise                      = 1
  where
    det = a*d-c*b
    x'  = e*d-f*b
    y'  = a*f-c*e

(-->) = flip fmap

main = do
  u@[a,b,e] <- getLine --> words --> map read
  v@[c,d,f] <- getLine --> words --> map read
  let _ = a :: Int
  print $ solve u v


import Control.Applicative
import Prelude

import Control.Arrow ((>>>))
import Control.Monad (liftM, when)
import Control.Monad.ST.Safe (ST, runST)
import Data.Array.ST.Safe (STArray, newArray, readArray, writeArray, getElems, mapArray)
import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef, modifySTRef)
import Data.Foldable (for_)

whileM_ :: (Monad m) => m Bool -> m a -> m ()
whileM_ p f = do
    x <- p
    when x (f >> whileM_ p f)

existsUnloved :: Int -> [Int] -> Bool
existsUnloved n g = runST $ do
    incoming <- newArray (1, n) [] :: ST s (STArray s Int [Int])
    gg <- newSTRef g
    for_ [1..n] $ \idx -> do
        h:t <- readSTRef gg
        current <- readArray incoming h
        writeArray incoming h (idx:current)
        writeSTRef gg t
    any null <$> (getElems incoming)

loopLengths :: Int -> [Int] -> [Int]
loopLengths n g = runST $ do
    visited <- newArray (1, n) False :: ST s (STArray s Int Bool)
    ans <- newSTRef []
    for_ [1..n] $ \idx -> do
        visitedCurrent <- readArray visited idx
        when (not visitedCurrent) $ do
            writeArray visited idx True
            current <- newSTRef (g !! (idx - 1))
            currentLength <- newSTRef 1
            whileM_ (readSTRef current >>= \v -> readArray visited v >>= \vv -> return $ not vv) $ do
                cval <- readSTRef current
                writeArray visited cval True
                modifySTRef current (\val -> g !! (val - 1))
                modifySTRef currentLength ((+) 1)
            finalval <- readSTRef current
            when (finalval == idx) $ do
                lenval <- readSTRef currentLength
                modifySTRef ans (\ansval -> lenval : ansval)
    readSTRef ans

main = do
    n <- readLn :: IO Int
    crush <- liftM (words >>> map read) getLine :: IO [Int]
    if existsUnloved n crush then
        print (-1)
    else
        let ll = foldr lcm 1 $ loopLengths n crush in
        if ll `rem` 2 == 0 then
            print $ ll `div` 2
        else
            print $ ll


main = getLine >>= print . solve

solve (c:r:_)
    | c `elem` "ah" && r `elem` "18" = 3
    | c `elem` "ah" || r `elem` "18" = 5
    | otherwise = 8


{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words, unpack, reverse, dropWhile)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Char as C (isSpace)
import qualified Control.Monad.ST.Safe as ST (runST, ST)
import qualified Data.Array.ST.Safe as ST (STUArray)
import qualified Data.Array.MArray.Safe as A (newArray, readArray, writeArray, getElems)
import qualified Control.Monad as M (forM_)

readInt = fst . M.fromJust . C.readInt
rstrip = C.reverse . C.dropWhile C.isSpace . C.reverse

incArray arr i = do
    x <- A.readArray arr i
    A.writeArray arr i (x + 1)

run x = ST.runST $ do
    arr <- A.newArray ('a', 'z') 0 :: ST.ST s (ST.STUArray s Char Int)
    M.forM_ x $ incArray arr
    arrx <- A.getElems arr
    return $ maximum arrx

main = do
    (map readInt . C.words -> [_, k]) <- B.getLine
    (C.unpack . rstrip -> xs) <- B.getLine
    putStrLn $ if run xs <= k then "YES" else "NO"