import Data.List
import qualified Data.Map.Strict as Map

toint s = (read s) :: Integer

agregar x m = Map.insertWith (+) x 1 m

asdasd [] = Map.fromList []
asdasd (x:xs) = agregar x (asdasd xs)

doit k [] = 0
doit k ((_,t):xs) =
	max (div (t+k-1) k) $ doit k xs

solve::String -> String
solve ss =
	let n:k:x = map toint $ words ss in
	let z = Map.toList $ asdasd x in
	let q = (doit k z) * k in
	show(sum $ map (\(_,t) -> q-t) z) ++ "\n"

main = do
  interact $ solve

module Main where
import Data.List

main = do
    [_,k] <- map (read :: String -> Int) . words <$> getLine
    a <- map (read :: String -> Int) . words <$> getLine
    let b = group $ sort a
        c = map length b
        d = maximum c
        e = (if d `mod` k == 0 then d else d + k - (d`mod`k)) `div` k
        f = (k*) $ (e*) $ length $ nub a
    print $ f - sum c

import Data.List

main = do
       e<-getLine
       e2<-getLine
       let xs=map read (words e2)::[Int]
           ys=map length $ group $ sort xs
           (n:k:[])=map read (words e)::[Int]
           t=maximum ys
       print $ (k*(length ys)*(t `div` k + (if t `mod` k==0 then 0 else 1 )))-n


import Control.Monad
import Control.Applicative
gcdd x y | x > y = gcdd y x
gcdd 0 _ = mzero
gcdd 1 x = return (x-1)
gcdd x y = (y `div` x +) <$> gcdd (y `mod` x) x

s x=minimum$[1..x]>>=gcdd x

main=interact$show.s.read

main = interact $ show.solve.read
solve x = minimum.map (gao).zip [1..x] $ repeat x
gao (a,b) | a == 1 = b - 1 | b `mod` a == 0 = 1000000 | 1>0 = b `div` a + gao (b `mod` a, a)

module Main (main) where

import System
import Data.Char
import Data.List
import Control.Monad
import Control.Applicative

doit :: Int -> Int -> Int -> Int
doit _ _ 30 = 999999999
doit 1 1 _ = 0
doit 0 _ _= 999999999
doit n 1 _= n - 1
doit a b dep
  | a > b = doit b a dep
  | otherwise = t + doit a (b - a * t) (dep + 1)
                  where d = b - a ; t = (max 1 (d `div` a))

solve :: Int -> String
solve n = show $ minimum [doit v n 0 | v <- [1..n]]

main = interact$solve.read.head.words


main=interact$f.lines
f[a,b]=zipWith(g)a b
g a b|a==b='0'|1>0='1'

main=interact$(\[x,y]->zipWith(\a b->if a==b then '0' else '1')x y).lines

import Data.Char

splitStr::String -> Char -> [String]
splitStr [] spliter = [""]
splitStr (x:xs) spliter
    | x == spliter = "" : rest
    | otherwise = (x : head rest) : tail rest
    where
        rest = splitStr xs spliter

readNum :: IO Integer
readNum = readLn

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

process "" "" = ""
process s1 s2
    | (take 1 s1) == (take 1 s2) = "0" ++ next
    | otherwise = "1" ++ next
    where next = process (drop 1 s1) (drop 1 s2)

main = do
    src <- getLine--readNum
    src2 <- getLine
    putStrLn $ process src src2

decide x = if fst x == snd x
             then '0'
             else '1'
main=interact $ (map decide) . (\[x,y] -> zip x y) . lines

main = do
	a <- getLine
	b <- getLine
	putStrLn $ zipWith (\i j -> if i == j then '0' else '1') a b

module Main where

main = do
    a <- getLine
    b <- getLine
    let c = zipWith (\a b -> if a == b then '0' else '1') a b

    putStrLn c

xor a b | a==b = '0'
        | otherwise = '1'

solve [] [] = ""
solve (a:as) (b:bs) = [xor a b] ++ (solve as bs)

main = do
	a<-getLine
	b<-getLine
	putStrLn $ solve a b

shapur :: String -> String -> String
shapur [] _    = []
shapur (x:xs) (y:ys)
  | x == y     = '0' : next
  | otherwise  = '1' : next
    where next = shapur xs ys

main = getLine >>= \line -> getLine >>= return . shapur line >>= putStrLn

xor :: String -> String -> String
xor [] [] = []
xor (a:as) (b:bs) = c:(xor as bs)
	where c = if a == b then '0' else '1'

main = do
	a <- getLine
	b <- getLine
	putStrLn $ xor a b

f a b = if a==b then '0' else '1'
main = do
	a <- getLine
	b <- getLine
	putStrLn $ zipWith f a b

-- https://downloads.haskell.org/~ghc/latest/docs/html/libraries/base-4.9.0.0/Data-Bits.html
import Data.Bits

myxor a b lst
 | (null a) = lst
 | (head a) == (head b) = myxor (tail a) (tail b) (concat [lst, ['0']])
 | otherwise = myxor (tail a) (tail b) (concat [lst, ['1']])

main = do
  ff <- getLine
  gg <- getLine
  let ans = myxor ff gg []
  putStrLn ans

main = do
    s1 <- getLine
    s2 <- getLine
    putStrLn $ zipWith (\i1 i2 -> if i1 == i2 then '0' else '1') s1 s2

main :: IO ()
main = do
    number1 <- getLine
    number2 <- getLine
    putStr (zipWith (\x y -> if x == y then '0' else '1') number1 number2)

xor [] _ = ""
xor (x:xs) (y:ys) = (if x == y then '0' else '1') : (xor xs ys)

main :: IO ()
main = do
    number1 <- getLine
    number2 <- getLine
    putStr (xor number1 number2)

main = do s <- getLine
          t <- getLine
          putStrLn $ gen s t

gen [] [] = []
gen (ca:sa) (cb:sb) =
  if ca==cb then '0':gen sa sb
  else '1':gen sa sb

main = do
  s <- getLine
  t <- getLine

  putStrLn $ zipWith (\a b -> if a /= b then '1' else '0') s t

import Data.List
import Data.List.Split

(|>) x f = f x
main = interact solve

solve contents = let
  nums = contents |> lines
  in solve' (nums !! 0) (nums !! 1)

solve' xs ys = zipWith exor xs ys

exor '1' '0' = '1'
exor '0' '1' = '1'
exor _ _ = '0'

solve :: String -> String -> String
solve (x:xs) (y:ys)
          | x == y    = '0' : solve xs ys
          | otherwise = '1' : solve xs ys
solve [] [] = []

main :: IO ()
main = do l1 <- getLine
          l2 <- getLine
          putStrLn $ solve l1 l2

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.take 2 . lines
solve :: [String]->String
solve [x,y] = solve2 x y
solve2 "" "" =""
solve2 (x:xs) (y:ys) = if x==y then "0"++solve2 xs ys else "1"++solve2 xs ys

main = do
    a <- getLine
    b <- getLine
    putStrLn $ zipWith (\q -> \w -> if q == w then '0' else '1') a b

main = do
    a <- getLine
    b <- getLine
    putStr (zipWith (\x y -> if x == y then '0' else '1') a b)

import Control.Applicative

main = do
  a <- getLine
  b <- getLine
  putStrLn $ zipWith f a b

f '0' '0' = '0'
f '1' '0' = '1'
f '0' '1' = '1'
f '1' '1' = '0'
f x y     = x

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

chxor :: Char -> Char -> Char
chxor a b = if a == b then '0' else '1'

solve :: String -> String -> String
solve = zipWith chxor

main :: IO ()
main = do
    s <- getLine
    t <- getLine
    putStrLn $ solve s t

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

main=do

      [a,b]<- (replicateM 2      getLine )
      putStrLn $ zipWith (\z1 z2 ->if z1==z2 then '0' else '1') a b

module Main where

import Control.Arrow
import Control.Applicative

import Data.Char

main = zipWith (/=) <$> getLine <*> getLine >>= (map (fromEnum >>> intToDigit) >>> putStr)

module Main where

import Data.Char

main = do
  a:b:_ <- lines `fmap` getContents
  putStr $ zipWith (((intToDigit . fromEnum) .) . (/=)) a b

import Data.Bits (xor)
import Data.Char (digitToInt)

main :: IO ()
main = getContents >>= putStrLn . concatMap show . solve . map (map digitToInt) . lines

solve :: [[Int]] -> [Int]
solve [xs, ys] = zipWith xor xs ys

import Control.Monad
main = putStrLn =<< liftM2 (zipWith xor) getLine getLine
xor '0' '0' = '0'
xor '0' '1' = '1'
xor '1' '0' = '1'
xor '1' '1' = '0'

main = do
    a <- getLine
    b <- getLine
    putStrLn $ solve a b

solve [] [] = []
solve (x:xs) (y:ys) | x /= y = '1' : solve xs ys
                    | otherwise = '0' : solve xs ys

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

getNums :: (Read a,Num a) => IO [a]
getNums = map read. words <$> getLine

xor a b = if a /= b then '1' else '0'

calc as bs = zipWith xor as bs

main = do
  as <- getLine
  bs <- getLine
  putStrLn $ calc as bs

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

chxor :: Char -> Char -> Char
chxor a b = if a == b then '0' else '1'

main :: IO ()
main = do
    s <- getLine
    t <- getLine
    putStrLn $ zipWith chxor s t

main = interact $ f . lines
f (x:y:[]) = calc x y
calc [] [] = ""
calc (a:as) (b:bs) = (if a == b then '0' else '1') : calc as bs

import System.IO

solve :: String -> String -> String
solve [] _ = []
solve (a:as) (b:bs) =
    if a/=b then '1' : solve as bs
    else '0' : solve as bs

main = do
    str1 <- getLine
    str2 <- getLine
    putStrLn $ solve str1 str2

main = do
    s1 <- getLine
    s2 <- getLine
    putStr $ map (\(x, y) -> if x /= y then '1' else '0') $ zip s1 s2

import Data.Char

xor a b = if a==b
 then 0
 else 1

xorlines [] [] = []
xorlines (a:xs) (b:ys) = [(xor a b)]++ xorlines xs ys

main =
 do
  line1 <- getLine
  line2 <- getLine
  putStrLn (foldr (++) " " $ map show (xorlines line1 line2))

get = zipWith f
    where f a b | a /= b = '1'
                | otherwise = '0'

main = do
    a <- getLine
    b <- getLine
    putStrLn $ get a b

module Main (main) where

import System
import Data.Char
import Data.List
import Control.Monad
import Control.Applicative

solve :: [String] -> String
solve [s1,s2] = [xor c1 c2 | (c1,c2) <- zip s1 s2]
                where
                  xor c1 c2
                     | c1 == c2 = '0'
                     | otherwise = '1'

main = interact$solve.take 2.words

main = interact $ (\[a,b]->zipWith (\x y->if x==y then '0' else '1') a b++"\n").lines

main = interact solve
solve input = output where
  inputs = lines input
  output = ans inputs
ans [[],[]] = []
ans [(x:xs),(y:ys)] = (if x==y then '0' else '1') : (ans [xs,ys])

import Control.Applicative
import qualified Data.Set  as S

xor '1' '1' ='0'
xor '0' '0' ='0'
xor '1' '0' ='1'
xor '0' '1' ='1'

main= do

	x<-  getLine
	y<-  getLine
	putStrLn $ zipWith xor x y

