There are three points marked on the coordinate plane. The goal is to make a simple polyline, without self-intersections and self-touches, such that it passes through all these points. Also, the polyline must consist of only segments parallel to the coordinate axes. You are to find the minimum number of segments this polyline may consist of.

Each of the three lines of the input contains two integers. The i-th line contains integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the i-th point. It is guaranteed that all points are distinct.

NoteThe variant of the polyline in the first sample:  The variant of the polyline in the second sample:  The variant of the polyline in the third sample:

solve :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Int
solve (x1, y1) (x2, y2) (x3, y3)
    | (x1 == x2 && x1 == x3) = 1
    | (y1 == y2 && y1 == y3) = 1
    | (x1 == x2 && (y3 <= (min y1 y2) || y3 >= (max y1 y2))) = 2
    | (y1 == y2 && (x3 <= (min x1 x2) || x3 >= (max x1 x2))) = 2
    | otherwise = 3

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

getPoint :: IO (Int, Int)
getPoint = do
    line <- getLine
    return (point (map read (words line)))

main = do
    a <- getPoint
    b <- getPoint
    c <- getPoint
    putStrLn (show (minimum [(solve a b c), (solve a c b), (solve b a c), (solve b c a), (solve c a b), (solve c b a)]))

-- There are three points marked on the coordinate plane. The goal is to make
-- a simple polyline, without self-intersections and self-touches, such that it
-- passes through all these points. Also, the polyline must consist of only
-- segments parallel to the coordinate axes. You are to find the minimum number
-- of segments this polyline may consist of.
--
-- Input
-- Each of the three lines of the input contains two integers. The i-th line
-- contains integers xi and yi ( - 109 ≤ xi, yi ≤ 109) — the coordinates of the
-- i-th point. It is guaranteed that all points are distinct.
--
-- Output
-- Print a single number — the minimum possible number of segments of the polyline.
--
-- Found at: http://codeforces.com/contest/617/problem/D
--

module Main where
import Data.List(permutations)

type Coords = (Int,Int)
type Direction = (Int,Int)

direction :: Coords -> Coords -> Direction
direction (x1,y1) (x2,y2) = (signum $ x2 - x1, signum $ y2 - y1)

directions :: [Coords] -> [Direction]
directions pts = zipWith direction pts (tail pts)

diagonal :: Direction -> Bool
diagonal (dx,dy) = (abs dx + abs dy) == 2

opposite :: Direction -> Direction -> Bool
opposite (dx1,dy1) (dx2,dy2) = (dx1,dy1) == (-dx2,-dy2)

segs :: [Coords] -> Int
segs pts = sum $ zipWith segsForMove dirs (tail dirs)
  where dirs = (0,0) : directions pts -- (0,0) for 'how to get to first point'

segsForMove :: Direction -> Direction -> Int
segsForMove d1 d2@(dx2,dy2)
  | d1 == (0,0)       = abs dx2 + abs dy2
  | continuable d1 d2 = if diagonal d2 then 1 else 0
  | diagonal d2       = 2
  | opposite d1 d2    = 3
  | otherwise         = 1

continuable :: Direction -> Direction -> Bool
continuable (dx1,dy1) (dx2,dy2)
  | dx1 /= 0 && dx1 == dx2    = True
  | dy1 /= 0 && dy1 == dy2    = True
  | otherwise                 = False

main :: IO ()
main = do
  line1 <- getLine
  line2 <- getLine
  line3 <- getLine
  let [x1,y1] = map read $ words line1 :: [Int]
      [x2,y2] = map read $ words line2 :: [Int]
      [x3,y3] = map read $ words line3 :: [Int]
  let perms = permutations [(x1,y1),(x2,y2),(x3,y3)]
  let best = minimum $ map segs perms
  putStrLn $ show best

solve :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Int
solve (x1, y1) (x2, y2) (x3, y3)
    | (x1 == x2 && x1 == x3) = 1
    | (y1 == y2 && y1 == y3) = 1
    | (x1 == x2 && (y3 <= (min y1 y2) || y3 >= (max y1 y2))) = 2
    | (y1 == y2 && (x3 <= (min x1 x2) || x3 >= (max x1 x2))) = 2
    | otherwise = 3

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

getPoint :: IO (Int, Int)
getPoint = do
    line <- getLine
    return (point (map read (words line)))

main = do
    a <- getPoint
    b <- getPoint
    c <- getPoint
    putStrLn (show (minimum [(solve a b c), (solve b a c), (solve c a b)]))

solve :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Int
solve (x1, y1) (x2, y2) (x3, y3)
    | (x1 == x2 && x1 == x3) = 1
    | (y1 == y2 && y1 == y3) = 1
    | (x1 == x2 && y1 == y3 && (y3 <= (min y1 y2) || y3 >= (max y1 y2))) = 2
    | (y1 == y2 && x1 == x3 && (x3 <= (min x1 x2) || x3 >= (max x1 x2))) = 2
    | otherwise = 3

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

getPoint :: IO (Int, Int)
getPoint = do
    line <- getLine
    return (point (map read (words line)))

main = do
    a <- getPoint
    b <- getPoint
    c <- getPoint
    putStrLn (show (minimum [(solve a b c), (solve b a c), (solve c a b)]))

solve :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Int
solve (x1, y1) (x2, y2) (x3, y3)
    | (x1 == x2 && x1 == x3) = 1
    | (x1 == x2 && y1 == y3 && (y3 <= (min y1 y2) || y3 >= (max y1 y2))) = 2
    | (y1 == y2 && x1 == x3 && (x3 <= (min x1 x2) || x3 >= (max x1 x2))) = 2
    | otherwise = 3

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

getPoint :: IO (Int, Int)
getPoint = do
    line <- getLine
    return (point (map read (words line)))

main = do
    a <- getPoint
    b <- getPoint
    c <- getPoint
    putStrLn (show (minimum [(solve a b c), (solve b a c), (solve c a b)]))


Alice got many presents these days. So she decided to pack them into boxes and send them to her friends.There are $$$n$$$ kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different kinds are distinguishable). The number of presents of each kind, that Alice has is very big, so we can consider Alice has an infinite number of gifts of each kind.Also, there are $$$m$$$ boxes. All of them are for different people, so they are pairwise distinct (consider that the names of $$$m$$$ friends are written on the boxes). For example, putting the first kind of present into the first box but not into the second box, is different from putting the first kind of present into the second box but not into the first box.Alice wants to pack presents with the following rules:  She won't pack more than one present of each kind into the same box, so each box should contain presents of different kinds (i.e. each box contains a subset of $$$n$$$ kinds, empty boxes are allowed);  For each kind at least one present should be packed into some box. Now Alice wants to know how many different ways to pack the presents exists. Please, help her and calculate this number. Since the answer can be huge, output it by modulo $$$10^9+7$$$.See examples and their notes for clarification.

The first line contains two integers $$$n$$$ and $$$m$$$, separated by spaces ($$$1 \leq n,m \leq 10^9$$$) — the number of kinds of presents and the number of boxes that Alice has.

Print one integer  — the number of ways to pack the presents with Alice's rules, calculated by modulo $$$10^9+7$$$

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

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

#define MOD 1000000007

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

solve :: Integer -> Integer -> Integer
solve n m = powMod (powMod 2 m MOD - 1) n MOD

powMod :: (Integral a, Integral b, Bits b) => a -> b -> a -> a
powMod x n m
    | n > 0 = go 1 x n
    | n == 0 = 1
    | otherwise = undefined
  where
    go !acc !y !i
        | i .&. 1 == 0 = go acc (y * y `rem` m) (unsafeShiftR i 1)
        | i == 1 = acc * y `rem` m
        | otherwise = go (acc * y `rem` m) (y * y `rem` m) (unsafeShiftR (i - 1) 1)
{-# INLINE powMod #-}


Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.  Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

NoteThe first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

main =
    do
        year <- getLine
        putStrLn.show.solve$read year

solve :: Integer -> Integer
solve 0 = 1
solve y =
    let
        year = y - 1
        m = 1000000007
        a = myPow2 2 year m
    in
        (2*((a*a) `mod` m) + a) `mod` m

myPow2 :: (Integral a) => a -> a -> a -> a
myPow2 _ 0 _ = 1
myPow2 b e m
    | e < 10^6  = (b^e) `mod` m
    | otherwise =
        let
            ex = if even e then 1 else b
            half = e `div` 2
            part = (myPow2 b half m) `mod` m
        in
            (ex * part^2) `mod` m

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

_mod :: Integer
_mod = (10^9+7)

pow _ 0 = 1
pow a n
 | odd n = (tmp * a) `mod` _mod
 | otherwise = tmp
 where
 	tmp1 = pow a (n `div` 2)
	tmp = (tmp1 * tmp1) `mod` _mod

main :: IO ()
main = do
	getLine >>= print . (\x -> x `mod` _mod). (\x -> x*(x+1) `div` 2). (pow 2). (\x -> read x )

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

_mod :: Integer
_mod = (10^9+7)

pow _ 0 = 1
pow a n
 | odd n = (tmp * a) `mod` _mod
 | otherwise = tmp
 where
 	tmp1 = pow a (n `div` 2)
	tmp = (tmp1 * tmp1) `mod` _mod

main :: IO ()
main = do
	getLine >>= print . (`mod` _mod). (\x -> x*(x+1) `div` 2). (pow 2). (\x -> read x )

import Data.Bits

main = print . solver . read =<< getLine

solver :: Integer -> Integer
solver n = p
   where
      md = 10^9 + 7
      one = [1,0,0,1]
      a' = [3,1,1,3] : map (\x -> x `mmul` x) a'
      b' = [ if testBit n i then a' !! i else one | i <- [0..63] ]
      (p:_) = foldl mmul one b'
      mmul [x,y,z,w] [a,b,c,d] = map (`mod`md) [x*a + y*c, x*b + y*d, z*a + w*c, z*b + w*d]