{-
A. Ultra-Fast Mathematician
============================
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.

One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.

In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0.

Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.

Now you are going to take part in Shapur's contest. See if you are faster and more accurate.

Input
------
There are two lines in each input. Each of them contains a single number. It is guaranteed that the numbers are made from 0 and 1 only and that their length is same. The numbers may start with 0. The length of each number doesn't exceed 100.

Output
------
Write one line — the corresponding answer. Do not omit the leading 0s.

Sample test(s)
---------------
input
1010100
0100101
output
1110001

input
000
111
output
111

input
1110
1010
output
0100

input
01110
01100
output
00010

-}

charXOR :: Char -> Char -> Char
charXOR '0' '0' = '0'
charXOR '1' '1' = '0'
charXOR '0' '1' = '1'
charXOR '1' '0' = '1'

main = do
  input <- getContents
  let [x, y] = lines input
  putStrLn $ zipWith charXOR x y

main :: IO ()
main = do
    s1 <- getLine
    s2 <- getLine
    putStrLn $ zipWith (curry (head . show . fromEnum . uncurry (/=))) s1 s2

import Data.List
xor [a,b] = if a == b then '0' else '1'
main = interact $ map xor . transpose . lines

main = do
  x1 <- getLine
  x2 <- getLine
  putStrLn $ zipWith comb x1 x2

comb :: Char -> Char -> Char
comb c1 c2
  | c1 == c2 = '0'
  | otherwise = '1'

import Data.Char
import Data.List
import Control.Monad
main = replicateM 2 getLine >>= putStrLn.map (intToDigit.abs.foldl1 (-).map digitToInt).transpose

process :: String -> String -> String
process s t = zipWith f s t
    where
        f x y
            | x == y = '0'
            | otherwise = '1'

main :: IO ()
main = do
    s <- getLine
    t <- getLine
    putStrLn $ process s t

main = do
	str1 <- getLine
	str2 <- getLine
	putStrLn $ calcStr str1 str2

cmpChar :: Char -> Char -> Char
cmpChar x y	| x == y 	= '0'
			| otherwise = '1'

calcStr :: String -> String -> String
calcStr x y = zipWith cmpChar x y

solve :: String -> String
solve s = zipWith (\x y -> if x == y then '0' else '1') xs ys
    where xs:ys:_ = lines s

main=interact $ solve

main=interact$show.(\[x,y]->zipWith(\a b->if a==b then '0' else '1')x y).lines

module Main where

import Control.Arrow
import Control.Applicative

import Data.Char

main = zipWith (==) <$> getLine <*> getLine >>= (map (fromEnum >>> intToDigit) >>> putStr)

main = interact $ f . lines
f (x:y:[]) = calc x y
calc [] [] = []
calc (a:as) (b:bs) = if a == b then "0" else "1" ++ calc as bs


import Data.List
import Data.Set as S

work cards = minimum [length s |
	s <- subsequences "RGBYW12345",
	size (S.map (intersect s) cards) == size cards
	]
main = interact $ show . work . fromList . tail . words