-- vim: set expandtab:

num str = (read str) :: Integer
m = 1000000007
exp' :: Integer -> Integer -> Integer
exp' _ 0 = 1
exp' a 1 = a
exp' a n = if mod n 2 == 0 then t * t `mod` m else t * t * a `mod` m
        where t = exp' a (n `div` 2)
solve n = if n == 0 then 1 else (exp' 2 (n-1) + 2 * exp' 4 (n-1)) `mod` m
main = do
        str <- getLine
        putStrLn (show (solve (num str)))

solve :: Integer -> Integer
solve 0  =  1
solve n  =  mod (pow 2 (2*n - 1) + pow 2 (n - 1)) m
  where
    m  =  10^9 + 7
    pow :: Integer -> Integer -> Integer
    pow p 0  =  1
    pow p n
      | mod n 2 == 0  =  p''^2
      | otherwise  =  p' * p''^2
      where
        p'   =  mod p m
        p''  =  mod (pow p' (div n 2)) m

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

main = do
  n <- readLn :: IO Integer
  if n==0
   then print 1
   else print $ (`rem`1000000007) $ pow 2 (n-1) + 2 * pow 4 (n-1)

pow :: Integer -> Integer -> Integer
pow x' n'
  | n' == 0   = 1
  | otherwise = f x' n'
    where f x n
             | even n    = f (x.*.x) (n`quot`2)
             | n == 1    = x
             | otherwise = g (x.*.x) ((n-1)`quot`2) x
          g x n y
             | even n    = g (x.*.x) (n`quot`2) y
             | n == 1    = x.*.y
             | otherwise = g (x.*.x) ((n-1)`quot`2) (x.*.y)

x.*.y=(x*y)`rem`1000000007

import Data.List
matrix = [
  [3, 1]
 ,[1, 3]
 ]

mult m1 m2 = md $ map (\l -> foldr (zipWith (+)) (repeat 0) $ zipWith (\i -> map (*i)) l m2) m1 {- where
 m2t = transpose m2 -}

md = map (map (\x -> x `mod` 1000000007))

pow m 0 = [[1,0],[0,1]]
pow m 1 = m
pow m n = mult m' (mult m2 m2) where
  m2 = pow m (n `div` 2)
  m' = pow m (n `mod` 2)

main = interact $ show . head . head . pow matrix . read

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

_mod :: Integer
_mod = (10^9+7)

pow _ 0 = 1
pow a n
 | odd n = (tmp * a) `mod` _mod
 | otherwise = tmp
 where
 	tmp1 = pow a (n `div` 2)
	tmp = (tmp1 * tmp1) `mod` _mod

main :: IO ()
main = do
	getLine >>= print .(\x -> x*(x+1) `div` 2). (pow 2). (\x -> read x )

import Data.Bits

main = print . solver . read =<< getLine

solver :: Integer -> Integer
solver n = p
   where
      md = 10^9 + 7
      one = [1,0,0,1]
      a' = [3,1,1,3] : map (\x -> x `mmul` x) a'
      b' = [ if testBit n i then a' !! i else one | i <- [0..31] ]
      (p:_) = foldl mmul one b'
      mmul [x,y,z,w] [a,b,c,d] = map (`mod`md) [x*a + y*c, x*b + y*d, z*a + w*c, z*b + w*d]

-- vim: set expandtab:


Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of money she will have to spend to make n rides?

The single line contains four space-separated integers n, m, a, b (1 ≤ n, m, a, b ≤ 1000) — the number of rides Ann has planned, the number of rides covered by the m ride ticket, the price of a one ride ticket and the price of an m ride ticket.

Print a single integer — the minimum sum in rubles that Ann will need to spend.

NoteIn the first sample one of the optimal solutions is: each time buy a one ride ticket. There are other optimal solutions. For example, buy three m ride tickets.

{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

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

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

main = do
	[ n, m, a, b ] <- getInts
	print $ minimum $ [ i * a + j * b | i <- [ 0 .. n ], j <- return $ ( n - i + m - 1 ) `div` m ]

module Main (main)
    where

main :: IO ()
main = print . solve . take 4 . map read . words =<< getLine
    where solve [n,m,a,b]
            | a*m <= b  = a*n
            | otherwise = let (q,r) = divMod n m in b*q + min (a*r) b

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

solve :: [Int] -> Int
solve (n:m:a:b:_) = solve' 0
    where solve' :: Int -> Int
          solve' i | i * m >= n = i * b
                   | otherwise  = min (i * b + (n - i * m) * a) (solve' (i + 1))

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = do
  [n, m, a, b] <- getInts
  let p = a * n
      q = b * (n `div` m) + a * (n `mod` m)
      r = b * ((n + m - 1) `div` m)
  print $ minimum [p, q, r]

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

import Data.List

solve :: Integer -> Integer -> Integer -> Integer -> Integer
solve n m a b = if (a * m < b) then a * n else ((n `div` m) * b + (min b ((n `mod` m) * a)))

main = do
    input <- getLine
    let arr = map (\s -> read s :: Integer) $ words input
    print $ solve (arr !! 0) (arr !! 1) (arr !! 2) (arr !! 3)

import Numeric

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

main = interact $ show.f.map fastRead .words

f (n:m:a:b:[])
  | m*a <= b = n*a
  | otherwise = i + min b ((n `mod` m)*a)
  where i = (n `div` m)*b

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

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

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

getAns :: [Int] -> Int
getAns (n:m:a:b:[]) = if a * m <= b then n * a
						else let d = n `div` m;
						 		 r = n `mod` m;
							 in d * b + if r == 0 then 0 else min b (r * a)

main = do
  [n, m, a, b] <- fmap (map read . words) getLine

  print $
    if m*a < b
       then n*a
       else b*(n`div`m) + min (a * (n`mod`m)) b

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show.solve.map read. words.head.lines
solve :: [Int]->Int
solve [a, b, c, d] | b*c <=d              = a*c
                   | a `mod` b==0 = (a `div` b) * d
                   | c>=d && a<=b         = d
                   | c>=d                 = ((a `div` b)+1) * d
                   | c< d && a<=b         = minimum [d, a*c]
                   | otherwise = (a `div` b) * d +(a `mod` b) * c

type Vec4 = (Integer, Integer, Integer, Integer)

split :: Eq a => a -> [a] -> [[a]]
split _    [] = []
split cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs

process :: Vec4 -> Integer
process (0, _, _, _) = 0
process (n, m, a, b) =
  let sep =
          [ a * x + b * y | x <- [0 .. 1000], y <- [0 .. 1000], x + m * y >= n ]
  in  if sep == [] then 1 else minimum sep

main :: IO ()
main = do
  input <- getLine
  let xs = map (read :: String -> Integer) (split ' ' input)
  let k  = (xs !! 0, xs !! 1, xs !! 2, xs !! 3)
  print $ process k

main = interact $ show . f . map read . words
f (a:b:c:d:e) = min (c*a) (min (d*(div a b+1)) (c*mod a b+d*div a b))

import Control.Applicative
main :: IO()
main = do
  [n,m,a,b] <- map read.words <$> getLine::IO [Int]
  if m*a <= b then print (n*a) else print$min (n `div` m * b + (n `mod` m) * a) ((n `div` m + 1)*b)

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

solve :: Int -> Int -> Int -> Int -> Int
solve n m a b = minimum [n * a, (n + m - 1) `div` m * b,
                         n `div` m * b + n `mod` m * a]

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

import Control.Applicative

process n m a b = minimum [b*((div n m )+1), b*(div n m)+a*(mod n m), a*n]

main=do
     [n,m,a,b]<-  map read <$> words <$> getLine::IO [Int]
     print $ process n m a b

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

solve :: [Int] -> Int
solve [n, m, a, b] = minimum [ n * a, b * (n `div` m) + a * (n `mod` m), b * (n `div` m + 1) ]

main = getLine >>= return . f . map read . words >>= print
f [n, m, a, b] = minimum
    [ n `div` m * b + n `mod` m * a
    , n * a
    , (n `div` m + 1) * b
    ]

import Control.Applicative

main= do
	[n,m,a,b] <- map read. words <$> getLine::IO [Int]
	print $ if (fromIntegral b )/ (fromIntegral m) >= fromIntegral a then n*a else min ((div n m)*b + (mod n m)*a ) (((div n m )+1)*b)

import Data.List

answer :: [Integer] -> Integer
answer [n, m, a, b] | fromIntegral b / fromIntegral m >  fromIntegral a = a * n
                    | need * a < b = buy * b + need * a
                    | otherwise = (buy + 1) * b
                     where (buy, need) =  n `divMod` m

someFunc :: IO ()
someFunc = getLine >>= print . answer . fmap read . words

main :: IO ()
main = someFunc

process :: Int -> Int -> Int -> Int -> Int
process n m a b
    | m*a <= b = n*a
    | r*a <= b = q*b + r*a
    | otherwise = q*b + b
    where
        (q,r) = n `divMod` m

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,m,a,b] <- fmap (map readInt.words) getLine
    print $ process n m a b

{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

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

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

main = do
	[ n, m, a, b ] <- getInts
	print $ minimum $ [ i * a + b * j | i <- [ 0 .. n ], ( n - i ) `mod` m == 0, j <- return $ ( n - i ) `div` m ]

module Main (main)
    where

main :: IO ()
main = print . solve . take 4 . map read . words =<< getLine
    where solve [n,m,a,b]
            | a*m <= b  = a*n
            | otherwise = let (q,r) = divMod n m in b*q + a*r

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = do
  [n, m, a, b] <- getInts
  let p = a * n
      q = b * (n `div` m) + a * (n `mod` m)
  print $ min p q

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

import Data.List

solve :: Integer -> Integer -> Integer -> Integer -> Integer
solve n m a b = if (a * m < b) then a * n else (mt * b + (n - mt * m) * a)
    where mt = n `div` m

main = do
    input <- getLine
    let arr = map (\s -> read s :: Integer) $ words input
    print $ solve (arr !! 0) (arr !! 1) (arr !! 2) (arr !! 3)

import Numeric

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

main = interact $ show.f.map fastRead .words

f (n:m:a:b:[])
  | m*a <= b = n*a
  | n `mod` m > 0 = b + i
  | otherwise = i
  where i = (n `div` m)*b

import Numeric

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

main = interact $ show.f.map fastRead .words

f (n:m:a:b:[])
  | m*a <= b = n*a
  | otherwise = (n `mod` m)*a + (n `div` m)*b

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show.solve.map read. words.head.lines
solve :: [Int]->Int
solve [a, b, c, d] | b*c <=d   = a*c
                   | c>=d      = if (a `mod` b)/=0 then ((a `div` b) + 1)*d else (a `div` b)*d
                   | otherwise = (a `div` b) * d +(a `mod` b) * c

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show.solve.map read. words.head.lines
solve :: [Int]->Int
solve [a, b, c, d] | b*c <=d   = a*c
                   | c>=d      = ((a `div` b) + 1)*d
                   | otherwise = (a `div` b) * d +(a `mod` b) * c

type Vec4 = (Integer, Integer, Integer, Integer)

split :: Eq a => a -> [a] -> [[a]]
split _    [] = []
split cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs

process :: Vec4 -> Integer
process (0, _, _, _) = 0
process (n, m, a, b) =
  let sep =
          [ a * x + b * y
          | x <- [0 .. floor (sqrt (1000.0))]
          , y <- [0 .. floor (sqrt (1000.0))]
          , x + m * y == n
          ]
  in  minimum sep

main :: IO ()
main = do
  input <- getLine
  let xs = map (read :: String -> Integer) (split ' ' input)
  let k  = (xs !! 0, xs !! 1, xs !! 2, xs !! 3)
  print $ process k

type Vec4 = (Integer, Integer, Integer, Integer)

split :: Eq a => a -> [a] -> [[a]]
split _    [] = []
split cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs

process :: Vec4 -> Integer
process (0, _, _, _) = 0
process (n, m, a, b) =
  let sep =
          [ a * x + b * y
          | x <- [0 .. floor (sqrt (1000.0))]
          , y <- [0 .. floor (sqrt (1000.0))]
          , x + m * y >= n
          ]
  in  if sep == [] then 1 else minimum sep

main :: IO ()
main = do
  input <- getLine
  let xs = map (read :: String -> Integer) (split ' ' input)
  let k  = (xs !! 0, xs !! 1, xs !! 2, xs !! 3)
  print $ process k

import Data.Char
main = interact $ show . f . map read . words
f (a:b:c:d:e) = min (a*c) (c*mod a b+d*div a b)

import Control.Applicative

process n m a b = minimum [b*((div n m )+1), b*(div n m)+a*(mod n m)]

main=do
     [n,m,a,b]<-  map read <$> words <$> getLine::IO [Int]
     print $ process n m a b

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

solve :: [Int] -> Int
solve [n, m, a, b] | a * m <= b = n * a
                   | otherwise = b * (n `div` m) + a * (n `mod` m)

import Control.Applicative

main= do
	[n,m,a,b] <- map read. words <$> getLine::IO [Int]
	print $ if (fromIntegral b )/ (fromIntegral m) >= fromIntegral a then n*a else min ((div n m)*b + (mod n m)*a ) ((div n m )+1)*b

import Control.Applicative

main= do
	[n,m,a,b] <- map read. words <$> getLine::IO [Int]
	print $ if (fromIntegral b )/ (fromIntegral m) >= fromIntegral a then n*a else (div n m)*b + (mod n m)*a

import Data.List

answer :: [Integer] -> Integer
answer [n, m, a, b] | fromIntegral b / fromIntegral m >  fromIntegral a = a * n
                    | need * a < b = buy * b + need * a
                    | otherwise = (buy + 1) * m
                     where (buy, need) =  n `divMod` m

someFunc :: IO ()
someFunc = getLine >>= print . answer . fmap read . words

main :: IO ()
main = someFunc


The king's birthday dinner was attended by $$$k$$$ guests. The dinner was quite a success: every person has eaten several dishes (though the number of dishes was the same for every person) and every dish was served alongside with a new set of kitchen utensils.All types of utensils in the kingdom are numbered from $$$1$$$ to $$$100$$$. It is known that every set of utensils is the same and consist of different types of utensils, although every particular type may appear in the set at most once. For example, a valid set of utensils can be composed of one fork, one spoon and one knife.After the dinner was over and the guests were dismissed, the king wondered what minimum possible number of utensils could be stolen. Unfortunately, the king has forgotten how many dishes have been served for every guest but he knows the list of all the utensils left after the dinner. Your task is to find the minimum possible number of stolen utensils.

The first line contains two integer numbers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100, 1 \le k \le 100$$$)  — the number of kitchen utensils remaining after the dinner and the number of guests correspondingly. The next line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$)  — the types of the utensils remaining. Equal values stand for identical utensils while different values stand for different utensils.

Output a single value — the minimum number of utensils that could be stolen by the guests.

NoteIn the first example it is clear that at least one utensil of type $$$3$$$ has been stolen, since there are two guests and only one such utensil. But it is also possible that every person received only one dish and there were only six utensils in total, when every person got a set $$$(1, 2, 3)$$$ of utensils. Therefore, the answer is $$$1$$$.One can show that in the second example at least $$$2$$$ dishes should have been served for every guest, so the number of utensils should be at least $$$24$$$: every set contains $$$4$$$ utensils and every one of the $$$3$$$ guests gets two such sets. Therefore, at least $$$14$$$ objects have been stolen. Please note that utensils of some types (for example, of types $$$2$$$ and $$$4$$$ in this example) may be not present in the set served for dishes.

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


Let's assume that we have a pair of numbers (a, b). We can get a new pair (a + b, b) or (a, a + b) from the given pair in a single step.Let the initial pair of numbers be (1,1). Your task is to find number k, that is, the least number of steps needed to transform (1,1) into the pair where at least one number equals n.

The input contains the only integer n (1 ≤ n ≤ 106).

NoteThe pair (1,1) can be transformed into a pair containing 5 in three moves: (1,1)  →  (1,2)  →  (3,2)  →  (5,2).

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)

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

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


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.

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

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

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


Have you ever played Hanabi? If not, then you've got to try it out! This problem deals with a simplified version of the game.Overall, the game has 25 types of cards (5 distinct colors and 5 distinct values). Borya is holding n cards. The game is somewhat complicated by the fact that everybody sees Borya's cards except for Borya himself. Borya knows which cards he has but he knows nothing about the order they lie in. Note that Borya can have multiple identical cards (and for each of the 25 types of cards he knows exactly how many cards of this type he has).The aim of the other players is to achieve the state when Borya knows the color and number value of each of his cards. For that, other players can give him hints. The hints can be of two types: color hints and value hints. A color hint goes like that: a player names some color and points at all the cards of this color. Similarly goes the value hint. A player names some value and points at all the cards that contain the value.Determine what minimum number of hints the other players should make for Borya to be certain about each card's color and value.

The first line contains integer n (1 ≤ n ≤ 100) — the number of Borya's cards. The next line contains the descriptions of n cards. The description of each card consists of exactly two characters. The first character shows the color (overall this position can contain five distinct letters — R, G, B, Y, W). The second character shows the card's value (a digit from 1 to 5). Borya doesn't know exact order of the cards they lie in.

Print a single integer — the minimum number of hints that the other players should make.

NoteIn the first sample Borya already knows for each card that it is a green three.In the second sample we can show all fours and all red cards.In the third sample you need to make hints about any four colors.

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

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

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

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


Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it's guaranteed that pi < pi + 1 and ti < ti + 1.A constant c is given too, representing the speed of loosing points. Then, submitting the i-th problem at time x (x minutes after the start of the contest) gives max(0,  pi - c·x) points.Limak is going to solve problems in order 1, 2, ..., n (sorted increasingly by pi). Radewoosh is going to solve them in order n, n - 1, ..., 1 (sorted decreasingly by pi). Your task is to predict the outcome — print the name of the winner (person who gets more points at the end) or a word "Tie" in case of a tie.You may assume that the duration of the competition is greater or equal than the sum of all ti. That means both Limak and Radewoosh will accept all n problems.

The first line contains two integers n and c (1 ≤ n ≤ 50, 1 ≤ c ≤ 1000) — the number of problems and the constant representing the speed of loosing points. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ 1000, pi < pi + 1) — initial scores. The third line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 1000, ti < ti + 1) where ti denotes the number of minutes one needs to solve the i-th problem.

Print "Limak" (without quotes) if Limak will get more points in total. Print "Radewoosh" (without quotes) if Radewoosh will get more points in total. Print "Tie" (without quotes) if Limak and Radewoosh will get the same total number of points.

NoteIn the first sample, there are 3 problems. Limak solves them as follows:  Limak spends 10 minutes on the 1-st problem and he gets 50 - c·10 = 50 - 2·10 = 30 points.  Limak spends 15 minutes on the 2-nd problem so he submits it 10 + 15 = 25 minutes after the start of the contest. For the 2-nd problem he gets 85 - 2·25 = 35 points.  He spends 25 minutes on the 3-rd problem so he submits it 10 + 15 + 25 = 50 minutes after the start. For this problem he gets 250 - 2·50 = 150 points. So, Limak got 30 + 35 + 150 = 215 points.Radewoosh solves problem in the reversed order:  Radewoosh solves 3-rd problem after 25 minutes so he gets 250 - 2·25 = 200 points.  He spends 15 minutes on the 2-nd problem so he submits it 25 + 15 = 40 minutes after the start. He gets 85 - 2·40 = 5 points for this problem.  He spends 10 minutes on the 1-st problem so he submits it 25 + 15 + 10 = 50 minutes after the start. He gets max(0, 50 - 2·50) = max(0,  - 50) = 0 points. Radewoosh got 200 + 5 + 0 = 205 points in total. Limak has 215 points so Limak wins.In the second sample, Limak will get 0 points for each problem and Radewoosh will first solve the hardest problem and he will get 250 - 6·25 = 100 points for that. Radewoosh will get 0 points for other two problems but he is the winner anyway.In the third sample, Limak will get 2 points for the 1-st problem and 2 points for the 2-nd problem. Radewoosh will get 4 points for the 8-th problem. They won't get points for other problems and thus there is a tie because 2 + 2 = 4.

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"

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


Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.Limak eats a lot and his weight is tripled after every year, while Bob's weight is doubled after every year.After how many full years will Limak become strictly larger (strictly heavier) than Bob?

The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 10) — the weight of Limak and the weight of Bob respectively.

Print one integer, denoting the integer number of years after which Limak will become strictly larger than Bob.

NoteIn the first sample, Limak weighs 4 and Bob weighs 7 initially. After one year their weights are 4·3 = 12 and 7·2 = 14 respectively (one weight is tripled while the other one is doubled). Limak isn't larger than Bob yet. After the second year weights are 36 and 28, so the first weight is greater than the second one. Limak became larger than Bob after two years so you should print 2.In the second sample, Limak's and Bob's weights in next years are: 12 and 18, then 36 and 36, and finally 108 and 72 (after three years). The answer is 3. Remember that Limak wants to be larger than Bob and he won't be satisfied with equal weights.In the third sample, Limak becomes larger than Bob after the first year. Their weights will be 3 and 2 then.

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

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

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


Johny likes numbers n and k very much. Now Johny wants to find the smallest integer x greater than n, so it is divisible by the number k.

The only line contains two integers n and k (1 ≤ n, k ≤ 109).

Print the smallest integer x > n, so it is divisible by the number k.

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)


The weather is fine today and hence it's high time to climb the nearby pine and enjoy the landscape.The pine's trunk includes several branches, located one above another and numbered from 2 to y. Some of them (more precise, from 2 to p) are occupied by tiny vile grasshoppers which you're at war with. These grasshoppers are known for their awesome jumping skills: the grasshopper at branch x can jump to branches .Keeping this in mind, you wisely decided to choose such a branch that none of the grasshoppers could interrupt you. At the same time you wanna settle as high as possible since the view from up there is simply breathtaking.In other words, your goal is to find the highest branch that cannot be reached by any of the grasshoppers or report that it's impossible.

The only line contains two integers p and y (2 ≤ p ≤ y ≤ 109).

Output the number of the highest suitable branch. If there are none, print -1 instead.

NoteIn the first sample case grasshopper from branch 2 reaches branches 2, 4 and 6 while branch 3 is initially settled by another grasshopper. Therefore the answer is 5.It immediately follows that there are no valid branches in second sample case.

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]

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]


Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in the second bit, and so on; the most significant bit is stored in the n-th bit.Now Sergey wants to test the following instruction: "add 1 to the value of the cell". As a result of the instruction, the integer that is written in the cell must be increased by one; if some of the most significant bits of the resulting number do not fit into the cell, they must be discarded.Sergey wrote certain values of the bits in the cell and is going to add one to its value. How many bits of the cell will change after the operation?

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of bits in the cell. The second line contains a string consisting of n characters — the initial state of the cell. The first character denotes the state of the first bit of the cell. The second character denotes the second least significant bit and so on. The last character denotes the state of the most significant bit.

Print a single integer — the number of bits in the cell which change their state after we add 1 to the cell.

NoteIn the first sample the cell ends up with value 0010, in the second sample — with 0000.

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


Baby Ehab was toying around with arrays. He has an array $$$a$$$ of length $$$n$$$. He defines an array to be good if there's no way to partition it into $$$2$$$ subsequences such that the sum of the elements in the first is equal to the sum of the elements in the second. Now he wants to remove the minimum number of elements in $$$a$$$ so that it becomes a good array. Can you help him?A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero or all) elements. A partitioning of an array is a way to divide it into $$$2$$$ subsequences such that every element belongs to exactly one subsequence, so you must use all the elements, and you can't share any elements.

The first line contains an integer $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 2000$$$) — the elements of the array $$$a$$$.

The first line should contain the minimum number of elements you need to remove. The second line should contain the indices of the elements you're removing, separated by spaces. We can show that an answer always exists. If there are multiple solutions, you can print any.

NoteIn the first example, you can partition the array into $$$[6,9]$$$ and $$$[3,12]$$$, so you must remove at least $$$1$$$ element. Removing $$$3$$$ is sufficient.In the second example, the array is already good, so you don't need to remove any elements.

import Data.Array.Unboxed ((!))
import qualified Data.Array.Unboxed as A
import qualified Data.Maybe as M
import Data.List (foldl', findIndex)

type BoolArray = A.UArray Int Bool

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

part :: BoolArray -> Int -> BoolArray
part dp x = A.array (A.bounds dp) [(j, get j) | j <- A.indices dp] where
  get j
    | j == 0 = True
    | x > j = dp ! j
    | otherwise = dp ! j || dp ! (j - x)

canParition :: [Int] -> Bool
canParition xs = even s && calc xs where
  s = sum xs
  calc (x : xs) = last ! n where
    n = s `div` 2
    init = A.array (0, n) $ (0, True) : [(j, x == j) | j <- [1..n] ]
    last = foldl' part init xs

reduceOdd :: [Int] -> [Int]
reduceOdd xs = if all even xs
  then reduceOdd $ map (`div` 2) xs
  else xs

solve :: [Int] -> Int
solve xs = if canParition xs
  then 1 + M.fromMaybe 0 (findIndex odd (reduceOdd xs))
  else 0

main :: IO ()
main =
  getLine >>
  solve <$> readInts >>= \ans ->
  if ans == 0
    then putStrLn "0"
    else putStrLn "1" >> print ans

import Data.Array.Unboxed ((!))
import qualified Data.Array.Unboxed as A
import qualified Data.Maybe as M
import Data.List (foldl', findIndex)

type BoolArray = A.UArray Int Bool

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

part :: BoolArray -> Int -> BoolArray
part dp x = A.array (A.bounds dp) [(j, get j) | j <- A.indices dp] where
  get j
    | j == 0 = True
    | x > j = dp ! j
    | otherwise = dp ! j || dp ! (j - x)

canParition :: [Int] -> Bool
canParition xs = even s && calc xs where
  s = sum xs
  calc (x : xs) = last ! n where
    n = s `div` 2
    init = A.array (0, n) $ (0, True) : [(j, x == j) | j <- [1..n] ]
    last = foldl' part init (x : xs)

reduceOdd :: [Int] -> [Int]
reduceOdd xs = if all even xs
  then reduceOdd $ map (`div` 2) xs
  else xs

solve :: [Int] -> Int
solve xs = if canParition xs
  then 1 + M.fromMaybe 0 (findIndex odd (reduceOdd xs))
  else 0

main :: IO ()
main =
  getLine >>
  solve <$> readInts >>= \ans ->
  if ans == 0
    then putStrLn "0"
    else putStrLn "1" >> print ans

import Data.Array ((!))
import qualified Data.Array as A
import qualified Data.Maybe as M
import Data.List (foldl', findIndex)

type BoolArray = A.Array Int Bool

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

part :: BoolArray -> Int -> BoolArray
part dp x = A.array (A.bounds dp) [(j, get j) | j <- A.indices dp] where
  get j
    | j == 0 = True
    | x > j = dp ! j
    | otherwise = dp ! j || dp ! (j - x)

canParition :: [Int] -> Bool
canParition xs = even s && calc xs where
  s = sum xs
  calc (x : xs) = last ! n where
    n = s `div` 2
    init = A.array (0, n) $ (0, True) : [(j, x == j) | j <- [1..n] ]
    last = foldl' part init (x : xs)

reduceOdd :: [Int] -> [Int]
reduceOdd xs = if all even xs
  then reduceOdd $ map (`div` 2) xs
  else xs

solve :: [Int] -> Int
solve xs = if canParition xs
  then M.fromMaybe 0 $ findIndex odd (reduceOdd xs)
  else 0

main :: IO ()
main =
  getLine >>
  solve <$> readInts >>= \ans ->
  if ans == 0
    then putStrLn "0"
    else putStrLn "1" >> print (ans + 1)


One day a highly important task was commissioned to Vasya — writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as  lines, drinks another cup of tea, then he writes  lines and so on: , , , ...The expression  is regarded as the integral part from dividing number a by number b.The moment the current value  equals 0, Vasya immediately falls asleep and he wakes up only in the morning, when the program should already be finished.Vasya is wondering, what minimum allowable value v can take to let him write not less than n lines of code before he falls asleep.

The input consists of two integers n and k, separated by spaces — the size of the program in lines and the productivity reduction coefficient, 1 ≤ n ≤ 109, 2 ≤ k ≤ 10.

Print the only integer — the minimum value of v that lets Vasya write the program in one night.

NoteIn the first sample the answer is v = 4. Vasya writes the code in the following portions: first 4 lines, then 2, then 1, and then Vasya falls asleep. Thus, he manages to write 4 + 2 + 1 = 7 lines in a night and complete the task.In the second sample the answer is v = 54. Vasya writes the code in the following portions: 54, 6. The total sum is 54 + 6 = 60, that's even more than n = 59.

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

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

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

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

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