{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as C
import qualified Data.Foldable         as F
import           Data.Function
import           Data.Functor
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Traversable
import           Text.Printf           (printf)

import qualified Data.Set as S
import Data.Char
import Debug.Trace

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  _ <- getLine
  cs <- words <$> getLine
  let ini = [ [ [c, v] `elem` cs  | v <- "12345" ]
            | c <- "RGBYW"
            ]
  print $ minimum $ do
    as <- replicateM 5 [True, False]
    bs <- replicateM 5 [True, False]
    guard $ check as bs ini
    return $ length $ filter id $ as ++ bs

check :: [Bool] -> [Bool] -> [[Bool]] -> Bool
check as bs bd =
  let st = [ [ not (b && a) && c
           | (c, b) <- zip row bs
           ]
         | (row, a) <- zip bd as
         ]

      step = (transpose . remo bs . transpose) . remo as
      ss = iterate step st

  in 1 >= length (filter id $ concat $ snd $ head $ dropWhile (\(a, b) -> a/=b) $ zip ss (tail ss))

remo :: [Bool] -> [[Bool]] -> [[Bool]]
remo rs = zipWith f rs where
  f r row
    | r && length (filter id $ row) == 1 = replicate 5 False
    | otherwise = row

import Control.Monad
import Data.Set as S

work cards = minimum [length s |
	s <- filterM (const [True, False]) "RGBYW12345",
	size (S.map (Prelude.map (\c -> if elem c s then c else '-')) cards) == size cards
	]
main = interact $ show . work . fromList . tail . words

import Control.Monad
import Data.Set as S

pow = filterM $ const [True, False]
has s a = if elem a s then a else '-'
work cards = minimum [length cs + length vs |
	cs <- pow "RGBYW", vs <- pow "12345",
	size (S.map (zipWith has [cs, vs]) cards) == size cards
	]
main = interact $ show . work . fromList . tail . words

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

distinguish :: Char -> [String] -> [[String]]
distinguish c xs = let (a, b) = partition (c `elem`) xs in [a,b]

maybeDistinguish :: Char -> (Int, [[String]]) -> [(Int, [[String]])]
maybeDistinguish c (k, ss) =
	[(k, ss), (k + 1, distinguish c =<< ss)]

allSingle :: [[a]] -> Bool
allSingle = all ((<= 1) . length)

main :: IO ()
main = do
	n <- inputInt
	cards <- nub . take n . words <$> getLine
	let results = foldl' (>>=) [(0, [cards])] $ map maybeDistinguish "RGBYW12345"
	print . minimum . map fst . filter (allSingle . snd) $ results

import Data.List
u x=length.group.sort$x
(#)=elemIndex
q=subsequences
s l=minimum[length$a++b|a<-q"RGBYW",b<-q"12345",u l==u(map(\[x,y]->(x#a,y#b))l)]
main=interact$show.s.tail.words

import Control.Monad
import Data.List
import Data.Set as S

work cards = minimum [length s |
	s <- filterM (const [True, False]) "RGBYW12345",
	size (S.map (intersect s) cards) == size cards
	]
main = interact $ show . work . fromList . tail . words

import Control.Monad
import qualified Data.Set as S

work cards = minimum [length s |
	s <- filterM (const [True, False]) "RGBYW12345",
	S.size (S.map (map (\c -> if elem c s then c else '-')) cards) == S.size cards
	]
main = interact $ show . work . S.fromList . tail . words


countPoints :: Int -> Int -> [Int] -> [Int] -> Int
countPoints n c ps ts = sum $ zipWith (\p x -> max 0 (p-c*x)) ps cts
    where cts = scanl1 (+) ts

result :: Int -> Int -> [Int] -> [Int] -> Ordering
result n c ps ts = (countPoints n c ps ts) `compare` (countPoints n c (reverse ps) (reverse ts))

readInt :: String -> Int
readInt = read

showOrdering :: Ordering -> String
showOrdering GT = "Limak"
showOrdering EQ = "Tie"
showOrdering LT = "Radewoosh"

main = do
    [n,c] <- fmap (map readInt.words) getLine
    ps <- fmap (map readInt.words) getLine
    ts <- fmap (map readInt.words) getLine
    putStrLn.showOrdering $ result n c ps ts

main = do
    [n,c] <- fmap ((map read) . words) getLine :: IO[Int]
    p <- fmap ((map read) . words) getLine :: IO[Int]
    t <- fmap ((map read) . words) getLine :: IO[Int]
    putStrLn $solve n c p t

solve n c p t =
    let sl = tail $ scanl (+) 0 t
        sr = init $ scanr (+) 0 t
    in case compare (fn p sl c) (fn p sr c) of
        LT -> "Radewoosh"
        EQ -> "Tie"
        GT -> "Limak"

fn pl tl c = sum (zipWith (\p t -> max 0 (p - (c*t))) pl tl)

import Data.Char
import Control.Monad

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

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

f [] [] duration c = 0
f (a:ax) (b:bx) duration c = (max 0 (a - c * duration - c * b)) + (f ax bx (duration + b) c)

main = do
    n <- readInt
    c <- readInt
    p <- readArr n readInt
    t <- readArr n readInt
    let limak = f p t 0 c
    let radewoosh = f (reverse p) (reverse t) 0 c
    let ans = if limak > radewoosh then "Limak" else if radewoosh > limak then "Radewoosh" else "Tie"
    putStrLn ans

f ::Int->[Int]->[Int]->Int
f _ [] []=0
f p (x:xs) (y:ys)
    |x-y*p<=0=f p xs ys
    |otherwise=(x-y*p)+f p xs ys

main = do
       e<-getLine
       e2<-getLine
       e3<-getLine
       let (n:p:[])=map read (words e)::[Int]
           xs=map read (words e2)::[Int]
           ys=map read (words e3)::[Int]
           s1=f p xs (scanl1 (+) ys)
           s2=f p (reverse xs) (scanl1 (+) (reverse ys))
       putStrLn $ if s1==s2 then "Tie" else if s1>s2 then "Limak" else "Radewoosh"

main = do first <- getLine
          sp <- getLine
          st <- getLine
          let n:c:[] = (map read.words) first
          let p = (map read.words) sp
          let t = (map read.words) st
          case compare (li n c p t) (ra n c p t) of
            LT -> putStrLn "Radewoosh"
            GT -> putStrLn "Limak"
            EQ -> putStrLn "Tie"
li :: Int -> Int -> [Int] -> [Int] -> Int
li n c p t = (sum.map (f c)) (zip p (scanl1 (+) t))
ra :: Int -> Int -> [Int] -> [Int] -> Int
ra n c p t = (sum.map (f c)) (zip p (scanr1 (+) t))
f :: Int -> (Int, Int) -> Int
f c (p, x) = max 0 (p - c*x)


import Control.Applicative
main = do
    [a, b] <- map read . words <$> getLine
    let n = logBase (3 / 2) (b / a)
    print $ if fromIntegral (ceiling n) == n then ceiling n + 1 else ceiling n

module Main
    where

import System.IO

calc a b =
    calc' a b 0
    where
        calc' a b c =
            if a <= b then
                calc' (a * 3) (b * 2) (c + 1)
            else
                c

solve line =
    calc a b
    where
        [a, b] =
            map read . words $ line

main = do
    line <- getLine
    print $ solve line

solve :: Integer -> Integer -> Integer -> Integer
solve l b n | l * (3 ^ n) > b * (2 ^ n) = n
            | otherwise = solve l b (n + 1)

main :: IO ()
main = do
    raw <- getLine
    let input = map (\x -> read x :: Integer) $ words raw

    putStrLn $ show $ solve (input !! 0) (input !! 1) 1

main = do
  n <- fmap (map read.words) getLine :: IO [Int]
  let f (a, b, c) = if (a * 3 > b * 2) then c else f (a*3, b*2, c + 1)
  putStrLn( show $ f(n!!0, n!!1, 1) );

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

solve :: [Integer] -> Int
solve [a, b] | a > b = 0
             | otherwise = 1 + solve [a * 3, b * 2]

main = do
  s <- getLine
  let [a, b] = map (read :: String -> Int) $ words s
      t = head [k | k<-[1..], 3^k*a > 2^k*b]
  print t

main :: IO ()
main = do
  line <- getLine
  print $ weight 0 $map (read :: String -> Int) $ words line

weight :: (Ord a, Num t, Num a) => t -> [a] -> t
weight i [a, b] = if a > b then i else weight (i+1) [a*3, b*2]
weight _       _= -1

{-# LANGUAGE BlockArguments #-}

import Control.Arrow

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

toFloat :: Int -> Double
toFloat x = (fromIntegral x)::Double

solve :: [Int] -> Int
solve [a,b] = floor(logBase 1.5 (toFloat b) - logBase 1.5 (toFloat a) + 1.0001)

solve :: [Int] -> Int -> Int
solve [a, b] years | a > b     = years
                   | otherwise = solve [a * 3, b * 2] (years + 1)

main :: IO ()
main = do
    line <- getLine
    let row = map read . words $ line
    print $ solve row 0

module Main(main) where

main :: IO ()
main = do
    [a, b] <- fmap (map read . words) getLine :: IO [Int]
    print . length $ takeWhile id [a * (3 ^ p) <= b * (2 ^ p) | p <- [0..]]

-- Codeforces 791A
import Data.List
main :: IO ()
main = do
    [limak, bob] <- getLine >>= return.(map read).words :: IO [Int]
    let zipped = zip3 (iterate (+1) 0) (iterate (*3) limak) (iterate (*2) bob) :: [(Int, Int, Int)]
    let Just (year, _, _) = find (\(y, l, b) -> l > b) zipped
    putStrLn $ show year

module Main where

getanswer :: Int -> [Int] -> Int
getanswer n [a, b] =
    if a > b
      then n
    else
      getanswer (n+1) [(a*3), (b*2)]
getanswer _ _ = 0

main :: IO ()
main = do
  getLine >>= putStrLn.show.(getanswer 0).(map (read :: [Char] -> Int)).words

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = (solve.concat =<< forM [1 ..1] ( \i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))
solve [x,y] = print $ head $ snd $ break (\a-> (x*3^a)>(y*2^a)) [1..]

{-#LANGUAGE OverloadedStrings#-}
module Main where

import Data.Text (splitOn, pack, unpack)

main :: IO ()
main = getInt >>= solve 0 >>= putStrLn . show

solve :: Int -> [Int] -> IO Int
solve i [a,b]
    | a > b = pure i
    | otherwise = solve (i+1) [3*a,2*b]

getInt :: IO [Int]
getInt = fmap (map (read . unpack)
            . splitOn " " . pack) getLine

{-# OPTIONS_GHC -fno-warn-tabs #-}
import Data.List;
import System.IO;
import Data.Maybe;

solve :: Int -> Int -> Int -> Int;
solve a b y
	| a > b = y
	| otherwise = solve (a*3) (b*2) (y+1);

main = do
	str <- getLine;
	let strs = map read (words str) :: [Int];
	print $ solve (head strs) (head (tail strs)) 0;

main = getLine
   >>= putStrLn . show . calc . parse . words

parse::[String] -> (Int, Int)
parse [a, b] = (read a, read b)

calc::(Int, Int) -> Int
calc (a, b)
  | a <= b = calc (a * 3, b * 2) + 1
  | otherwise = 0

import Text.Printf
import Data.List
import Data.Functor
import Prelude

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [a, b] <- (map readInt . words) <$> getLine
    let
        answer :: Int
        Just answer = find (\x -> a * 3 ^ x > b * 2 ^ x) [1..]
    printf "%d" answer

main = do
    line <- getLine
    let [a, b] = map read (words line)

    let limak = [a * (3 ^ m) | m <- [0..]]
    let bob = [b * (2 ^ m) | m <- [0..]]

    print $ length $ takeWhile (\(a, b) -> a <= b) $ zip limak bob

import Control.Applicative

process a b n | a>b = n
              | otherwise = process (3*a) (2*b) (n+1)

main=do

      [a,b]<- map read <$> words <$>  getLine ::IO [Int]
      print $ process  a b 0

import Data.List

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

mas:: IO()
has a b = succ$length$[x | x<-[1..100], a*3^x<=b*2^x]
mas = do
  [a,b]<-fmap (map read.words) getLine
  print$has a b

main :: IO()
main = mas

exceed :: String -> Int
exceed s = (floor $ logBase 1.5 (b / a)) + 1
  where a = nums !! 0
        b = nums !! 1
        nums = map read . words $ s :: [Float]

main = do
  s <- getLine
  print $ exceed s

main = interact $ show . length . takeWhile (uncurry (<=)) .
                  iterate grow . ((,) <$> (!!0) <*> (!!1)) . map read . words
grow (a,b) = (3*a,2*b)

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

glwr = fmap (map read . words) getLine

main = do
  hSetBuffering stdout NoBuffering
  solve

solve :: IO ()
solve = do
  a:b:_ <- glwr

  print $ bear a b

bear :: Int -> Int -> Int
bear a b
  | a > b = 0
  | 0 < 1 = 1 + bear (a*3) (b*2)

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

getInt :: IO Int
getInt = readLn

getList :: IO [Int]
getList = do
            xs <- getLine
            return $ map read $ words xs

getNList :: Int -> IO [[Int]]
getNList 0 = return [[]]
getNList n = do
              xs <- getList
              fmap (xs:) $ getNList (n-1)

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

solve :: Int -> Int -> Int -> Int
solve a b t | a > b = t
            | otherwise = solve (3*a) (2*b) (t+1)

main = do
  (a:b:[]) <- getList
  print $ solve a b 0

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

main :: IO ()
main = do
    [a,b] <- fmap (map read . words) getLine :: IO [Int]
    print . length $ takeWhile id [a*(3^p) <= b*(2^p) | p <- [0..]]

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

solve :: [Int] -> Int
solve [a,b] | a > b = 0
            | otherwise = 1 + solve [a*3, b*2]

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

parseInts :: String -> [Int]
parseInts str = map read (words str)

solver :: Int -> Int -> Int
solver x y =
    if x > y then 0
    else 1 + (solver (x * 3) (y * 2))

main = do
    integers <- fmap parseInts getLine
    putStrLn (show (solver (integers!!0) (integers!!1)))

import Control.Applicative( (<$>))
main = do
    [a_, b_] <- map read . words <$> getLine
    let
	proc n limak bob =	let
				limak' = limak*3
				bob' = bob*2
			    in
				if limak' > bob'
				    then n+1
				    else proc (n+1) limak' bob'
    print $ proc 0 a_ b_

module Main where

infixl 0 |>
x |> f = f x

solve :: [Int] -> Int -> Int
solve [a, b] years | a > b     = years
                   | otherwise = solve [a * 3, b * 2] (years + 1)

main :: IO ()
main = do
  line <- getLine
  let row = line |> map read . words
  solve row 0 |> print

main = do
    input <- getLine
    let [limak, bob] = map read $ words input
    print $ solve [limak, bob] 0

solve :: [Integer] -> Integer -> Integer
solve [limak, bob] year
    | limak > bob = year
    | otherwise = solve [limak * 3, bob * 2] (year + 1)

main = do
    n <- getLine
    print . f . g . stoi . words $ n

stoi :: [[Char]] -> [Int]
stoi []     = []
stoi (n:ns) = (read n::Int) : stoi ns

g :: [Int] -> (Int,Int)
g (x:y:[]) = (x,y)

f :: (Int,Int) -> Int
f (x,y)
    | x <= y    = 1 + f (3*x, 2*y)
    | otherwise = 0

solve :: String -> Int
solve input =
    let (a:b:_) = map (\xs -> read xs :: Int) (words input)
        la = [a * (3 ^ p) | p <- [0, 1..]]
        lb = [b * (2 ^ p) | p <- [0, 1..]]
        lc = zipWith (>) la lb
    in  length $ takeWhile (\x -> x == False) lc

main = do
    input <- getLine
    print $ solve input

getID :: [Bool] -> Int
getID (x:xs)
    | x == True = 0
    | otherwise = 1 + getID xs

solve :: String -> Int
solve input =
    let (a:b:_) = map (\xs -> read xs :: Int) (words input)
        la = [a * (3 ^ p) | p <- [0, 1..]]
        lb = [b * (2 ^ p) | p <- [0, 1..]]
        lc = zipWith (>) la lb
    in  getID lc

main = do
    input <- getLine
    print $ solve input

main :: IO ()
main = do
    [a, b] <- map read <$> words <$> getLine
    let x = -1 * (log (a / b)) / (log (3 / 2))
    let cx = ceiling x
    print $ if x < (fromIntegral cx) then cx else cx + 1

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

import Control.Monad (forM_, forM)

bin :: Integer -> Integer -> Integer -> Integer -> Integer
bin a b x y | x >= y - 1 = if a * 3^x == b * 2^x then x + 1 else y
            | a * 3^m > b * 2^m  = bin a b x m
            | a * 3^m == b * 2^m = m + 1
            | otherwise = bin a b m y where
    m = (x + y) `div` 2

run a b = bin a b 0 1000

main = do
    ((map read) . words -> [a, b]) <- getLine
    putStrLn $ (show $ run a b)

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

ans a b = (\(x1,y1,z1)->x1) $ head $ dropWhile (\(x,y,z)-> y<=z) $  [(i,a*3^i,b*2^i)| i<-[1..]]

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

solve :: Int -> Int -> Int
solve l b
    | l > b = 0
    | otherwise = 1 + solve (3*l) (2*b)

main :: IO ()
main = do
    [l,b] <- map (read :: String -> Int) . words <$> getLine
    print $ solve l b

main :: IO ()
main = do
    val <- getLine
    let (n:k:_) = map read $ (words val) ::[Int]
    print(grow n k 0)

grow ::(Num a, Ord a) => a -> a -> a -> a
grow n k j
    |n <= k = grow (n * 3) (k * 2) (j + 1)
    |otherwise = j

--ghc 7.10

yearCount :: Float -> Float -> Int
yearCount a b =
    if 3^k * a > 2^k * b
        then k
        else k+1
    where
        k = floor $ log (b / a) / log (ra / rb)
        ra = 3.0
        rb = 2.0

main = do
    line <- getLine
    let [a,b] = map read . words $ line :: [Float]
    print $ yearCount a b

lastTuple :: (Int, Int, Int) -> Int
lastTuple (a, b, c) = c

process :: (Int, Int) -> Int
process (small, big) =
    lastTuple $ until (\(x,y,z) -> x > y) (\(x,y,z) -> (x*3, y*2, z+1)) (small, big, 0)

main :: IO ()
main = do
    [small, big] <- fmap( map read . words) getLine
    let result = process (small, big)
    putStrLn (show result)

-- {-# LANGUAGE MagicHash #-}
module Main where

-- import           GHC.Integer.Logarithms (integerLogBase#)

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

f (x:y:_) = length . takeWhile (uncurry (<=)) . iterate (\(a,b) -> (a*3, b*2)) $ (x,y)

{-# LANGUAGE BlockArguments #-}

import Control.Arrow

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

toFloat :: Int -> Double
toFloat x = (fromIntegral x)::Double

solve :: [Int] -> Int
solve [a,b] = floor(logBase 1.5 (toFloat b) - logBase 1.5 (toFloat a) + 1)

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

ans a b = (\(x1,y1,z1)->x1) $ head $ dropWhile (\(x,y,z)-> y<z) $  [(i,a*3^i,b*2^i)| i<-[1..]]

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


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

solve :: [Int] -> Int
solve [n, k] = n + k - n `mod` k

solve [n, k] = x' - x' `mod` k
    where x' = n + k

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

module Main where

main = do
    [n,k] <- map (read :: String -> Int) . words <$> getLine
    let a = n`mod`k
    print $ n + if a == 0 then k else k-a

main = getLine >>= print . (\[n, k] -> n + k - n `mod` k) . map read . words

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

solve :: [Int] -> Int
solve (a:b:_) = (a `div` b) * b + b

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

main = do
		[n,k]<- map read <$> words <$> getLine ::IO [Int]
		print $ n + (k - mod n k)


okBranch :: Int -> Int -> Bool
okBranch p branch =  null $ filter (`divides` branch) [2..limit]
  where divides n = (==0) . (`rem` n)
        limit     = min p . floor . sqrt . fromIntegral $ branch

main :: IO ()
main = let output l = if null l then -1 else head l in do
  l <- getLine
  let [p, y] =  map read . words $ l
  print . output . filter (okBranch p) $ [y,y-1..p+1]

import Control.Monad

(%) = rem

check :: Int -> Int -> Bool
check p n = let s = floor $ sqrt $ fromIntegral n
                divs = filter (\x -> (n % x) == 0) [y | y <- [2..s]] in
                null divs || p < head divs

main = do
        [p, y] <- (liftM ((map read).words) $ getLine) :: IO [Int]
        print $ (\xs -> if null xs then -1 else head xs)  $ filter (check p) [y,(y-1)..p + 1]


import Control.Applicative
import Data.List

process [] n = n
process (s:ss) n | s=='1' = process ss (n+1)
	         | otherwise = n+1

main= do
	getLine
	s<- getLine
	print $ process s 0

import Numeric
import Data.Char
readBin = foldr (\c s -> s * 2 + c) 0 . reverse . map c2i
    where c2i c = if c == '0' then 0 else 1
showBin x = showIntAtBase 2 intToDigit x ""
main = do
  getLine
  line <- getLine
  let ans = sum (zipWith (\x y -> if x == y then 0 else 1) line (take (length line) (reverse (showBin ((readBin (reverse line)) + 1)))))
  print ans

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

main = interact $ show . getAns . last . words

getAns :: String -> Int
getAns xs = min (length xs) (((+1) . (\xs@(x:_) -> if x == '1' then length xs else 0) . head . group) xs)

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

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

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

main = do
  getLine
  bs <- getLine

  let
    bs' = map (== '1') bs
    bs'' = add bs' True
      where
        add [] _ = []
        add (b:bs) f = (if b then not f else f):(add bs $ b && f)

  print $ length $ filter id $ zipWith (/=) bs' bs''

import Control.Monad

main :: IO ()
main = do
  n <- fmap read getLine
  l <- liftM (length.takeWhile (=='1')) getLine
  print$min n (l+1)

module Main where

import Control.Monad

main :: IO ()
main =
  do n <- readLn
     l <- replicateM n $ getChar
     print $ (\x -> if x == length l then x else x + 1) $ length $ takeWhile (== '1') l
     return ()

main :: IO ()
main = getContents >>= print . solve . lines

solve :: [String] -> Int
solve [_, cs] = min (length cs) (length (takeWhile (=='1') cs) + 1)
solve _ = undefined

main = getContents >>= print . solve . lines
solve [n, cs] = min (read n) (length (takeWhile (=='1') cs) + 1)

main = do
  sz <- fmap read getLine
  count <- (getLine >>= return . length . takeWhile (== '1'))
  print $ min sz (count + 1)

solve :: [Char] -> Int
solve x =
	if res == length x then res
	else res + 1
	where
		res = solve_ x
		solve_ [] = 0
		solve_ (x:xs) = if x == '1' then 1 + (solve_ xs) else 0

main = interact $ show.solve.head.tail.lines


{-
import HUnit

testInput :: Test
testInput  =  TestList "TestInput"
  [
    Test "1" $ assertEq 4 (solve 7 2),
    Test "2" $ assertEq 54 (solve 59 9)
  ]

testMaximum :: Test
testMaximum  =  TestList "TestMaximum"
  [
    Test "1" $ assertEq 500000008 (solve (10^9) 2),
    Test "2" $ assertEq 1 (solve 1 2),
    Test "3" $ assertEq 888888894 (solve (10^9) 9)
  ]

test :: IO ()
test  =  mapM_ run
  [
    testInput,
    testMaximum
  ]

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

-}

v :: Int -> Int -> Int
v 0 k  =  0
v n k  =  n + v (div n k) k

solve :: Int -> Int -> Int
solve n k  =  solve' 1 n
  where
    solve' l r
      | l + 1 >= r  =  r
      | v m k >= n  =  solve' l m
      | otherwise  =  solve' m r
      where
        m  =  div (l+r) 2

main :: IO ()
main  =  do
    line  <-  getLine
    let [n, k]  =  map read $ words line
    print $ solve n k

import Control.Applicative

solve n k = search 1 n
	where
		search l r
			| l >= r = l
			| s >= n = search l m
			| s < n = search (m + 1) r
			where
				m = (l + r) `div` 2
				s = sum $ takeWhile (/= 0) $ iterate (`div` k) m

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

import Debug.Trace

write k v = write' 1 v
    where
        write' q v | v < q = 0
        write' q v = v `div` q + write' (k * q) v

binsearch b e f | b >= e = b
binsearch b e f =
    let
        p = (b + e) `div` 2
    in
        if f p < 0
        then
            binsearch (p + 1) e f
        else
            binsearch b p f

main = do
    words <- getLine >>= return.words
    let (n, k) = (read(words !! 0)::Integer, read(words!!1)::Integer)
    let r = binsearch 1 n (\v -> write k v - n)
    if write k r < n then print (r + 1) else print r

binarySearch :: (Integral a) => (a -> Bool) -> a -> a -> a
binarySearch p l h
  | h < l     = h+1
  | p m       = binarySearch p l (m-1)
  | otherwise = binarySearch p (m+1) h
    where m = (l + h) `div` 2

series v k = sum $ takeWhile (>0) $ map (floor.(v/).(k^)) [0..]

predicate :: Int -> Int -> Int -> Bool
predicate n k v
  | s < n     = False
  | otherwise = True
    where s = series (realToFrac v) (realToFrac k)

code :: Int -> Int -> Int
code n k = binarySearch (predicate n k) 1 (10^9)

main :: IO()
main = do
  input <- getContents
  let (n:k:_) = map read (words input) :: [Int]
  putStr $ show $ code n k

{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}
import Control.Monad
import Control.Applicative
import Debug.Trace
import qualified Data.ByteString.Char8 as B
import qualified Data.Char as C

atoi :: B.ByteString -> Int
atoi = B.foldl' (\a c -> a*10 + C.ord c - C.ord '0') 0

bisearch :: (Int -> Bool) -> Int -> Int -> Int
bisearch p lo hi
    | lo+1 == hi = hi
    | p mid = bisearch p lo mid
    | otherwise = bisearch p mid hi
  where mid = (lo + hi) `div` 2

solve :: Int -> Int -> Int
solve n k = bisearch ((>=n) . sumline k) 0 n

sumline :: Int -> Int -> Int
sumline k = sum . takeWhile (> 0) . iterate (flip div k)

main = do
    [n, k] <- map atoi . B.words <$> B.getLine
    putStrLn . show $ solve n k

main = do getLine >>= print . gao . map read . words
gao [n, k] = f 0 (n * k) where
    g m = sum $ takeWhile (>0) $ iterate (`div` k) m
    f l r
        | l == r    = r
        | otherwise = let m = div (l + r) 2 in if g m < n then f (m + 1) r else f l m

module Main where

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

import Data.Time.Calendar

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

solve :: [Int] -> Int
solve [n, k] = maxV (-1) n n k

maxV :: Int -> Int -> Int -> Int -> Int
maxV leftV rightV n k
    | leftV == rightV - 1 = rightV
    | otherwise = let middleV = (leftV + rightV) `div` 2 in
        if solution middleV k >= n
            then maxV leftV middleV n k
            else maxV middleV rightV n k

solution :: Int -> Int -> Int
solution = solution' 0
solution' result 0 _ = result
solution' result v k = solution' (result + v) (v `div` k) k

import System.IO

main = print . solve =<< parse stdin

parse h = fmap (f . map read . words) getLine
   where f [x,y] = (x,y)

solve :: (Int, Int) -> Int
solve (n,k) = solve' init
   where
      init = (0, 10^9)
      solve' (a, b)
         | a + 1 >= b = b
         | cnt >= n   = solve' (a, c)
         | otherwise  = solve' (c, b)
         where
            c   = (a + b) `div` 2
            cnt = count c
      count 0 = 0
      count v = v + count (v `div` k)

-- vim: set expandtab:

import Control.Monad
import Data.List
binSearch n k lo hi =
  if lo + 1 == hi then hi
  else let mid = div (lo + hi) 2
           val = sum $ unfoldr (\x -> if x == 0 then Nothing else Just (x, div x k)) mid
       in if val >= n then binSearch n k lo mid
                      else binSearch n k mid hi
main = do
  [n, k] <- (liftM $ (map read) . words) getLine
  putStrLn . show $ binSearch n k 0 n

solve n k = search 1 n
	where
		search l r
			| l >= r = l
			| s >= n = search l m
			| s < n = search (m + 1) r
			where
				m = (l + r) `div` 2
				s = sum $ takeWhile (/= 0) $ iterate (`div` k) m

main = do
	[n, k] <- (map read . words) `fmap` getLine
	print $ solve n k

main = getLine >>= putStrLn . show . func . map read . words

func :: [Integer] -> Integer
func [n, k] =  fst . head $ takeWhile (flip (<=) (n+20) . snd ) testlist
		where
				ans v = v + test[v,k,1]
				testlist = [ (v,ans v) | v <- [(n - n`div`k)..n], ans v >= n]
test [v,k,s]
		| acc > 0 = acc + test [v,k,s+1]
		| acc == 0 = 0
		where acc = v `div` k^s

solve :: Int -> Int -> Int
solve n k  =  solve' n k (0, n)
  where
    solve' :: Int -> Int -> (Int, Int) -> Int
    solve' n k (l, r)
      | l + 1 == r  =  r
      | f m k >= n  =  solve' n k (l, m)
      | otherwise   =  solve' n k (m, r)
      where
        m  =  div (l+r) 2

f :: Int -> Int -> Int
f 0 _  =  0
f v k  =  v + f (div v k) k

main :: IO ()
main  =  do
    line <- getLine
    let [n, k]  =  map read (words line)
    print $ solve n k

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

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

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

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

binarySearch :: (Integer -> Bool) -> Integer -> Integer
binarySearch test falseValue = head [ loop falseValue (falseValue + 2 ^ i)
                                    | i <- [0..]
                                    , test (falseValue + 2 ^ i)
                                    ]
  where
    -- test lo == False, test hi = True
    loop lo hi
        | lo + 1 == hi = hi
        | test mid     = loop lo mid
        | otherwise    = loop mid hi
      where
        mid = (lo + hi) `div` 2

solve (n, k) = binarySearch test 0
  where
    test c = getSum c >= n
    getSum 0 = 0
    getSum a = a + getSum (a `div` k)

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

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

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

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

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

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

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

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

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

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

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

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

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

state = State

main = do
  [n,k] <- fmap (map read . words) getLine
  print $ solve n k 0 (n*k)
solve n k a b | a >= b - 1   = b
              | try k c >= n = solve n k a c
              | otherwise    = solve n k c b
    where c = (a + b + 1) `div` 2
try k v = sum . map (v `div`) . takeWhile (<= v) $ iterate (*k) 1

main = interact $ show.solve.map read.words
solve [n,k] = let p v = (>=n) . sum . takeWhile (>0) . map (div v) $ iterate (k*) 1
              in bsearch p 0 (n+1)

bsearch p l m
  | l >= m = l
  | p ((l+m)`div`2) = bsearch p l ((l+m)`div`2)
  | otherwise = bsearch p ((l+m)`div`2+1) m

import Control.Applicative
import Control.Monad

bs' :: Int -> Int -> (Int, Int) -> Int
bs' n k (lower, upper)
        | lower == upper = lower
        | (calc' mid k) < n = bs' n k (mid+1, upper)
        | otherwise = bs' n k (lower, mid)
        where mid = (lower + upper) `div` 2

calc' v k
    | v == 0 = 0
        | otherwise = v + (calc' (v `div` k) k)

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

main = do
    [n, k] <- readInts

    putStr (show (bs' n k (1, 10^9)))

main = getLine >>= putStrLn . show .func .map read. words

func :: [Int] -> Int
func [n, k] = head $ [ v | v<-[1..n] , ans v >= n]
        where ans v = v + test[v,k]

test [v,k]
        | acc >0 = acc + test [v,k*k]
        | acc == 0 = 0
        where acc = v `div` k

write k v = write' 1 v
    where
        write' q v | v < q = 0
        write' q v = v `div` q + write' (k * q) v

binsearch b e f | b >= e = b
binsearch b e f =
    let
        p = (b + e) `div` 2
    in
        if f p < 0
        then
            binsearch (p + 1) e f
        else
            binsearch b (p - 1) f

main = do
    words <- getLine >>= return.words
    let (n, k) = (read(words !! 0)::Int, read(words!!1)::Int)
    let r = binsearch 1 n (\v -> write k v - n)
    if write k r < n then print (r + 1) else print r


flrDiv :: Integral a => a -> a -> a
flrDiv a b = div (a+b-1) b

readInts :: String -> [Int]
readInts str = map read (words str)

main :: IO ()
main = do

  as <- fmap readInts getLine
  bs <- fmap readInts getLine
  n <- fmap read getLine :: IO Int
  let b = (flrDiv (sum as) 5) + (flrDiv (sum bs) 10) <= n
  putStr $ if b then "YES" else "NO"

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  as <- getInts
  bs <- getInts
  n <- readLn

  putStrLn $ if (sum as + 4) `div` 5 + (sum bs + 9) `div` 10 <= n then "YES" else "NO"

import Control.Applicative

parse = map read . words

main = do
  cs <- parse <$> getLine
  ms <- parse <$> getLine
  n  <- read <$> getLine
  let c = sum cs
      m = sum ms
      n1 = (n*5 - c) `div` 5
      n2 = (n1*10-m) `div` 10
  putStrLn $
    if n2 >= 0 then "YES" else "NO"

import Control.Applicative

main = do
  cups <- sum . map read . words <$> getLine
  medals <- sum . map read . words <$> getLine
  n <- readLn

  let cs = (cups + 4) `div` 5
      ms = (medals + 9) `div` 10
      s = cs + ms
    in putStrLn $ if s <= n then "YES" else "NO"

import Control.Applicative
import Data.List

process n q1 q2 | sq1+sq2 <= n= "YES"
                | otherwise = "NO"
      where sq1= (div ((sum q1)-1) 5)+1
            sq2= (div ((sum q2)-1) 10)+1

main = do
  q1<-  map read  <$>   words  <$> getLine ::IO [Int]
  q2<-  map read  <$>   words  <$> getLine ::IO [Int]
  n<- read <$> getLine ::IO Int
  putStrLn  $ process n q1 q2

main :: IO ()
main = getContents >>= putStrLn . yesno . solve . map (map read . words) . lines

solve :: [[Int]] -> Bool
solve [as, bs, [n]] = sum as // 5 + sum bs // 10 <= n

(//) :: Integral a => a -> a -> a
x // y = (x + y - 1) `div` y

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

main = do
  cs <- fmap (sum . map read . words) getLine
  ms <- fmap (sum . map read . words) getLine
  s <- readLn
  putStrLn $ if (cs + 4) `div` 5 + (ms + 9) `div` 10 > s then "NO" else "YES"

main :: IO ()
main = do
  sa <- getLine
  sb <- getLine
  sn <- getLine
  let suma = sum . map read $ words sa
      sumb = sum . map read $ words sb
      tot = ceiling ((/) suma 5) + ceiling ((/) sumb 10)
      n = read sn
      res = if tot <= n then "YES" else "NO"
  putStrLn res

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
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.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
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=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# 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
  x <- sum.map readInt.B.words <$> B.getLine
  y <- sum.map readInt.B.words <$> B.getLine
  n <- readLn
  putStrLn.bool"YES""NO" $ solve n x y

solve :: Int -> Int -> Int -> Bool
solve n x y = (x+4)`div`5 + (y+9)`div`10 <= n

import Control.Applicative
main = do
	a <- (`div` 5) . (+4) . sum . map read . words <$> getLine
	b <- (`div` 10) . (+9) . sum . map read . words <$> getLine
	n <- read <$> getLine
	putStrLn $ if a + b > n then "NO" else "YES"

import Control.Applicative
main = do
	a <-  ceiling . (/5) . sum . map read . words <$> getLine
	b <- ceiling . (/10) . sum . map read . words <$> getLine
	n <- read <$> getLine
	putStrLn $ if a + b > n then "NO" else "YES"

import Control.Applicative

calc a b = div (sum a) b +(if mod (sum a) b>0 then 1 else 0)

main=do
	a<-map read.words <$> getLine::IO [Int]
	b<-map read.words <$> getLine::IO [Int]
	c<- read <$> getLine::IO Int
	putStrLn $ if c>= (calc a  5+ calc b 10) then "YES" else "NO"

import Control.Monad
import Data.List

main = replicateM 3 getLine
   >>= putStrLn . solve . map sum
   where sum = foldl1 (+) . map read .words

solve :: [Float] -> String
solve [a, b, n] = if ceiling(a / 5.0) + ceiling(b / 10.0) <= ceiling(n) then "YES" else "NO"

main :: IO ()
main = interact solve

solve :: String -> String
solve s
    | (a `divUp` 5) + (b `divUp` 10) <= n = "YES"
    | otherwise = "NO"
        where [a, b, n] = (fmap (sum . fmap read . words) . lines) s :: [Int]

divUp :: (Integral a) => a -> a -> a
divUp a b =  (a + b - 1) `div` b

module Main where

main = do
	line1 <- getLine
	line2 <- getLine
	line3 <- getLine
	let a = readIntList line1
	let b = readIntList line2
	let n = read line3 :: Int

	putStr $ result a b n

result a b n = sayYesNo $ ((ceiling' a' 5.0) + (ceiling' b' 10.0)) <= n
	where
		sayYesNo bool = if bool then "YES" else "NO"
		ceiling' s alpha = ceiling (toRational s / alpha)
		a' = sum a
		b' = sum b

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

parseInput :: String -> ([Int], [Int], Int)
parseInput input = (xs, ys, n) where
    ls = lines input
    xs = map read $ words $ head ls
    ys = map read $ words $ head $ tail ls
    n = read $ last ls

solve xs ys n | m <= n    = "YES"
              | otherwise = "NO"
    where x = sum xs
          y = sum ys
          m = (x + 4) `div` 5 + (y + 9) `div` 10

main :: IO ()
main = do
    input <- getContents
    let (xs, ys, n) = parseInput input
    putStrLn $ solve xs ys n

module Main (main)
    where

import Control.Monad (replicateM)

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

main :: IO ()
main = putStrLn . toYesNo . solve . map readInts =<< replicateM 3 getLine
    where solve [as,bs,[n]] = n >= shelves (sum as) 5 + shelves (sum bs) 10
          shelves c m = let (q,r) = divMod c m in q + min 1 r
          toYesNo True  = "YES"
          toYesNo False = "NO"

main = do
	as<-getLine
	bs<-getLine
	n<-getLine
	let [a1,a2,a3] =map read $ words as
	let [b1,b2,b3]= map read $ words bs
	putStrLn $ solve a1 a2 a3 b1 b2 b3 (read n)

solve a1 a2 a3 b1 b2 b3 n = if div (a-1) 5 + div (b-1) 10 +2 <=n then "YES" else "NO"
	     where a=a1+a2+a3
	           b=b1+b2+b3

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

solve :: [Int] -> String
solve [a1, a2, a3, b1, b2, b3, n] = let a = a1 + a2 + a3
                                        b = b1 + b2 + b3
                                        na = div (a + 4) 5
                                        nb = div (b + 9) 10
                                    in if na + nb <= n then "YES" else "NO"

import Data.List
import Data.Function
import Data.Char

main = interact $ getAns . map (map read . words) . lines

getAns :: [[Int]] -> String
getAns (ax:bx:(n:_):_)
	| s > n = "NO"
	| otherwise = "YES"
	where s = di 5 ax + di 10 bx
	      di a = ceiling . (/ a) . fromIntegral . sum

import Data.List
import Data.Function
import Data.Char

main = interact $ getAns . map read . words

getAns :: [Int] -> String
getAns (a1:a2:a3:b1:b2:b3:n:_)
	| s > n = "NO"
	| otherwise = "YES"
	where s = ceiling (fromIntegral (a1 + a2 + a3) / 5) + ceiling (fromIntegral (b1 + b2 + b3) / 10)

import Data.List
import Data.Function
import Data.Char

main = interact $ getAns . map read . words

getAns :: [Int] -> String
getAns (a1:a2:a3:b1:b2:b3:n:_)
	| s > n = "NO"
	| otherwise = "YES"
	where s = di 5 (a1 + a2 + a3) + di 10 (b1 + b2 + b3)
	      di a = ceiling . (/ a) . fromIntegral

import Data.List
import Data.Function
import Data.Char

main = interact $ getAns . map read . words

getAns :: [Int] -> String
getAns (a1:a2:a3:b1:b2:b3:n:_)
	| s > n = "NO"
	| otherwise = "YES"
	where ta = a1 + a2 + a3
	      tb = b1 + b2 + b3
	      sa = ta `div` 5 + if ta `mod` 5 == 0 then 0 else 1
	      sb = tb `div` 10 + if tb `mod` 10 == 0 then 0 else 1
	      s = sa + sb

main = do
  [a1, a2, a3] <- fmap (map read . words) getLine
  [b1, b2, b3] <- fmap (map read . words) getLine
  n <- readLn

  putStrLn $ if (a1+a2+a3 + 4) `div` 5 + (b1+b2+b3+9) `div` 10 > n then "NO" else "YES"

main = do
    aux1 <- getLine
    let cups = sum (map read $ words aux1 :: [Int])
    aux2 <- getLine
    let medals = sum (map read $ words aux2 :: [Int])
    aux3 <- getLine
    let shelfs = read aux3
    let neededForCups = if (mod cups 5 == 0) then (div cups 5) else ((div cups 5) + 1)
    let neededForMedals = if (mod medals 10 == 0) then (div medals 10) else ((div medals 10) + 1)
    let ans = if (neededForCups + neededForMedals <= shelfs) then "YES" else "NO"

    putStrLn ans

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
import Data.Maybe
import Control.Applicative
import qualified Data.ByteString.Char8 as BS

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

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

main = do
  as <- getints
  bs <- getints
  n  <- getint
  let sumA = sum as
      needA = sumA `div` 5 + (if sumA `mod` 5 == 0 then 0 else 1)
      sumB = sum bs
      needB = sumB `div` 10 + (if sumB `mod` 10 == 0 then 0 else 1)
  if needA + needB > n then putStrLn "NO" else putStrLn "YES"

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = solve =<< forM [1..3] (\i-> sum.map (fst.fromJust.C.readInt).C.words<$>C.getLine)
--solve::Int->IO()
solve [x,y,z] = let s = (+) (ceiling (fromIntegral x / 5)) (ceiling (fromIntegral y / 10)) in putStr $ if s>z then "NO" else "YES"

main = do
	as<-getLine
	bs<-getLine
	n<-getLine
	let [a1,a2,a3] =map read $ words as
	let [b1,b2,b3]= map read $ words bs
	putStrLn $ solve a1 a2 a3 b1 b2 b3 (read n)

solve 0 0 0 0 0 0 _ = "YES"
solve a1 a2 a3 b1 b2 b3 n = if div (a-1) 5 + div (b-1) 10 +2 <=n then "YES" else "NO"
	     where a=if a1+a2+a3 >0 then a1+a2+a3 else 1
	           b=if b1+b2+b3 >0 then b1+b2+b3 else 1

main = do
	as<-getLine
	bs<-getLine
	n<-getLine
	let [a1,a2,a3] =map read $ words as
	let [b1,b2,b3]= map read $ words bs
	putStrLn $ solve a1 a2 a3 b1 b2 b3 (read n)

solve a1 a2 a3 b1 b2 b3 n = if div (a-1) 5 + div (b-1) 10 +2 <=n then "YES" else "NO"
	     where a=if a1+a2+a3 >0 then a1+a2+a3 else 1
	           b=if b1+b2+b3 >0 then b1+b2+b3 else 1

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
import Data.Maybe
import Control.Applicative
import qualified Data.ByteString.Char8 as BS

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

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

main = do
  as <- getints
  bs <- getints
  n  <- getint
  let sumA = sum as
      needA = sumA `div` 5 + (if sumA `mod` 5 == 0 then 0 else 1)
      sumB = sum bs
      needB = sumB `div` 10 + (if sumA `mod` 10 == 0 then 0 else 1)
  if needA + needB > n then putStrLn "NO" else putStrLn "YES"

main :: IO ()
main = do
  sa <- getLine
  sb <- getLine
  sn <- getLine
  let suma = sum . map read $ words sa
      sumb = sum . map read $ words sb
      tot = ceiling ((/) suma 5) + ceiling ((/) sumb 10)
      n = read sn
      res = if tot <= n then "Yes" else "No"
  putStrLn res

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
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.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
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=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# 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
  x <- sum.map readInt.B.words <$> B.getLine
  y <- sum.map readInt.B.words <$> B.getLine
  n <- readLn
  putStrLn.bool"YES""NO" $ solve n x y

solve :: Int -> Int -> Int -> Bool
solve n x y = (x+4)`div`5 + (x+9)`div`10 <= n

import Control.Applicative

calc a = div (sum a) 5 +(if mod (sum a) 5>0 then 1 else 0)

main=do
	a<-map read.words <$> getLine::IO [Int]
	b<-map read.words <$> getLine::IO [Int]
	c<- read <$> getLine::IO Int
	putStrLn $ if c>= calc a + calc b then "YES" else "NO"

module Main where

main = do
	line1 <- getLine
	line2 <- getLine
	line3 <- getLine
	let a = readIntList line1
	let b = readIntList line2
	let n = read line3 :: Int

	putStr $ result a b n

result a b n = sayYesNo $ ((ceiling' a' 10.0) + (ceiling' b' 10.0)) <= n
	where
		sayYesNo bool = if bool then "YES" else "NO"
		ceiling' s alpha = ceiling (toRational s / alpha)
		a' = sum a
		b' = sum b

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


import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Array as Arr
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List
import Control.Applicative
import Control.Monad
import Data.Function

z c l = let l' = takeWhile (/= c) l in if any (/='.') l' then 100 else length l'

s cs = minimum (map (z 'W') cs) <= minimum (map (z 'B' . reverse) cs)

p True = "A\n"
p False = "B\n"

main = interact $ p . s . transpose . lines

import Control.Applicative
import Data.List

myfind x n [] = 100
myfind x n (s:ss) | s==x = n+1
                  | s=='.'= myfind x  (n+1) ss
                  | otherwise =100

main= do
	s<- transpose. lines <$> getContents::IO [String]
	let w= minimum $ map (myfind 'W' 0) s
	let b= minimum $ map (myfind 'B' 0) (map reverse s)
	putStrLn $ if w<=b then "A" else "B"

import Control.Monad

getMoves :: [Char] -> Char -> Int
getMoves [] _ = 8
getMoves column c
    | head column == c = 8 - length column
    | head column == '.' = getMoves (tail column) c
    | otherwise = 8

main = do
    rows <- forM [0..7] (\a -> getLine)

    let columns = [[row !! i | row <- rows] | i <- [0..7]]
        bestWhite = minimum [getMoves (columns !! i) 'W' | i <- [0..7]]
        bestBlack = minimum [getMoves (reverse (columns !! i)) 'B' | i <- [0..7]]

    if bestWhite <= bestBlack
        then putStrLn("A")
    else putStrLn("B")

import Control.Applicative
import Data.List

myfind x (s:ss) n = if elem x s then n else myfind x ss (n+1)

main= do
	s<- lines <$> getContents::IO [String]
	let w= (myfind 'W' s 1)-1
	let b= 8 - (myfind 'B' s 1)
	putStrLn $ if w<b then "A" else "B"

import Control.Applicative
import Data.List

myfind x (s:ss) n = if elem x s then n else myfind x ss (n+1)

main= do
	s<- lines <$> getContents::IO [String]
	let w= (myfind 'W' s 1)-1
	let b=   (myfind 'B' (reverse s) 1)-1
	putStrLn $ if w<b then "A" else "B"


main = do
    k <- getLine >>= return.read
    s <- getLine
    putStr $ solve k s

solve :: Int -> String -> String
solve k s = if k' < k then "NO" else "YES\r\n"
        ++(unlines
            $ (take (k-1) parts)++[concat $ drop (k-1) parts])
    where
        parts = so s []
        k' = length parts

so :: String -> [Char] -> [String]
so [] _ = []
so (x:xs) l = (x:cur):(so (drop (length cur) xs) l')
    where
    l' = x:l
    cur = takeWhile (`elem` l') xs

import Control.Applicative
import qualified Data.Set as Set

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

findBeautiful :: Set.Set Char -> Int -> String -> Maybe [String]
findBeautiful _ _ [] = Nothing
findBeautiful set 1 (x:xs) = Just ([x:xs])
findBeautiful set k (x:xs) = Just ((x:prefix):) <*> findBeautiful (Set.insert x set) (k-1) remainder
	where
		(prefix, remainder) = span (\item -> item == x || item `Set.member` set) xs

main = do
	lns <- getLines 2

	let
		k = read $ lns !! 0 :: Int
		q = lns !! 1
		result = findBeautiful Set.empty k q

	case result of
		Nothing -> putStrLn "NO"
		Just xs -> mapM_ putStrLn $ "YES":xs

import Data.List (intercalate)
answer::Int->String->[String]
answer k q = trimData q $ takeOrNot k $ getTrueNumber $ getNotPrev $ q
getNotPrev::String -> [Bool]
getNotPrev q = map (\x -> not (elem (fst x) (snd x))) $ zip q $ map (\k -> take k q) [0..((length q)-1)]
getTrueNumber::[Bool] -> [Int]
getTrueNumber b = map snd $ filter fst $ zip b [0..]
takeOrNot ::Int -> [Int]-> [Int]
takeOrNot k a | (length a) < k = []
              | otherwise = take k a
trimData::String -> [Int] -> [String]
trimData q n | null n = []
             | (length n) == 1 = [q]
             | otherwise = [a]++trimData b nt
               where nh0 = head n
                     nt = tail n
                     nh1 = head nt
                     (a,b) = splitAt (nh1-nh0) q

printAnswer::[String] -> IO ()
printAnswer a = do
  if (null a)
    then putStrLn "NO"
    else do
           putStrLn "YES"
           putStrLn $ intercalate "\n" a
main = do
  w <- getLine
  let k = read w::Int
  q <- getLine
  printAnswer $ answer k q
  --print $ getNotPrev q

import Control.Monad

main = do
    input <- getLine
    let n = read input
    s <- getLine
    let ans = f s ""
    mapM_ putStrLn (yesOrNo n ans)

f :: String -> String -> [String]
f [] _ = []
f (x:xs) used =
    let xused = (x:used)
    in (x : takeWhile (`elem` xused) xs) : (f (dropWhile (`elem` xused) xs) xused)

yesOrNo :: Int -> [String] -> [String]
yesOrNo _ [] = []
yesOrNo n xs =
    if n-1 < length xs then
        "YES" : listToPrint n xs
    else
        ["NO"]

listToPrint :: Int -> [String] -> [String]
listToPrint n xs = (take (n-1) xs) ++ [rmsp $ unwords $ drop (n-1) xs]

rmsp :: String -> String
rmsp [] = ""
rmsp (x:xs) =
    if x == ' ' then rmsp xs
    else x : rmsp xs

import Control.Applicative ((<$>))
import Control.Monad (replicateM, liftM, join, mapM_)

break' :: String -> [String] -> [String]
break' [] acc = acc
break' (h:rest) acc
    | any ((== h).last) acc = break' rest $ (h:head acc):tail acc
    | otherwise = break' rest $ [h]:acc

out :: [String] -> Int -> [String]
out tok k | length tok < k = ["NO"]
out tok k = "YES":init ++ [rest]
    where init = take (k - 1) tok
          rest = join $ drop (k - 1) tok

main = do
    let parse = reverse.(map reverse).(flip break' [])

    k <- read <$> getLine
    tok <- parse <$> getLine
    mapM_ putStrLn $ out tok k

import Data.List(nub, elemIndex, group)
import Data.Maybe(fromJust)

answer s n = n <= length (nub s)

splitNAux :: String -> Int -> String -> [String]
splitNAux s n [] = [s]
splitNAux s 0 _ = [""]
splitNAux s 1 _ = [s]
splitNAux s n (x:xs) = a : splitNAux b (n - 1) xs
    where pos = fromJust (elemIndex x s)
          (a, b) = splitAt pos s

splitN s n = splitNAux s n (tail lst)
             where lst = nub s

main = interact $ unlines . callAnswer . lines
       where callAnswer (ns:ss:_) =
                 let n = read ns
                 in
                 if answer ss n then
                     "YES":splitN ss n
                 else
                     ["NO"]

import Data.List

solve :: Int -> String -> Maybe [String]
solve n q = solveHelper [last q] n q
    where
    solveHelper :: [Char] -> Int -> String -> Maybe [String]
    solveHelper used n "" = Nothing
    solveHelper used 1 q = Just [q]
    solveHelper used n (q:qs)
        | q `elem` used = do
            (f:rest) <- solveHelper used n qs
            return ((q:f):rest)

        | otherwise = do
            rest <- solveHelper (q:used) (n-1) qs
            return ([q]:rest)

printAnswer :: Maybe [String] -> IO ()
printAnswer Nothing = putStrLn "NO"
printAnswer (Just xs) = do
    putStrLn "YES"
    putStrLn $ reverse $ intercalate "\n" xs

main = do
    n <- getLine
    q <- getLine
    printAnswer $ solve (read n :: Int) (reverse q)

import Control.Monad

-- doit s n seen current = a way to do it with n left (including current)
doit :: String -> Integer -> [Char] -> String -> Maybe [String]
doit [] 1 _ [] = Nothing
doit str 1 seen current = Just [current ++ str]
doit [] _ _ _ = Nothing
doit (c:cs) n seen current
  | c `elem` seen = doit cs n seen (current ++ [c])
  | otherwise = do
    tmp <- doit cs (n-1) (c:seen) [c]
    return (current:tmp)

main = do
  n <- readLn
  str <- getLine
  putStr $ case doit (tail str) n [head str] [head str] of
               Nothing -> "NO\n"
               Just ans -> unlines ("YES":ans)

import Control.Applicative
import Data.List

del x (y:ys) | x==y = ys
             | otherwise = y: (del x ys)

myprocess s _ 0 (x:xs) = reverse ((x++s): xs)
myprocess s s1 n x=  myprocess (dropWhile (\z-> notElem z s2) (tail s))  s2 (n-1) (((head s):(takeWhile (\z-> notElem z  s2) (tail s))):x)
		where s2 = del (head s ) s1

main= do
	n<- read <$> getLine ::IO Int
	s<-    getLine
	let s1 = map head $ group $ sort s
	putStrLn $ if length s1<n then "NO" else "YES"
	putStrLn $ intercalate "\n"  $ if length s1>=n then myprocess s s1 n [] else []

import Control.Applicative

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

findBeautiful :: Int -> String -> Maybe [String]
findBeautiful _ [] = Nothing
findBeautiful 1 (x:xs) = Just ([x:xs])
findBeautiful k (x:xs) = Just ((x:prefix):) <*> findBeautiful (k-1) remainder
	where (prefix, remainder) = span (== x) xs

main = do
	lns <- getLines 2

	let
		k = read $ lns !! 0 :: Int
		q = lns !! 1
		result = findBeautiful k q

	case result of
		Nothing -> putStrLn "NO"
		Just xs -> mapM_ putStrLn $ "YES":xs

import Data.List(nub, elemIndex, group)
import Data.Maybe(fromJust)

answer s n = n <= length (nub s)

splitNAux :: String -> Int -> String -> [String]
splitNAux s n [] = []
splitNAux s 0 _ = [s]
splitNAux s 1 _ = [s]
splitNAux s n (x:xs) = a : splitNAux b (n - 1) xs
    where pos = fromJust (elemIndex x s)
          (a, b) = splitAt pos s

splitN s n = splitNAux s n (tail lst)
             where lst = concatMap nub (group s)

main = interact $ unlines . callAnswer . lines
       where callAnswer (ns:ss:_) =
                 let n = read ns
                 in
                 if answer ss n then
                     "YES":splitN ss n
                 else
                     ["NO"]

import Data.List(nub, elemIndex)
import Data.Maybe(fromJust)

answer s n = n <= (length $ nub s)

splitNAux :: String -> Int -> String -> [String]
splitNAux s n [] = []
splitNAux s 0 _ = [s]
splitNAux s 1 _ = [s]
splitNAux s n (x:xs) = a : (splitNAux b (n - 1) xs)
    where pos = fromJust (elemIndex x s)
          (a, b) = splitAt pos s

splitN s n = splitNAux s n (tail $ nub s)

main = interact $ unlines . callAnswer . lines
       where callAnswer (ns:ss:_) =
                 let n = read ns
                 in
                 if answer ss n then
                     "YES":splitN ss n
                 else
                     ["NO"]

import Data.List

solve :: Int -> String -> Maybe [String]
solve = solveHelper []
    where
    solveHelper :: [Char] -> Int -> String -> Maybe [String]
    solveHelper used n "" = Nothing
    solveHelper used 1 q = Just [q]
    solveHelper used n (q:qs)
        | q `elem` used = do
            (f:rest) <- solveHelper used n qs
            Just ((q:f):rest)

        | otherwise = do
            rest <- solveHelper (q:used) (n-1) qs
            Just ([q]:rest)

printAnswer :: Maybe [String] -> IO ()
printAnswer Nothing = putStrLn "NO"
printAnswer (Just xs) = do
    putStrLn "YES"
    putStrLn $ reverse $ intercalate "\n" xs

main = do
    n <- getLine
    q <- getLine
    printAnswer $ solve (read n :: Int) (reverse q)

import Control.Applicative
import Data.List

del x (y:ys) | x==y = ys
             | otherwise = y: (del x ys)

myprocess s _ 0 (x:xs) = reverse ((x++s): xs)
myprocess s s1 n x=  myprocess (dropWhile (\z-> notElem z s2) (tail s))  s1 (n-1) (((head s):(takeWhile (\z-> notElem z  s2) (tail s))):x)
		where s2 = del (head s ) s1

main= do
	n<- read <$> getLine ::IO Int
	s<-    getLine
	let s1 = map head $ group $ sort s
	putStrLn $ if length s1<n then "NO" else "YES"
	putStrLn $ intercalate "\n"  $ if length s1>=n then myprocess s s1 n [] else []

import Control.Applicative
import Data.List

myprocess s _ 0 (x:xs) = reverse ((x++s): xs)
myprocess s s1 n x=  myprocess (dropWhile (\z-> notElem z s1) (tail s))  s1 (n-1) (((head s):(takeWhile (\z-> notElem z  s1) (tail s))):x)

main= do
	n<- read <$> getLine ::IO Int
	s<-    getLine
	let s1 = map head $ group $ sort s
	putStrLn $ if length s1<n then "NO" else "YES"
	putStrLn $ intercalate "\n"  $ if length s1>=n then myprocess s (take  n s1) n [] else []


import Data.Functor ((<$>))
import Data.List (inits, tails)
import Data.Maybe (fromMaybe, listToMaybe)

main :: IO ()
main = putStrLn =<< fromMaybe "NA" . solve <$> getLine

solve :: String -> Maybe String
solve xs = listToMaybe [ as ++ [b] ++ cs | (as, cs) <- zip (inits xs) (tails xs), b <- ['a'..'z'], isPalindrome $ as ++ [b] ++ cs ]

isPalindrome :: Eq a => [a] -> Bool
isPalindrome xs = xs == reverse xs

main = interact $ a . filter h . concat . f . lines
f [x] = map (g [] x) ['a'..'z']
g l [] c = [l ++ [c]]
g l s@(x:xs) c = (l ++ c:s):(g (l ++ [x]) xs c)
h s = s == (reverse s)
a [] = "NA"
a x = head x

import Data.Functor ((<$>))
import Data.List (inits, tails)
import Data.Maybe (fromMaybe, listToMaybe)

main :: IO ()
main = putStrLn =<< fromMaybe "NA" . solve <$> getLine

solve :: String -> Maybe String
solve xs = listToMaybe [ as ++ [b] ++ cs | (as, cs) <- zip (inits xs) (tails xs), b <- ['a'..'z'], isPalindrome $ as ++ [b] ++ cs ]

isPalindrome :: Eq a => [a] -> Bool
isPalindrome xs = all (uncurry (==)) $ zip xs (reverse xs)

main = do
  str <- getLine
  case mkPalindrome str of
    Just str' -> putStrLn str'
    Nothing -> putStrLn "NA"

mkPalindrome :: String -> Maybe String
mkPalindrome str = if isPalindrome s1
                   then Just s1
                   else if isPalindrome s2
                        then Just s2
                        else Nothing
  where
    len = length str
    front = take (len `div` 2) str
    back  = drop (len `div` 2) str
    ((s1f, s1b), (s2f, s2b)) = insertCharIfNec front (reverse back)
    s1 = s1f ++ reverse s1b
    s2 = s2f ++ reverse s2b

insertCharIfNec :: String -> String -> ((String, String), (String, String))
insertCharIfNec (a:as) (b:bs)
    | a == b = let ((s1f, s1b), (s2f, s2b)) = insertCharIfNec as bs
               in ((a:s1f, b:s1b), (a:s2f, b:s2b))
    | otherwise = ((b:a:as, b:bs),
                   (a:as, a:b:bs))
insertCharIfNec "" "" = (("", "y"), ("", "y"))
insertCharIfNec "" s = ((s, s), (s, s))

isPalindrome :: String -> Bool
isPalindrome str = go front back
  where
    len = length str
    front = take (len `div` 2) str
    back  = take (len `div` 2) (reverse str)
    go (a:as) (b:bs) | a == b = go as bs
                     | otherwise = False
    go [] [] = True

main = getLine >>= putStrLn . solve
solve [] = "a"
solve [x] = [x, x]
solve (x:xs) | (x == last xs) && (st /= "NA")  = x : st ++ [last xs]
             | (x == last xs) && (st == "NA") = "NA"
             | isPalindrome v1 = v1
             | isPalindrome v2 = v2
             | otherwise = "NA"
    where st = solve $ init xs
          v1 = x:xs++[x]
          v2 = last xs : x : xs
          isPalindrome s = s == reverse s

import Control.Applicative
import System.IO

inserts :: a -> [a] -> [[a]]
inserts x []       = [[x]]
inserts x l@(y:ys) = (x:l) : ((fmap (y:)) $ inserts x ys)

isPalin :: Eq a => [a] -> Bool
isPalin s = reverse s == s

main :: IO()
main = do
  s <- getLine
  case filter isPalin $ concat $ fmap ($ s) $ fmap inserts ['a'..'z'] of
    [] -> putStrLn "NA"
    (x:xs) -> putStrLn x

#!/usr/bin/env runghc
import Data.Maybe
main = getContents >>= mapM_ putStrLn . solve . lines
solve = map f
f::String->String
f s
  | null a = "NA"
  | otherwise = fromJust . head $ a
  where
  a = dropWhile isNothing . map g $ [0..n]
  n = length s
  g::Int->Maybe String
  g i
    | n-i>i  = p $ t ++ ((s!!(n-i-1)) : d)
    | n-i<i  = p $ t ++ ((s!!(n-i)) : d)
    | otherwise = p $ t ++ ('a' : d)
    where (t,d) = splitAt i s
p::String->Maybe String
p s = if s==reverse s then Just s else Nothing

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

main = interact $ sol . head . lines

isPar s = reverse s == s

getNS s p c = p1 ++ [c] ++ p2
	where (p1, p2) = splitAt p s

sol x =	maybe "NA" id $ find isPar [getNS x p c | p <- [0 .. length x], c <- ['a' .. 'z']]

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  s <- getLine

  let
    check s = and $ zipWith (==) s (reverse s)
    ss = [s | i <- [0..length s], let (s1, s2) = splitAt i s, c <- ['a'..'z'], let s = s1 ++ [c] ++ s2, check s]

  putStrLn $ if null ss then "NA" else head ss

import Control.Applicative

main = getLine >>= putStrLn . solve

solve :: String -> String
solve s = head . (++ ["NA"]) . filter ((==) <*> reverse) $ rs
    where rs = [take i s ++ [c] ++ drop i s | i <- [0..length s], c <- ['a'..'z']]

import Control.Monad
import Control.Applicative
import Data.Monoid
import qualified Data.Map as M
import qualified Data.IntMap as I

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

toOutput :: Maybe String -> String
toOutput = maybe "NA" id

solve :: String -> Maybe String
solve s = getFirst $ mconcat $ map (toPal s) [0..length s]

toPal :: String -> Int -> First String
toPal s i = First ans
          where
            ans = if isPal newString
                  then (Just newString)
                  else Nothing
            newString = take i s ++ [c'] ++ drop i s
            c' = if i == length newString `div` 2
                 then 'a'
                 else newString !! (length newString - 1-i)

isPal s = s == reverse s

main = interact $ a . filter h . concat . f . concat . lines
f x = map (g [] x) ['a'..'z']
g l [] c = [l ++ [c]]
g l s@(x:xs) c = (l ++ c:s):(g (l ++ [x]) xs c)
h s = s == (reverse s)
a [] = "NA"
a x = head x

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  s <- getLine

  let
    check s = and $ zipWith (==) s (reverse s)
    ss = [s | i <- [0..length s], let (s1, s2) = splitAt i s, c <- ['a'..'z'], let s = s1 ++ [c] ++ s2, check s]

  print ss
  putStrLn $ if null ss then "NA" else head ss

main = interact $ a . filter h . concat . f
f x = map (g [] x) ['a'..'z']
g l [] c = [l ++ [c]]
g l s@(x:xs) c = (l ++ c:s):(g (l ++ [x]) xs c)
h s = s == (reverse s)
a [] = "NA"
a x = head x


module Main where
import Data.List
import Control.Applicative

f (u,d,l,r) [] = u==d && l==r
f (u,d,l,r) (a:as)
    | a == 'U' = f (u+1, d, l, r) as
    | a == 'D' = f (u, d+1, l, r) as
    | a == 'L' = f (u, d, l+1, r) as
    | a == 'R' = f (u, d, l, r+1) as

main = do
    getLine
    print =<< length . filter (f (0,0,0,0)) .  concat . map (init. tails )  . tail . inits <$> getLine

module Main where

import Data.List

move :: (Int, Int) -> Char -> (Int, Int)
move (x, y) 'U' = (x, y - 1)
move (x, y) 'D' = (x, y + 1)
move (x, y) 'L' = (x - 1, y)
move (x, y) 'R' = (x + 1, y)

identity :: [Char] -> Bool
identity moves = (foldl move (0, 0) moves) == (0, 0)

solve :: String -> Int
solve moves = length . filter id $ [identity ps | s <- ss, ps <- tail (inits s)]
    where ss = init $ tails moves

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

import Data.List
import Data.List.Split

solve s = length [(i, j) | i <- [0..(n-1)], j <- [i..(n-1)], f i j]
    where n = length s
          val 'U' = (1, 0)
          val 'D' = (-1, 0)
          val 'L' = (0, 1)
          val 'R' = (0, -1)
          tsum (a, b) (c, d) = (a+c, b+d)
          subsum i j = foldl tsum (0, 0) $ map val $ take (j-i+1) $ drop i s
          f i j = (subsum i j) == (0, 0)

main = do
    str1 <- getLine
    str2 <- getLine
    putStrLn $ show $ solve str2

import Data.Char

allSubstrings :: String -> [String]
allSubstrings s = concat $ map allPrefixes $ allSuffixes s

allSuffixes :: String -> [String]
allSuffixes [] = []
allSuffixes s = let x : xs = s in s : allSuffixes xs

allPrefixes :: String -> [String]
allPrefixes s = map reverse $ allSuffixes $ reverse $ s

concat' :: [[a]] -> [a]
concat' [] = []
concat' (x:xs) = x ++ (concat' xs)

charShift :: Char -> (Int,Int)
charShift 'U' = (1, 0)
charShift 'R' = (0, 1)
charShift 'D' = (-1, 0)
charShift 'L' = (0, -1)

strShift :: String -> (Int,Int)
strShift [] = (0,0)
strShift (x:xs) =
    let (x1,y1) = charShift x
        (x2,y2) = strShift xs
    in (x1 + x2, y1 + y2)

count :: String -> Int
count s = foldl (\answer subStr -> answer + (if strShift subStr == (0,0) then 1 else 0)) 0 $ allSubstrings s

main = do
    contents <- getContents
    let contentsWords = words contents
    let [_,source] = contentsWords
    print $ count source

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections       #-}

module Main where
import qualified Data.Map    as Map
import           Data.Monoid

move ::Num a=>Char -> (a, a)
move 'D' = ( 0,-1)
move 'U' = ( 0, 1)
move 'L' = (-1, 0)
move 'R' = ( 1, 0)
move _   = ( 0, 0)

solution::forall a.Integral a=>String->a
solution = combine where
  psum (a,b)           = (Sum a, Sum b)
  unsum (Sum a, Sum b) = (a, b)
  start = psum ((0, 0)::(a,a))
  points = map ((,1) .unsum) . scanl (<>) start . map (psum . move)
  comb2 a = a * (a - 1) `div` 2::a
  combine = sum . map comb2 . Map.elems . Map.fromListWith (+) . points

main:: IO ()
main = getLine >> getLine >>= print . (solution::String->Integer)

import Prelude
import Control.Monad
import Data.List
import qualified Data.Map as M
import qualified Data.Array as A
import Data.Functor

update :: (Int,Int) -> Char -> (Int,Int)
update (a,b) c
  | c == 'U' = (a+1,b)
  | c == 'D' = (a-1,b)
  | c == 'L' = (a,b-1)
  | c == 'R' = (a,b+1)

main :: IO ()
main = do
  n <- readLn :: IO Int
  str <- getLine
  let things = scanl update (0,0) str
      m_things = M.fromListWith (+) [(t,1) | t <- things]
      m_oper = M.map (\n -> div (n*(n-1)) 2) m_things
      ans = M.fold (+) 0 m_oper :: Int
  print ans
  return ()

import Data.List (group, sort)

main :: IO ()
main = print . solve . parse . lines =<< getContents

type Input = String

parse :: [String] -> Input
parse [_, s] = s
parse _ = undefined

delta :: Char -> (Int, Int)
delta 'U' = (0, 1)
delta 'R' = (1, 0)
delta 'D' = (0, -1)
delta 'L' = (-1, 0)
delta _ = undefined

solve :: Input -> Int
solve = sum . map count . group . sort . scanl step (0, 0)
    where step (x, y) c = let (x', y') = delta c in (x + x', y + y')
          count a = let n = length a in n * (n - 1) `div` 2


import Data.Maybe
import Data.Int
import Data.Foldable
import qualified Data.ByteString.Char8 as C
import Data.Array.Base
import Data.Array.IO

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

kMod :: Int
kMod = 998244353

toInt64 :: Int -> Int64
toInt64 = fromIntegral

fromInt64 :: Int64 -> Int
fromInt64 = fromIntegral

newtype Mint = Mint { mint :: Int }
  deriving (Eq, Ord)
instance Num Mint where
  (Mint a) + (Mint b) = Mint (let c = a + b in if c >= kMod then c - kMod else c)
  (Mint a) - (Mint b) = Mint a + Mint (kMod - b)
  (Mint a) * (Mint b) = Mint $ fromInt64 $ (toInt64 a * toInt64 b) `mod` (toInt64 kMod)
  fromInteger n = Mint (fromIntegral $ n `mod` fromIntegral kMod)
instance Show Mint where show = show . mint

main :: IO ()
main = do
  n <- fmap parseInt C.getLine
  prime <- newArray_ (0, n) :: IO (IOUArray Int Int)
  tau <- newArray_ (0, n) :: IO (IOUArray Int Int)
  unsafeWrite tau 1 1
  forM_ [2..n] $ \i -> do
    p <- unsafeRead prime i
    if p /= 0
      then do
        t1 <- unsafeRead tau p
        let f y = if y `mod` p == 0 then let (a, b) = f (y `div` p) in (a, b + 1) else (y, 0)
            (x, c) = f i
        t2 <- unsafeRead tau x
        unsafeWrite tau i ((c + 1) * t2)
        return ()
      else do
        unsafeWrite tau i 2
        forM_ [2 * i, 3 * i .. n] $ \j -> do
          unsafeWrite prime j i
  let func :: Int -> IO (Mint, Mint)
      func 1 = return (1, 0)
      func x = do
        (f', t') <- func (x - 1)
        t <- fmap (Mint . (subtract 1)) $ unsafeRead tau x
        return $ (2 * f' - t' + t, t)
  result <- fmap fst $ func n
  putStrLn $ show result

-- dp(n) = 2^(n- 1) + D(n) + D(n - 1)  + 2 * D(D - 2)  + 4 * D(n - 3) + 8 * D(n - 4) + ... + 2^(n-2)D(1) - 2^(n-1)

-- dp(3) = 2 + 2 + 2 * 1
-- dp(2) = 2 + 1
-- dp(1) =
--
--
import Data.Int (Int64)
import qualified Data.Array as A

main = do
    n <- read <$> getLine
    print $ solve n

m = 998244353
solve :: Int -> Int
solve n = foldl1 (\x y -> let t = x + y in if t < m then t else t - m) (map calc [1..n])
     where calc k = mul (if x >= 0 then x else x + m) (minv (mpow A.! k - 1) m) + d
             where d = if n `rem` k == 0 then 1 else 0
                   x = mpow A.! (n - 1) -  mpow A.! ((n - 1) `rem` k)

mpow = A.listArray (0,1000000) l
    where l = 1:map (\x -> let t = 2 * x in if t < m then t else t - m) l

minv :: Int -> Int -> Int
minv 1 _ = 1
minv a b = b + fromIntegral (quot (1 - t * fromIntegral  b) (fromIntegral a))
         where t = fromIntegral (minv (b `rem` a) a) :: Int64

mul :: Int -> Int -> Int
mul a b = fromIntegral (x * y `rem` fromIntegral m)
        where x = fromIntegral a :: Int64
              y = fromIntegral b :: Int64

{-# LANGUAGE FlexibleContexts #-}
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.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Tuple
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)

md :: Int64
md = 998244353

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)

solve :: Int -> MInt
solve n =
    let ds = [t | i <- [1..n], t <- [i,i+i..n]]
        da = accumArray (\t _ -> t + 1) 0 (1,n) (zip ds (repeat ())) :: UArray Int Int
        d = map fromIntegral $ elems da
    in
        fst $ foldl' (\(_, s) t -> (s + t, s + s + t)) (0,0) d

main = do
    n <- parseInt <$> BS.getLine
    print $ solve n

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

import Data.Array.Unboxed

p :: Int
p = 998244353

data LoopVal = LoopVal !Int !Int

step :: LoopVal -> Int -> LoopVal
step (LoopVal _ai psum) currFactors = let
  nai = rem (currFactors - 1 + psum) p
  npsum = rem (nai + psum) p
  in  LoopVal nai npsum

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n] <- readInts
  let
    factors :: UArray Int Int
    factors = accumArray (\ct _ -> ct + 1) 0 (1, n)
      $ [(j, ()) | i <- [1 .. n], j <- [i, 2*i .. n]]
    LoopVal ans _ = foldl' step (LoopVal 1 1) $ elems factors
  --putInts $ elems factors
  putInts [ans]

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder