{-# LANGUAGE MultiWayIf #-}

module Main where

import           Control.Monad
import           Control.Monad.Extra
import qualified Data.Array as A
import qualified Data.Array.IO as AIO
import qualified Data.Array.Unboxed as AU
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC8
import           Data.Char
import           Data.Either
import           Data.Function
import qualified Data.Graph.Inductive.Graph as G
import qualified Data.Graph.Inductive.PatriciaTree as G
import qualified Data.Heap as H
import           Data.Int
import           Data.List
import qualified Data.Map.Strict as M
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import qualified Data.Sequence as SQ
import qualified Data.Set as S
import           Data.Tuple
import qualified Data.Vector as V
import           Data.Vector.Algorithms.Search
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import           Debug.Trace
import           GHC.Base

main = do
  --aN       <- getI
  --[aA, aB] <- getIL
  --aS       <- getLine
  [aN, aM] <- getIL
  graphIniData <- aclMaxFlowGraph $ (aN * aM + 2 :: Int)
  let s = aN * aM
  let t = aN * aM + 1
  grid <- V.replicateM aN getVUC
  graphIniDataAdd1 <- VU.foldM
    (\acc1 i -> VU.foldM
       (\acc2 j -> let v = i * aM + j
                   in if grid V.! i VU.! j == '#'
                      then return acc2
                      else if even (i + j)
                           then do
                             (m, ret) <- aclMaxFlowAddEdge acc2 s v 1
                             return ret
                           else do
                             (m, ret) <- aclMaxFlowAddEdge acc2 v t 1
                             return ret)
       acc1
       (VU.enumFromN 0 aM))
    graphIniData
    (VU.enumFromN 0 aN)
    :: IO (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int))
  graphIniDataAdd2@(_, _, pos1) <- VU.foldM
    (\acc1 i -> VU.foldM
       (\acc2 j
        -> let v0 = i * aM + j
           in VU.foldM
                (\acc3 k@(ky, kx)
                 -> let v1 = kx + (ky * aM)
                    in if odd (i + j) || grid V.! i VU.! j == '#'
                       then return acc3
                       else if grid V.! ky VU.! kx == '.'
                            then do
                              (m, ret) <- aclMaxFlowAddEdge acc3 v0 v1 1
                              return ret
                            else return acc3)
                acc2
              $ VU.fromList
              $ aroundSquare i j aN aM)
       acc1
       (VU.enumFromN 0 aM))
    graphIniDataAdd1
    (VU.enumFromN 0 aN)
  graphData@(_, graph, pos2) <- aclMaxFlowConvertIniData graphIniDataAdd2
  {-
  print "graph1"
  V.imapM_
    (\i x -> do
       fx <- VU.freeze x
       print $ show i ++ ":" ++ show fx)
    =<< (V.freeze graph)
    -}
  flow <- aclMaxFlowFlow graphData s t
  print flow
  {-
  print "graph2"
  V.imapM_
    (\i x -> do
       fx <- VU.freeze x
       print $ show i ++ ":" ++ show fx)
    =<< (V.freeze graph)
  -}
  edges <- aclMaxFlowEdges graphData
  --print edges
  --print =<< VU.freeze pos2
  newGrid <- V.thaw =<< (V.generateM aN $ \i -> VU.thaw $ grid V.! i)
  VU.mapM_
    (\e@(from, to, cap, flow) -> do
       if from == s || to == t || flow == 0
         then return ()
         else do
           let i0 = div from aM
               j0 = mod from aM
               i1 = div to aM
               j1 = mod to aM
           newGridI0 <- VM.read newGrid i0
           newGridI1 <- VM.read newGrid i1
           if
             | i0 == i1 + 1 -> do
               VUM.write newGridI1 j1 'v'
               VUM.write newGridI0 j0 '^'
             | j0 == j1 + 1 -> do
               VUM.write newGridI1 j1 '>'
               VUM.write newGridI0 j0 '<'
             | i0 == i1 - 1 -> do
               VUM.write newGridI0 j0 'v'
               VUM.write newGridI1 j1 '^'
             | otherwise -> do
               VUM.write newGridI0 j0 '>'
               VUM.write newGridI1 j1 '<')
    edges
  V.mapM_ (\newGridI -> putStrLn =<< VU.toList <$> VU.freeze newGridI)
    =<< V.freeze newGrid
  return ()

--雑多系
t :: Int -> (Int, Int)
t x = (x, 1)

i def f t = bool t def $ f t

shiftRCnt k = shiftRCntP k 1

shiftRCntP k c = let nk = shiftR k 1
                 in if nk == 0
                    then c
                    else shiftRCntP nk (c + 1)

myVUmap f vu =
  if vu == VU.empty
  then VU.empty
  else VU.unfoldr
    (\x -> let ret = f $ VU.head x
               tailx = VU.tail x
           in if x == VU.empty
              then Nothing
              else if isLeft ret
                   then Just (either id id ret, tailx)
                   else Just (either id id ret, VU.empty))
    vu

myVUmapM f vu =
  if vu == VU.empty
  then return VU.empty
  else VU.unfoldrM
    (\x -> do
       ret <- f $ VU.head x
       let tailx = VU.tail x
       if x == VU.empty
         then return Nothing
         else if isLeft ret
              then return $ Just (either id id ret, tailx)
              else return $ Just (either id id ret, VU.empty))
    vu

myVUmapM_ f vu =
  if vu == VU.empty
  then return ()
  else do
    ret1 <- VU.unfoldrM
      (\x -> do
         ret2 <- f $ VU.head x
         let tailx = VU.tail x
         if x == VU.empty
           then return Nothing
           else if isLeft ret2
                then return $ Just (either id id ret2, tailx)
                else return $ Just (either id id ret2, VU.empty))
      vu
    return ()

myVUfor vu f = myVUmap f vu

myVUforM vu f = myVUmapM f vu

myVUforM_ vu f = myVUmapM_ f vu

myVUfoldl f acc vu =
  if vu == VU.empty
  then return acc
  else do
    let ret = f acc (VU.head vu)
    if isLeft ret
      then myVUfoldl f (either id id ret) (VU.tail vu)
      else return $ either id id ret

myVUfoldr f acc vu =
  if vu == VU.empty
  then return acc
  else do
    let ret = f acc (VU.last vu)
    if isLeft ret
      then myVUfoldr f (either id id ret) (VU.init vu)
      else return $ either id id ret

myVUfoldM f acc vu =
  if vu == VU.empty
  then return acc
  else do
    ret <- f acc (VU.head vu)
    if isLeft ret
      then myVUfoldM f (either id id ret) (VU.tail vu)
      else return $ either id id ret

--周りのマス
aroundSquare y x h w =
  [aYX
  | aYX@(aY, aX)
      <- [(y + a, x + b) | a <- [-1 .. 1], b <- [-1 .. 1], abs a + abs b == 1]
  , aY >= 0
  , aY <= h - 1
  , aX >= 0
  , aX <= w - 1]

--入力系
splitReadBSC8 :: BSC8.ByteString -> [Int]
splitReadBSC8 bs = let (bs1, newBs) = BSC8.splitAt 1 bs
                   in if newBs == BSC8.empty
                      then [test $ BSC8.readInt bs1]
                      else test (BSC8.readInt bs1):splitReadBSC8 newBs
  where
    test (Just (i, _)) = i

read2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> IO Char
read2DimChar vec y x = do
  vecY <- VM.read vec y
  VUM.read vecY x

write2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> Char -> IO ()
write2DimChar vec y x t = do
  vecY <- VM.read vec y
  VUM.write vecY x t

readTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> IO Int
readTwoDimVec vec y x = do
  vecY <- VM.read vec y
  VUM.read vecY x

writeTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> Int -> IO ()
writeTwoDimVec vec y x t = do
  vecY <- VM.read vec y
  VUM.write vecY x t

getVUI :: IO (VU.Vector Int)
getVUI = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine

getRepVUI :: Int -> IO (VU.Vector Int)
getRepVUI n = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) . BSC8.unlines
  <$> replicateM n BSC8.getLine

getVS :: IO (V.Vector Char)
getVS = V.fromList <$> getLine

getVUC :: IO (VU.Vector Char)
getVUC = VU.fromList <$> getLine

readI :: BSC8.ByteString -> Int
readI = fst . fromJust . BSC8.readInt

readInteger :: BSC8.ByteString -> Integer
readInteger = fst . fromJust . BSC8.readInteger

readIL :: BSC8.ByteString -> [Int]
readIL = map readI . BSC8.words

readIT2 :: BSC8.ByteString -> (Int, Int)
readIT2 bs = let words = BSC8.words bs
             in (readI $ head words, readI $ last words)

readIT3 :: BSC8.ByteString -> (Int, Int, Int)
readIT3 bs = let words = BSC8.words bs
             in (readI $ head words, readI $ words !! 1, readI $ words !! 2)

getI :: IO Int
getI = readI <$> BSC8.getLine

getInteger :: IO Integer
getInteger = readInteger <$> BSC8.getLine

getIL :: IO [Int]
getIL = readIL <$> BSC8.getLine

getIT2 :: IO (Int, Int)
getIT2 = readIT2 <$> BSC8.getLine

getIT3 :: IO (Int, Int, Int)
getIT3 = readIT3 <$> BSC8.getLine

getIT2Order :: IO (Int, Int)
getIT2Order = getIL
  >>= \x@[xz, xo] -> if xz > xo
                     then return (xo, xz)
                     else return (xz, xo)

getNIS :: Int -> IO [(Int, BSC8.ByteString)]
getNIS 0 = return []
getNIS n = do
  [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
  next <- getNIS (n - 1)
  return ((readI aFst, aSnd):next)

il2Words :: [Int] -> String
il2Words = unwords . map show

il2Lines :: [Int] -> String
il2Lines = unlines . map show

--modNum = 10 ^ 9 + 7
--modulus = 1000000007
modulus = 1000000007

newtype MInt = M Int

instance Num MInt where
  (M a) + (M b) = M $ mod (a + b) modulus

  (M a) - (M b) = M $ mod (a - b) modulus

  (M a) * (M b) = M $ mod (a * b) modulus

  fromInteger a = M $ mod (fromInteger a) modulus

  abs (M a) = undefined

  signum (M a) = undefined

instance Show MInt where
  show (M a) = show (mod a modulus)

int2MInt :: Int -> MInt
int2MInt a = M (mod a modulus)

mInt2Int :: MInt -> Int
mInt2Int (M a) = a

{-
factsMod :: V.Vector MInt
factsMod = V.scanl (\acc x -> M x * acc) 1 $ V.generate 2000000 (+ 1)

factMod :: Int -> MInt
factMod = (factsMod V.!)
-}
factMod :: Int -> MInt
factMod n
  | n == 0 = 1
  | n == 1 = 1
  | otherwise = M n * factMod (n - 1)

factDivMod :: Int -> Int -> MInt
factDivMod n k
  | n == k = M 1
  | otherwise = M n * factDivMod (n - 1) k

powMod :: MInt -> MInt -> MInt
powMod n mK@(M k)
  | k == 0 = M 1
  | k == 1 = n
  | mod k 2 == 0 = powMod (n ^ 2) (M (div k 2))
  | otherwise = n * powMod (n ^ 2) (M (div k 2))

invMod :: MInt -> MInt
invMod (M 0) = error "inverse of 0"
invMod x = powMod x (M (modulus - 2))

{-
combiMod :: Int -> Int -> MInt
combiMod n k
  | n < 0 || k < 0 || k > n = 0
  | otherwise = factMod n * invMod (factMod (n - k)) * invMod (factMod k)
-}
combiMod :: Int -> Int -> MInt
combiMod n k
  | n < 0 || k < 0 || k > n = 0
  | k > n - k = factDivMod n k * invMod (factMod (n - k))
  | otherwise = factDivMod n (n - k) * invMod (factMod k)

combi :: Int -> Int -> Int
combi n k
  | n < 0 || k < 0 || k > n = 0
  | k == n = 1
  | otherwise = div (div (fact n) (fact (n - k))) (fact k)

{-w
primes :: Integral a => [a]
primes = map fromIntegral $ [2, 3] ++ primes'
 where
  primes' = [5] ++ f 1 7 primes'
  f m s (p : ps) = [ n | n <- ns, gcd m n == 1 ] ++ f (m * p) (p * p) ps
    where ns = [ x + y | x <- [s, s + 6 .. p * p - 2], y <- [0, 4] ]

prime n = primes !! n
primes = sieve [2 ..]
sieve (p : xs) = p : sieve [ x | x <- xs, x `mod` p /= 0 ]
-}
fact :: Int -> Int
fact 0 = 1
fact n
  | n > 0 = n * fact (n - 1)

knappsackWDP :: Int -> [(Int, Int)] -> VU.Vector Int
knappsackWDP maxW [] = VU.replicate (maxW + 1) 0
knappsackWDP maxW ((w, v):xs) =
  let tailDP = knappsackWDP maxW xs
  in VU.generate (maxW + 1)
     $ \i -> if w <= i
             then max (tailDP VU.! i) (tailDP VU.! (i - w) + v)
             else tailDP VU.! i

knappsackVDP :: Int -> Int -> Int -> [(Int, Int)] -> VU.Vector Int
knappsackVDP maxW maxV n [] = VU.cons 0 $ VU.replicate (n * maxV) maxW
knappsackVDP maxW maxV n ((w, v):xs) =
  let tailDP = knappsackVDP maxW maxV n xs
  in VU.generate (n * maxV + 1)
     $ \i -> if v <= i
             then min (tailDP VU.! i) (tailDP VU.! (i - v) + w)
             else tailDP VU.! i

knappsackMinVol :: AIO.IOArray (Int, Int) Int
                -> VU.Vector Int
                -> VU.Vector Int
                -> Int
                -> Int
                -> IO Int
knappsackMinVol dp volumeVec valueVec dpSize maxVolume = do
  mapM_
    (\i -> mapM_
       (\v -> do
          let volume = volumeVec VU.! i
              value = valueVec VU.! i
          newdp <- if (v + value) > dpSize
                   then AIO.readArray dp (i, v)
                   else do
                     dpIVm <- AIO.readArray dp (i, v + value)
                     dpIV <- AIO.readArray dp (i, v)
                     return (min (dpIVm - volume) dpIV)
          AIO.writeArray dp (i + 1, v) newdp)
       (reverse [0 .. dpSize]))
    [0 .. VU.length valueVec - 1]
  foldM
    (\acc x -> do
       num <- AIO.readArray dp (VU.length volumeVec, x)
       return
         $ if num <= maxVolume
           then x
           else acc)
    0
    [0 .. dpSize]

lcsTable :: BS.ByteString -> BS.ByteString -> V.Vector (VU.Vector Int)
lcsTable xs ys = V.scanl step (VU.replicate (m + 1) 0) xs'
  where
    n = BS.length xs

    m = BS.length ys

    xs' = V.generate n $ BSC8.index xs :: V.Vector Char

    ys' = VU.generate m $ BSC8.index ys :: VU.Vector Char

    step :: VU.Vector Int -> Char -> VU.Vector Int
    step v x = VU.scanl innerStep 0 (VU.zip3 v (VU.tail v) ys')
      where
        innerStep :: Int -> (Int, Int, Char) -> Int
        innerStep a (b, c, y)
          | x == y = 1 + b
          | otherwise = max a c

{-
main = do
xs <- BS.getLine
ys <- BS.getLine
print $ VU.last $ V.last $ lcsTable xs ys
-}
myFilter :: (a -> Bool) -> [a] -> ([a], [a])
myFilter _pred [] = ([], [])
myFilter pred (x:xs)
  | pred x = let (l, r) = myFilter pred xs
             in (x:l, r)
  | otherwise = let (l, r) = myFilter pred xs
                in (l, x:r)

--UnionFindデータ構造
type UF_PARENT = VUM.IOVector Int

type UF_RANK = VUM.IOVector Int

type UF = (UF_PARENT, UF_RANK)

ufMakeSet :: Int -> IO UF
ufMakeSet n = do
  parent <- VU.thaw $ VU.generate n id
  rank <- VUM.replicate n 0
  return (parent, rank)

ufUnion :: UF -> Int -> Int -> IO ()
ufUnion unionFind@(parents, ranks) x y = do
  xRoot <- ufFind unionFind x
  yRoot <- ufFind unionFind y
  xRootRank <- VUM.read ranks xRoot
  yRootRank <- VUM.read ranks yRoot
  if
    | xRootRank > yRootRank -> VUM.write parents yRoot xRoot
    | xRootRank < yRootRank -> VUM.write parents xRoot yRoot
    | xRoot /= yRoot -> do
      VUM.write parents yRoot xRoot
      VUM.write ranks xRoot (xRootRank + 1)
    | otherwise -> return ()

ufFind :: UF -> Int -> IO Int
ufFind unionFind@(parents, ranks) x = do
  xParent <- VUM.read parents x
  if xParent == x
    then return x
    else do
      xRootParent <- ufFind unionFind xParent
      VUM.write parents x xRootParent
      return xRootParent

--無向グラフ
type UDG = M.Map Int [Int]

list2UDG :: [(Int, Int)] -> M.Map Int [Int]
list2UDG = foldl
  (\acc x -> let lr = M.insertWith (++) (fst x) [snd x] acc
             in M.insertWith (++) (snd x) [fst x] lr)
  M.empty

--有向グラフエッジ情報(コスト付き)
type DGEwC = M.Map Int [(Int, Int, Int)]

--OSA-K法テーブル準備(お酒？)
osaKMethod m = do
  table <- VUM.replicate (m + 1) (0 :: Int) :: IO (VUM.IOVector Int)
  modi table m 2 1 1 (div m 2)
  loopModi table m 3
  VU.freeze table
  where
    loopModi table m x
      | x > m = return ()
      | otherwise = do
        modi table m x 1 2 (div m x)
        loopModi table m (x + 2)

    modi table m x n s nm
      | n > nm = return ()
      | otherwise = do
        let xn = x * n
        target <- VUM.read table xn
        if target == 0
          then do
            VUM.write table xn x
            modi table m x (n + s) s nm
          else if n == 1
               then return ()
               else modi table m x (n + s) s nm

getPrimes osaKTable target = VU.unfoldr
  (\x -> let minPrime = osaKTable VU.! target
             (prime, quo) = if minPrime == 0
                            then (target, 1)
                            else (target, div target minPrime)
         in if x == 1
            then Nothing
            else Just (prime, quo))
  target

--IMOS法1次元用
imosMethodDim1 n lrs = VU.create
  $ do
    table <- VUM.replicate n 0
    VU.mapM_
      (\(l, r) -> do
         VUM.modify table succ $ pred l
         when (r <= n - 1) $ VUM.modify table pred r)
      lrs
    cumTable <- VUM.replicate n 0
    fTable <- VU.freeze table
    VUM.write cumTable 0 $ bool 1 0 $ even (fTable VU.! 0)
    VU.mapM_
      (\x -> do
         pv <- VUM.read cumTable (x - 1)
         VUM.write cumTable x $ bool 1 0 $ even (pv + fTable VU.! x))
      $ VU.enumFromN 1 (n - 1)
    return cumTable

--ベルマンフォード法 最短経路取得(負数が混じる場合は、まずは、負数閉路があるかどうかを調べる。)
bfMethodShortestPath vn edges = do
  table <- VUM.replicate vn maxInt :: IO (VUM.IOVector Int)
  VUM.write table 0 0
  myVUmapM_
    (\v -> do
       flg <- VU.foldM
         (\acc (from, to, cost) -> do
            fromCost <- VUM.read table $ pred from
            toCost <- VUM.read table $ pred to
            if fromCost /= maxInt && toCost > fromCost + cost
              then do
                VUM.write table (pred to) (fromCost + cost)
                return True
              else return acc)
         False
         edges
       if flg
         then return $ Left ()
         else return $ Right ())
    $ VU.enumFromN (0 :: Int) (vn - 1)
  VU.freeze table

{-bfMethodShortestPath vn edges = do
  table <- VUM.replicate vn maxInt
  VUM.write table 0 0
  scanLoop table
  VU.freeze table
  where
    scanLoop table = do
      flg <- VU.foldM
        (\acc (from, to, cost) -> do
           fromCost <- VUM.read table $ pred from
           toCost <- VUM.read table $ pred to
           if fromCost /= maxInt && toCost > fromCost + cost
             then do
               VUM.write table (pred to) (fromCost + cost)
               return $ True
             else return $ acc)
        False
        edges
      if flg
        then scanLoop table
        else return ()
-}
--ベルマンフォード法 負数閉路探索
bfMethodFindNegativeLoop vn edges = do
  table <- VUM.replicate vn 0 :: IO (VUM.IOVector Int)
  VU.mapM_
    (\v -> VU.mapM_
       (\(from, to, cost) -> do
          fromCost <- VUM.read table $ pred from
          toCost <- VUM.read table $ pred to
          when (toCost > fromCost + cost)
            $ VUM.write table (pred to) (fromCost + cost))
       edges)
    $ VU.enumFromN (0 :: Int) (vn - 1)
  myVUfoldM
    (\acc (from, to, cost) -> do
       fromCost <- VUM.read table $ pred from
       toCost <- VUM.read table $ pred to
       if toCost > fromCost + cost
         then do
           VUM.write table (pred to) (fromCost + cost)
           return $ Right True
         else return $ Left False)
    False
    edges

--ベルマンフォード法 負数閉路影響調査
bfMethodScanNegativeLoop vn edges = do
  table <- VUM.replicate vn 0 :: IO (VUM.IOVector Int)
  rTable <- VUM.replicate vn False :: IO (VUM.IOVector Bool)
  VU.mapM_
    (\v -> VU.mapM_
       (\(from, to, cost) -> do
          fromCost <- VUM.read table $ pred from
          toCost <- VUM.read table $ pred to
          when (toCost > fromCost + cost)
            $ VUM.write table (pred to) (fromCost + cost))
       edges)
    $ VU.enumFromN (0 :: Int) (vn - 1)
  VU.foldM_
    (\acc (from, to, cost) -> do
       fromCost <- VUM.read table $ pred from
       toCost <- VUM.read table $ pred to
       if toCost > fromCost + cost
         then do
           VUM.write table (pred to) (fromCost + cost)
           VUM.write rTable (pred to) True
           return True
         else return False)
    False
    edges
  VU.freeze rTable

--DijkstraMethod 壊れてるっぽい
dijkstraMethod :: Int -> DGEwC -> Int -> IO (VU.Vector Int)
dijkstraMethod n edges s = do
  table <- VUM.replicate n maxInt :: IO (VUM.IOVector Int)
  VUM.write table (pred s) 0
  let heap = H.insert (0, s) H.empty
  mfs table heap
  VU.freeze table
  where
    mfs table heap =
      if heap == H.empty
      then return ()
      else do
        let (hCost, hTo) = H.minimum heap
        toCost <- VUM.read table (pred hTo)
        let toEdges = M.findWithDefault [] hTo edges
        if toCost >= hCost
          then do
            accHeap <- foldM
              (\acc (eFrom, eTo, eCost) -> do
                 totoCost <- VUM.read table (pred eTo)
                 if totoCost > (toCost + eCost)
                   then do
                     VUM.write table (pred eTo) (toCost + eCost)
                     return $ H.insert (toCost + eCost, eTo) acc
                   else return acc)
              (H.deleteMin heap)
              toEdges
            mfs table accHeap
          else mfs table (H.deleteMin heap)

--BinarySearchっぽいもの 1からmまでのすべての数値をFにいれたとき最初にTrueになる数値を見つける。
binarySearchFirstTrueSerialASC f m =
  binarySearchFirstTrueSerialASCP f 0 (m + 1)

binarySearchFirstTrueSerialASCP f l r =
  let i = l + div (r - l) 2
      test = f i
  in if
       | test && i - l == 1 -> i
       | test && i - l /= 1 -> binarySearchFirstTrueSerialASCP f l i
       | not test && r - i == 1 -> r
       | otherwise -> binarySearchFirstTrueSerialASCP f i r

--BinarySearchっぽいもの その２ vuiのすべての数値をFにいれたとき最初にTrueになる数値を見つける。
binarySearchFirstTrueList f vui = let lenl = VU.length vui
                                  in binarySearchFirstTrueListP f vui (-1) lenl

binarySearchFirstTrueListP f vui l r =
  let i = l + div (r - l) 2
      test = f (vui VU.! i)
  in if
       | test && i - l == 1 -> i
       | test && i - l /= 1 -> binarySearchFirstTrueListP f vui l i
       | not test && r - i == 1 -> r
       | otherwise -> binarySearchFirstTrueListP f vui i r

--MaxHeap関連
hMaxPoint :: Int
hMaxPoint = 101

hMaximum :: H.Heap Int -> Int
hMaximum h = hMaxPoint - H.minimum h

hInsertMax :: Int -> H.Heap Int -> H.Heap Int
hInsertMax x = H.insert (hMaxPoint - x)

hDeleteMax :: H.Heap Int -> H.Heap Int
hDeleteMax = H.deleteMin

----ACL(AtCoder Library)のHaskell移植版(おっさんたたき台Ver.))
---DSU
aclDsuTable n = do
  parentOrSize <- VUM.replicate n (-1)
  return (n, parentOrSize)

aclDsuMerge table@(n, parentOrSize) a b
  | a < 0 || n <= a = error
    "aclDsuMerge:aを0以上でnより小さい値になるように見直してください。"
  | b < 0 || n <= b = error
    "aclDsuMerge:bを0以上でnより小さい値になるように見直してください。"
  | otherwise = do
    x <- aclDsuLeader table a
    y <- aclDsuLeader table b
    if x == y
      then return x
      else do
        posX <- VUM.read parentOrSize x
        posY <- VUM.read parentOrSize y
        if -posX < -posY
          then do
            VUM.write parentOrSize y (posY + posX)
            VUM.write parentOrSize x y
            return y
          else do
            VUM.write parentOrSize x (posX + posY)
            VUM.write parentOrSize y x
            return x

aclDsuSame table@(n, parentOrSize) a b
  | a < 0 && n <= a = error
    "aclDsuSame:aを0以上でnより小さい値になるように見直してください。"
  | b < 0 && n <= b = error
    "aclDsuSame:bを0以上でnより小さい値になるように見直してください。"
  | otherwise = do
    x <- aclDsuLeader table a
    y <- aclDsuLeader table b
    return $ x == y

aclDsuLeader table@(n, parentOrSize) a
  | a < 0 && n <= a = error
    "aclDsuLeader:aを0以上でnより小さい値になるように見直してください。"
  | otherwise = do
    posA <- VUM.read parentOrSize a
    if posA < 0
      then return a
      else do
        x <- aclDsuLeader table posA
        VUM.write parentOrSize a x
        return x

aclDsuSize table@(n, parentOrSize) a
  | a < 0 && n <= a = error
    "aclDsuSize:aを0以上でnより小さい値になるように見直してください。"
  | otherwise = do
    x <- aclDsuLeader table a
    negate <$> VUM.read parentOrSize x

aclDsuGroup table@(n, parentOrSize) = do
  leaderBuf <- VUM.replicate n 0
  groupSize <- VUM.replicate n 0
  VU.forM_ (VU.enumFromN 0 n)
    $ \i -> do
      leaderI <- aclDsuLeader table i
      VUM.write leaderBuf i leaderI
      VUM.modify groupSize succ leaderI
  resultTmpIndex <- VUM.replicate n 0
  resultTmp <- V.generateM n
    $ \i -> do
      gs <- VUM.read groupSize i
      VUM.replicate gs 0
  VU.forM_ (VU.enumFromN 0 n)
    $ \i -> do
      leaderI <- VUM.read leaderBuf i
      tmpIndex <- VUM.read resultTmpIndex leaderI
      VUM.write (resultTmp V.! leaderI) tmpIndex i
      VUM.modify resultTmpIndex succ leaderI
  V.mapMaybe id
    <$> V.mapM
      (\i -> do
         rti <- VU.freeze $ resultTmp V.! i
         if rti == VU.empty
           then return Nothing
           else return $ Just rti)
      (V.enumFromN 0 n)

---Fenwick Tree
aclFenwickTreeData n = do
  ftData <- VUM.replicate n 0
  return (n, ftData)

--TODO:元のコード読めない。。。これでいいんだろうか。。。
aclFenwickTreeAdd ftData@(n, ft) p x
  | p < 0 || n <= p = error
    "aclFenwickTreeAdd:pを0以上でnより小さい値になるように見直してください。"
  | otherwise = aloop ft (p + 1)
  where
    aloop ft p
      | p > n = return ()
      | otherwise = do
        VUM.modify ft (+ x) (p - 1)
        aloop ft (p + (p .&. (-p)))

aclFenwickTreeSum ftData@(n, ft) l r
  | l < 0 || l > r || r > n = error
    "aclFenwickTreeSum:l rを0以上でnより小さい且つ、lがr以下の値になるように見直してください。"
  | otherwise = (-) <$> psum ft r <*> psum ft l
  where
    psum ft r = aloop ft r 0

    aloop ft r s
      | r <= 0 = return s
      | otherwise = do
        ftr <- VUM.read ft (r - 1)
        aloop ft (r - (r .&. (-r))) (s + ftr)

---Math
--TODO:未テスト
aclMathPowMod x n m
  | n < 0 = error
    "aclMathPowMod:nを0以上の値になるように見直してください。"
  | m < 1 = error
    "aclMathPowMod:mを1以上の値になるように見直してください。"
  | otherwise = if m == 1
                then 0
                else aloop n 1 (aclMathInternalSafeMod x m)
  where
    aloop n r y
      | n == 0 = return r
      | otherwise = if (n .&. 1) /= 0
                    then aloop (shiftR n 1) (mul m r y) (mul m y y)
                    else aloop (shiftR n 1) r (mul m y y)

    mul m a b = let im = div (-1) m + 1
                    z = a * b
                    x = shiftR (z * im) 64
                    v = z - x * m
                in if m <= v
                   then v + m
                   else v

--TODO:未テスト
aclMathInternalSafeMod x m =
  let nx = mod x m
  in if nx < 0
     then nx + m
     else nx

--TODO:未テスト
aclMathInvMod x m
  | m < 1 = error
    "aclMathInvMod:mを1以上の値になるように見直してください。"
  | otherwise = let z = aclMathInternalInvGcd x m
                in if fst z == 1
                   then
                     --TODOエラーメッセージ見直し。
                     error "aclMathInvMod:値を見直してください。"
                   else snd z

--TODO:未テスト
aclMathInternalInvGcd a b =
  let na = aclMathInternalSafeMod a b
      (s, t, m0, m1) = aloop b a 0 1
  in if a == 0
     then (b, 0)
     else if m0 < 0
          then (s, m0 + div b s)
          else (s, m0)
  where
    aloop s t m0 m1
      | t == 0 = (s, t, m0, m1)
      | otherwise = let u = div s t
                    in aloop t (s - t * u) m1 (m0 - m1 * u)

--TODO:未テスト
aclMathCrt r m
  | VU.length r /= VU.length m =
    error "aclMathCrt:r mの配列サイズを見直してください。"
  | otherwise = let n = VU.length r
                in aloop r m 0 0 1
  where
    aloop r m i r0 m0
      | i >= VU.length r = (r0, m0)
      | m VU.! i < 1 = error
        "aclMathCrt:mを1以上の値になるように見直してください。"
      | otherwise = let r1 = aclMathInternalSafeMod (r VU.! i) (m VU.! i)
                        m1 = m VU.! i
                    in if m0 >= m1
                       then amethod r m i r0 r1 m0 m1
                       else amethod r m i r1 r0 m1 m0

    amethod r m i r0 r1 m0 m1 =
      let (g, im) = aclMathInternalInvGcd m0 m1
          u1 = div m1 g
          x = mod (mod (div (r1 - r0) g) u1 * im) u1
          nr0 = r0 + x * m0
          nm0 = m0 * u1
      in if mod m0 m1 == 0
         then if mod r0 m1 /= r1
              then (0, 0)
              else aloop r m (i + 1) r0 m0
         else if mod (r1 - r0) g /= 0
              then (0, 0)
              else if nr0 < 0
                   then aloop r m (i + 1) (nr0 + nm0) nm0
                   else aloop r m (i + 1) nr0 nm0

aclMathFloorSum n m a b =
  let (ans1, a1) = am 0 n m a
      (ans2, b1) = bm ans1 n m b
      yMax = div (a1 * n + b1) m
      xMax = yMax * m - b1
  in if yMax == 0
     then ans2
     else ans2
       + (n - div (xMax + a1 - 1) a1) * yMax
       + aclMathFloorSum yMax a1 m (mod (a1 - mod xMax a1) a1)
  where
    am ans n m a = if a >= m
                   then (div ((n - 1) * n * div a m) 2, mod a m)
                   else (ans, a)

    bm ans n m b = if b >= m
                   then (ans + n * div b m, mod b m)
                   else (ans, b)

---MaxFlow
{-aclMaxFlowGraph n = (,,) n <$> VM.replicateM n (VUM.replicate 0 (0, 0, 0))
  <*> VU.thaw VU.empty
-}
aclMaxFlowGraph
  :: Int -> IO (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int))
aclMaxFlowGraph n = do
  graphIni <- VM.replicate n (SQ.empty)
  return (n, graphIni, SQ.empty)

aclMaxFlowAddEdge
  :: (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int))
  -> Int
  -> Int
  -> Int
  -> IO (Int, (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int)))
aclMaxFlowAddEdge graphIniData@(iniN, iniGraph, iniPos) from to cap = if
  | from < 0 || iniN <= from -> error
    "aclMaxFlowAddEdge:fromを0以上nより小さい値になるように見直してください。"
  | to < 0 || iniN <= to -> error
    "aclMaxFlowAddEdge:toを0以上nより小さい値になるように見直してください。"
  | cap < 0 -> error
    "aclMaxFlowAddEdge:capを0以上の値になるように見直してください。"
  | otherwise -> do
    let m = SQ.length iniPos
    graphFrom <- VM.read iniGraph from
    graphTo <- VM.read iniGraph to
    let graphFromSize = SQ.length graphFrom
    let graphToSize = SQ.length graphTo
    VM.write iniGraph from (graphFrom SQ.|> (to, graphToSize, cap))
    VM.write iniGraph to (graphTo SQ.|> (from, graphFromSize, 0))
    return (m, (iniN, iniGraph, iniPos SQ.|> (from, graphFromSize)))

aclMaxFlowConvertIniData
  :: (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int))
  -> IO
    (Int, VM.IOVector (VUM.IOVector (Int, Int, Int)), VUM.IOVector (Int, Int))
aclMaxFlowConvertIniData graphIniData@(iniN, iniGraph, iniPos) = do
  graph <- V.thaw
    =<< (V.generateM
           iniN
           (\i -> do
              seq <- VM.read iniGraph i
              VU.thaw
                $ VU.unfoldr
                  (\x -> let (s SQ.:< sn) = SQ.viewl x
                         in if x == SQ.empty
                            then Nothing
                            else Just (s, sn))
                  seq))
  pos <- VU.thaw
    $ VU.unfoldr
      (\x -> let (s SQ.:< sn) = SQ.viewl x
             in if x == SQ.empty
                then Nothing
                else Just (s, sn))
      iniPos
  return (iniN, graph, pos)

                                                                                --TODO:可変長の可変データどうやって持とう？時間かかりすぎなので最後に見直す。
                                                                                {-aclMaxFlowAddEdge graphData from to cap =
  aclMaxFlowAddAllEdges graphData $ VU.singleton (from, to, cap)

bkaclMaxFlowAddAllEdges graphData@(n, graph, pos) edges = do
  (addPos, addGraphMap) <- VU.foldM
    (\acc@(accPos, accGraphMap) edge@(from, to, cap) -> if
       | from < 0 || n <= from -> error
         "aclMaxFlowAddEdge:fromを0以上nより小さい値になるように見直してください。"
       | to < 0 || n <= to -> error
         "aclMaxFlowAddEdge:toを0以上nより小さい値になるように見直してください。"
       | cap < 0 -> error
         "aclMaxFlowAddEdge:capを0以上の値になるように見直してください。"
       | otherwise -> do
         gFrom <- VM.read graph from
         gTo <- VM.read graph to
         let gFromSize = VUM.length gFrom
             gToSize = VUM.length gTo
             accGFrom = M.findWithDefault [] from accGraphMap
             accGTo = M.findWithDefault [] to accGraphMap
             accGFromSize = length accGFrom
             accGToSize = length accGTo
             sumGFromSize = gFromSize + accGFromSize
             sumGToSize = gToSize + accGToSize
         return
           ( (from, sumGFromSize):accPos
           , M.insert
               to
               ((from, sumGFromSize, 0):accGTo)
               (M.insert from ((to, sumGToSize, cap):accGFrom) accGraphMap)))
    ([], M.empty)
    edges
  nGraph <- V.thaw
    =<< V.mapM
      (\i -> do
         oGraph <- VU.freeze =<< VM.read graph i
         let nGraph = oGraph
               VU.++ (VU.fromList
                      $ reverse (M.findWithDefault [] i addGraphMap))
         VU.thaw nGraph)
      (V.enumFromN 0 n)
  nPos <- VU.thaw =<< ((VU.++ VU.fromList addPos) <$> VU.freeze pos)
  return (n, nGraph, nPos)
-}
aclMaxFlowGetEdge graphData@(n, graph, pos) i =
  let m = VUM.length pos
  in if i < 0 || m <= i
     then error
       "aclMaxFlowAddEdge:iを0以上mより小さい値になるように見直してください。"
     else do
       posi <- VUM.read pos i
       graphi <- VM.read graph (fst posi)
       e@(eTo, eRev, eCap) <- VUM.read graphi (snd posi)
       graphTo <- VM.read graph eTo
       re@(reTo, reRev, reCap) <- VUM.read graphTo eRev
       return (fst posi, eTo, eCap + reCap, reCap)

aclMaxFlowEdges graphData@(n, graph, pos) =
  let m = VUM.length pos
  in VU.mapM (aclMaxFlowGetEdge graphData) $ VU.enumFromN 0 m

aclMaxFlowChangeEdge graphData@(n, graph, pos) i newCap newFlow = do
  let m = VUM.length pos
  if i < 0 || m <= i
    then error
      "aclMaxFlowAddEdge:iを0以上mより小さい値になるように見直してください。"
    else do
      posi <- VUM.read pos i
      graphA <- VM.read graph (fst posi)
      e@(eTo, eRev, eCap) <- VUM.read graphA (snd posi)
      graphB <- VM.read graph eTo
      re@(reTo, reRev, reCap) <- VUM.read graphB eRev
      return ()

aclMaxFlowFlow graphData@(n, graph, pos) s t =
  aclMaxFlowFlowLimit graphData s t maxInt

--TODO: もう無理なんだこれ
--TODO: 元コードのiterはなんのためにあるのかな。0から常にループしてるようにみるけど。
aclMaxFlowFlowLimit graphData@(n, graph, pos) s t flowLimit
  | s < 0 || n <= s = error
    "aclMaxFlowFlow:sを0以上nより小さい値になるように見直してください。"
  | t < 0 || n <= t = error
    "aclMaxFlowFlow:tを0以上nより小さい値になるように見直してください。"
  | otherwise = do
    aloop graph 0
  where
    aloop graph flow =
      if flow >= flowLimit
      then return flow
      else do
        levelIni <- VUM.replicate n (-1) :: IO (VUM.IOVector Int)
        VUM.write levelIni s 0
        level <- bfs graph levelIni (SQ.singleton s)
        levelt <- VUM.read level t
        if levelt == -1
          then return flow
          else do
            nFlow <- bloop graph level flow
            aloop graph nFlow

    bfs graph level sq
      | sq == SQ.empty = return level
      | otherwise = do
        let (sqh SQ.:< sqt) = SQ.viewl sq
        edges <- VM.read graph sqh
        nSq <- cloop level edges 0 sqh sqt
        bfs graph level nSq

    cloop level edges i v sqt = do
      if i >= VUM.length edges
        then return sqt
        else do
          edge@(to, rev, cap) <- VUM.read edges i
          levelTo <- VUM.read level to
          if cap == 0 || levelTo >= 0
            then cloop level edges (i + 1) v sqt
            else do
              levelv <- VUM.read level v
              VUM.write level to (levelv + 1)
              if to == t
                then return SQ.empty
                else cloop level edges (i + 1) v (to SQ.<| sqt)

    bloop graph level flow
      | flow >= flowLimit = return flow
      | otherwise = do
        f <- if t == s
             then return (flowLimit - flow)
             else do
               levelV <- VUM.read level t
               graphV <- VM.read graph t
               dfs graph graphV level 0 levelV t (flowLimit - flow) 0
        if f == 0
          then return flow
          else bloop graph level (flow + f)

    dfs graph graphV level i levelV v up res = do
      let lenGraphV = VUM.length graphV
      if i >= lenGraphV
        then return res
        else do
          edge@(to, rev, cap) <- VUM.read graphV i
          levelTo <- VUM.read level to
          graphTo <- VM.read graph to
          graphToRev@(nTo, nRev, nCap) <- VUM.read graphTo rev
          if levelV <= levelTo || nCap == 0
            then dfs graph graphV level (i + 1) levelV v up res
            else do
              d <- if to == s
                   then do
                     return (min (up - res) nCap)
                   else do
                     dfs
                       graph
                       graphTo
                       level
                       0
                       levelTo
                       to
                       (min (up - res) nCap)
                       0
              if d <= 0
                then dfs graph graphV level (i + 1) levelV v up res
                else do
                  edge@(to2, rev2, cap2) <- VUM.read graphV i
                  graphToRev@(nTo2, nRev2, nCap2) <- VUM.read graphTo rev
                  VUM.write graphV i (to2, rev2, cap2 + d)
                  VUM.write graphTo rev (nTo2, nRev2, nCap2 - d)
                  let nres = res + d
                  if nres == up
                    then return nres
                    else dfs graph graphV level (i + i) levelV v up nres

aclMaxFlowMinCut graphData@(n, graph, pos) s = do
  visited <- VUM.replicate n False
  let sq = SQ.singleton s
  aloop visited sq
  VU.freeze visited
  where
    aloop visited sq
      | sq == SQ.empty = return ()
      | otherwise = do
        let (sqh SQ.:< sqt) = SQ.viewl sq
        VUM.write visited sqh True
        edges <- VM.read graph sqh
        bloop visited edges 0 sq

    bloop visited edges i sq = do
      edge@(to, rev, cap) <- VUM.read edges i
      visitedTo <- VUM.read visited to
      if cap /= 0 && visitedTo == False
        then do
          VUM.write visited to True
          bloop visited edges i (to SQ.<| sq)
        else bloop visited edges i sq
---MinCostFlow後回し
---Convolution


import Data.Bool
main=putStrLn.bool"No""Yes".solve.map read.words=<<getLine
solve[d,t,s]=d<=t*s

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


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

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

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

import qualified Data.ByteString.Char8 as B

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

import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

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

modifyArray a i f = writeArray a i =<< f <$> readArray a i

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = do
	[ d, t, s ] <- readInts
	putStrLn $ which "Yes" "No" $ d <= t * s


-- SPDX-License-Identifier: X11
-- 2020-08-23
-- Takoyaki

module Main where

solve :: [Int] -> Int
solve [n,x,t] = (if n `mod` x == 0
                   then n `div` x
                   else n `div` x + 1) * t
solve _ = error "Failure parsing inputs"

parse :: String -> [Int]
parse = map (read :: String -> Int) . words

main :: IO ()
main = getContents >>= \x -> print . solve . parse $ x

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


main = read <$> getLine >>= (\n -> putStr (if n `mod` 9 ==0 then "Yes" else "No"))

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


module Main where

consecLength :: Eq a => a -> [a] -> Integer
consecLength a xs = maximum $ f 0 a xs
	where   f :: Eq a => Integer -> a -> [a] -> [Integer]
		f _ _ [] = []
		f n a (x:xs)
			| a == x = n + 1 : (f (n + 1) a xs)
			| otherwise = 0 : (f 0 a xs)

main :: IO ()
main = getLine >>= putStrLn . show . consecLength 'R'

Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of consecutive rainy days in the period.

Sample Input 1

RRS

Sample Output 1

2

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


import Control.Monad
import Data.Function
import Data.Char
import Data.List
import Text.Read
import Text.ParserCombinators.ReadPrec

import Data.Ratio

newtype Pair a b = Pair { getPair :: (a, b) }

instance (Read a, Read b) => Read (Pair a b) where
  readPrec = Pair `dot` (,) <$> readPrec <* get <*> readPrec

instance (Show a, Show b) => Show (Pair a b) where
  show (Pair (a, b)) = show a ++ " " ++ show b

readPair :: IO (Int, Int)
readPair = getPair <$> readLn

infixr 8 `dot`
dot :: (c -> d) -> (a -> b -> c) -> a -> b -> d
dot = ((.).(.))

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

solve :: Int -> Int -> Int -> Int
solve x k d
  | x < 0     = solve (-x) k d
  | x > k * d = x - k * d
  | otherwise = _solve x0 (k - k0) d
 where
  k0 = floor $ x % d
  x0 = x - k0 * d

  _solve x k d
    | x < 0     = error "BUG"
    | k >= 2    = _solve x (k `mod` 2) d
    | k == 0    = x
    | k == 1    = d - x

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.


import qualified Data.Vector.Unboxed as V
import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BS
readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getIntList = readIntList <$> BS.getLine

main = do
  [n,k] <- getIntList
  p <- V.fromList . map (+(-1)) <$> getIntList
  c <- V.fromList <$> getIntList
  let acc i = tail $ scanl' (+) 0 $ map ((c V.!).(p V.!)) $ takeWhile (/=i) (iterate (p V.!) (p V.! i)) ++ [i] -- O(n)
      ans i = -- O(n)
        if val > 0
          then
            if rem /= 0
              then num * val + maximum (take (fromIntegral rem) list)
              else (num-1) * val + maximum list
          else maximum list
        where list = acc i
              val = last list
              len = fromIntegral $ length list
              num = k `div` len
              rem = k `mod` len
  print $ maximum $ map ans [0..n-1] -- n * O(n) = O(n^2)

Score : 400 points

Problem Statement

Takahashi will play a game using a piece on an array of squares numbered 1, 2, \cdots, N. Square i has an integer C_i written on it. Also, he is given a permutation of 1, 2, \cdots, N: P_1, P_2, \cdots, P_N.

Now, he will choose one square and place the piece on that square. Then, he will make the following move some number of times between 1 and K (inclusive):

In one move, if the piece is now on Square i (1 \leq i \leq N), move it to Square P_i. Here, his score increases by C_{P_i}.

Help him by finding the maximum possible score at the end of the game. (The score is 0 at the beginning of the game.)

Constraints

2 \leq N \leq 5000

1 \leq K \leq 10^9

1 \leq P_i \leq N

P_i \neq i

P_1, P_2, \cdots, P_N are all different.

-10^9 \leq C_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
P_1 P_2 \cdots P_N
C_1 C_2 \cdots C_N

Output

Print the maximum possible score at the end of the game.

Sample Input 1

5 2
2 4 5 1 3
3 4 -10 -8 8

Sample Output 1

8

When we start at some square of our choice and make at most two moves, we have the following options:

If we start at Square 1, making one move sends the piece to Square 2, after which the score is 4. Making another move sends the piece to Square 4, after which the score is 4 + (-8) = -4.

If we start at Square 2, making one move sends the piece to Square 4, after which the score is -8. Making another move sends the piece to Square 1, after which the score is -8 + 3 = -5.

If we start at Square 3, making one move sends the piece to Square 5, after which the score is 8. Making another move sends the piece to Square 3, after which the score is 8 + (-10) = -2.

If we start at Square 4, making one move sends the piece to Square 1, after which the score is 3. Making another move sends the piece to Square 2, after which the score is 3 + 4 = 7.

If we start at Square 5, making one move sends the piece to Square 3, after which the score is -10. Making another move sends the piece to Square 5, after which the score is -10 + 8 = -2.

The maximum score achieved is 8.

Sample Input 2

2 3
2 1
10 -7

Sample Output 2

13

Sample Input 3

3 3
3 1 2
-1000 -2000 -3000

Sample Output 3

-1000

We have to make at least one move.

Sample Input 4

10 58
9 1 6 7 8 4 3 2 10 5
695279662 988782657 -119067776 382975538 -151885171 -177220596 -169777795 37619092 389386780 980092719

Sample Output 4

29507023469

The absolute value of the answer may be enormous.


import           Control.Monad
import           Data.Array.Unboxed
getIntLine = map read . words <$> getLine
main = do
  [n,k] <- getIntLine
  p <- listArray (1,n) <$> getIntLine :: IO (Array Integer Integer)
  c <- listArray (1,n) <$> getIntLine :: IO (Array Integer Integer)
  let acc i = scanl1 (+) $ map ((c !).(p !)) $ takeWhile (/= i) (tail $ iterate (p !) i) ++ [i] -- O(n)
      ans i = -- O(n)
        if val > 0
          then
            if rem /= 0
              then num * val + maximum (take (fromIntegral rem) list)
              else (num-1) * val + maximum list
          else maximum list
        where list = acc i
              val = last list
              len = fromIntegral $ length list
              num = k `div` len
              rem = k `mod` len
  print $ maximum $ map ans [1..n]


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

import Control.Arrow
import Control.Concurrent
import Control.Monad
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Char8 as C
import Data.Bits
import Data.Complex
import Data.Char
import Data.Function
import Data.Function.HT
import qualified Data.IntMap.Strict as IM
import qualified Data.IntSet as IS
import Data.List
import Data.Monoid
import Data.Ord
import qualified Data.Sequence as Sq
import Data.Vector.Algorithms.Search
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import Debug.Trace
import System.IO

r :: Int -> IO (U.Vector Int)
r n = U.unfoldrN n (C.readInt . C.dropWhile (==' ')) <$> C.getLine

r' :: IO [Int]
r'  =   unfoldr    (C.readInt . C.dropWhile (==' ')) <$> C.getLine

main = do
    [n,k] <- r' :: IO [Int]
    ps <- U.map pred <$> r n
    cs <- r n
    visited <- UM.replicate n False
    loops <- filter (/=[]) <$> (mapM (\f -> findloop f ps cs visited) [0..n-1])
    let sums = map sum loops
    --print $ loops
    let remCs = map (optForLoop k) loops
    print $ maximum $ zipWith re sums remCs

findloop :: Int -> U.Vector Int -> U.Vector Int -> UM.IOVector Bool -> IO [Int]
findloop from ps cs visited = do
    x <- UM.read visited from
    if x then return [] else do
        let resP = (from :) $ takeWhile (/= from) $ tail $ iterate (ps U.!) from
        mapM_ (\a -> UM.write visited a True) resP
        return $ map (\p -> cs U.! p) resP

optForLoop :: Int -> [Int] ->  Int
optForLoop k lp = let remK = if k == length lp then k else k `rem` length lp in
    maximum $ map (kukan lp) [1..remK]

kukan :: [Int] -> Int -> Int
kukan lp len = maximum $ zipWith (-) (drop len (scanl1 (+) (cycle lp))) (scanl1 (+) lp)

re s ku = if s > 0 then s + ku else ku


main = readLn >>= putStrLn . (\x -> if x < 30 then "No" else "Yes")

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


{-# LANGUAGE BangPatterns     #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiWayIf       #-}
import           Control.Monad
import           Control.Monad.ST
import           Control.Monad.State
import           Control.Monad.Trans.State
import           Data.Array.IArray
import           Data.Array.ST
import           Data.Array.Unboxed
import           Data.Bits
import qualified Data.ByteString.Char8     as BS
import           Data.Char
import           Data.Graph
import           Data.Int                  (Int64)
import           Data.List
import           Data.Maybe
import           Data.Proxy
import           Data.Sequence             (Seq, (<|), (><), (|>))
import qualified Data.Sequence             as Seq
import qualified Data.Set                  as S
import           Data.STRef
import qualified Data.Vector               as V
import qualified Data.Vector.Unboxed       as VU
import           Numeric

main :: IO ()
main = do
  [n,d] <- readLnAsListWith unconsInt
  nvec <- readLnAsUVecWith2Tuple unconsInt n

  print $ VU.length $ VU.filter (\x -> x <= d^2) $ VU.map (\(x,y) -> x^2 + y^2) nvec

-- converter
unconsChar :: StateT BS.ByteString Maybe Char
unconsChar = StateT BS.uncons

unconsInt :: StateT BS.ByteString Maybe Int
unconsInt = StateT $ BS.readInt . BS.dropWhile isSpace

unconsInteger :: StateT BS.ByteString Maybe Integer
unconsInteger = StateT $ BS.readInteger . BS.dropWhile isSpace

-- 1D Data
-- for list
readLnAsListWith :: StateT BS.ByteString Maybe a -> IO [a]
readLnAsListWith !st = unfoldr (runStateT st) <$> BS.getLine

-- for boxed array
readLnAsArrayWith :: StateT BS.ByteString Maybe a -> Int -> IO (Array Int a)
readLnAsArrayWith !st !n = listArray (1,n) <$> readLnAsListWith st

-- for unboxed array
readLnAsUArrayInt :: Int -> IO (UArray Int Int)
readLnAsUArrayInt !n = listArray (1,n) <$> readLnAsListWith unconsInt

readLnAsUArrayChar :: Int -> IO (UArray Int Char)
readLnAsUArrayChar !n = listArray (1,n) <$> readLnAsListWith unconsChar

-- for boxed vector
readLnAsVecWith :: StateT BS.ByteString Maybe a -> Int -> IO (V.Vector a)
readLnAsVecWith !st !n = V.unfoldrN n (runStateT st) <$> BS.getLine

-- for unboxed vector
readLnAsUVecWith :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> IO (VU.Vector a)
readLnAsUVecWith !st !n = VU.unfoldrN n (runStateT st) <$> BS.getLine

-- example: 1D tuple vector
readLnAsUVecWith2Tuple :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> IO (VU.Vector (a,a))
readLnAsUVecWith2Tuple !st !n = VU.replicateM n $ (\vec -> (vec VU.! 0, vec VU.! 1)) <$> readLnAsUVecWith st 2

-- 2D Data
-- n: number of lines
-- m: number of values per a line

-- for boxed array
readLnAs2DArrayWith :: StateT BS.ByteString Maybe a -> Int -> Int -> IO (Array (Int,Int) a)
readLnAs2DArrayWith !st !n !m = listArray ((1,1),(n,m)) . unfoldr (runStateT st) . BS.concat <$> replicateM n BS.getLine

-- for boxed vector
readLnAs2DVecWith :: StateT BS.ByteString Maybe a -> Int -> Int -> IO (V.Vector (V.Vector a))
readLnAs2DVecWith !st !n !m = V.replicateM n $ V.unfoldrN m (runStateT st) <$> BS.getLine

-- for unboxed vector
readLnAs2DUVecWith :: VU.Unbox a => StateT BS.ByteString Maybe a -> Int -> Int -> IO (V.Vector (VU.Vector a))
readLnAs2DUVecWith !st !n !m = V.replicateM n $ VU.unfoldrN m (runStateT st) <$> BS.getLine

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

1 \leq N \leq 2\times 10^5

0 \leq D \leq 2\times 10^5

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE NoStarIsType #-}
{-# LANGUAGE ScopedTypeVariables #-}
import Data.Char (isSpace)
import Data.Int (Int64)
import Data.List (unfoldr)
import Control.Monad
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM
import qualified Data.ByteString.Char8 as BS
import qualified Test.QuickCheck as QC
import Data.Proxy
import GHC.TypeNats (Nat, KnownNat, SomeNat(..), someNatVal, natVal, type (^), type (+))
import Control.Exception (assert)

naive :: Int -> Int
naive k | k `rem` 2 == 0 || k `rem` 5 == 0 = -1
        | otherwise = 1 + length (takeWhile (\x -> x `rem` toInteger k /= 0) $ iterate (\x -> x * 10 + 7) 7)

naive2 :: Int -> Int
naive2 k | k `rem` 2 == 0 || k `rem` 5 == 0 = -1
         | otherwise = 1 + length (takeWhile (\x -> x /= 0) $ iterate (\x -> (x * 10 + 7) `rem` k) (7 `rem` k))

prop_n :: QC.Positive Int -> Bool
prop_n (QC.Positive k) = naive2 k == naive k

factorOut3 :: Int -> (Int, Int)
factorOut3 = go 0
  where
    go !acc !n = case n `quotRem` 3 of
                   (q,0) -> go (acc + 1) q
                   _ -> (n, acc)

prop_factorOut3 :: Int -> Int -> Bool
prop_factorOut3 x y = factorOut3 (3^x * (3 * y + 1)) == (3 * y + 1, x)

-- a_0 = 0
-- a_{n+1} = 10 * a_n + 7  mod 9
--         = a_n + 7  mod 9
-- a_n = 7 * n  mod 9
solve3 :: Int -> Int
solve3 threes = 3 ^ threes

solveNot3 :: Int -> Int
solveNot3 1 = 1
solveNot3 m = assert (gcd m 3 == 1) $
              case someNatVal (fromIntegral m) of
                SomeNat (_ :: Proxy m) -> 1 + discreteLogarithm (10 :: IntMod m) (1/10)

-- a_0 = 0
-- a_{n+1} = 10 * a_n + 7
-- a_{n+1} - t = 10 * (a_n + (7 - t) / 10)
-- - t = (7 - t) / 10
-- 0 = (7 + 9 * t) / 10
-- t = -7/9
-- a_{n+1} + 7/9 = 10 * (a_n + (63 + 7) / 90)
-- a_{n+1} + 7/9 = 10 * (a_n + 7/9)
-- (1/10)^{n+1} * (a_{n+1} + 7/9) = (1/10)^n * (a_n + 7/9)
-- (1/10)^n * (a_n + 7/9) = 0 + 7/9 = 7/9
-- a_n + 7/9 = 7/9 * 10^n
-- a_n = 7/9 * (10^n - 1)
-- a_n = 0 <=> 10^n = 1 mod m
solve :: Int -> Int
solve k | k `rem` 2 == 0 || k `rem` 5 == 0 = -1
        | (k', threes) <- factorOut3 k = case k' `quotRem` 7 of
                                           (k'',0) -> lcm (solve3 threes) (solveNot3 k'')
                                           (_,_) -> lcm (solve3 threes) (solveNot3 k')

prop :: QC.Positive Int -> Bool
prop (QC.Positive k) = solve k == naive k

main = do
  k <- readLn @Int
  print $ solve k

--
-- Modular Arithmetic
--

newtype IntMod (m :: Nat) = IntMod { unwrapN :: Int64 } deriving (Eq)

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

instance KnownNat m => Num (IntMod m) where
  t@(IntMod x) + IntMod y
    | x + y >= modulus = IntMod (x + y - modulus)
    | otherwise = IntMod (x + y)
    where modulus = fromIntegral (natVal t)
  t@(IntMod x) - IntMod y
    | x >= y = IntMod (x - y)
    | otherwise = IntMod (x - y + modulus)
    where modulus = fromIntegral (natVal t)
  t@(IntMod x) * IntMod y = IntMod ((x * y) `rem` modulus)
    where modulus = fromIntegral (natVal t)
  fromInteger n = let result = IntMod (fromInteger (n `mod` fromIntegral modulus))
                      modulus = natVal result
                  in result
  abs = undefined; signum = undefined

{-# RULES
"^9/Int" forall x. x ^ (9 :: Int) = let u = x; v = u * u * u in v * v * v
"^9/Integer" forall x. x ^ (9 :: Integer) = let u = x; v = u * u * u in v * v * v
 #-}

fromIntegral_Int64_IntMod :: KnownNat m => Int64 -> IntMod m
fromIntegral_Int64_IntMod n = result
  where
    result | 0 <= n && n < modulus = IntMod n
           | otherwise = IntMod (n `mod` modulus)
    modulus = fromIntegral (natVal result)

{-# RULES
"fromIntegral/Int->IntMod" fromIntegral = fromIntegral_Int64_IntMod . (fromIntegral :: Int -> Int64) :: Int -> IntMod (10^9 + 7)
"fromIntegral/Int64->IntMod" fromIntegral = fromIntegral_Int64_IntMod :: Int64 -> IntMod (10^9 + 7)
 #-}

---

exEuclid :: (Eq a, Integral a) => a -> a -> (a, a, a)
exEuclid !f !g = loop 1 0 0 1 f g
  where loop !u0 !u1 !v0 !v1 !f 0 = (f, u0, v0)
        loop !u0 !u1 !v0 !v1 !f g =
          case divMod f g of
            (q,r) -> loop u1 (u0 - q * u1) v1 (v0 - q * v1) g r

instance KnownNat m => Fractional (IntMod m) where
  recip t@(IntMod x) = IntMod $ case exEuclid x modulus of
    (1,a,_) -> a `mod` modulus
    (-1,a,_) -> (-a) `mod` modulus
    _ -> error "not invertible"
    where modulus = fromIntegral (natVal t)
  fromRational = undefined

-- Properties:
-- * base^(discreteLogarithm base x) == x
-- * let l = discreteLogarithm base x in filter (base^t == x) [0 .. l]) == l
discreteLogarithm :: KnownNat m => IntMod m -> IntMod m -> Int
discreteLogarithm base x = go 0 1
  where
    -- Naive algorithm
    go n y | y == x = n
           | otherwise = go (n + 1) (y * base)

Score : 300 points

Problem Statement

Takahashi loves the number 7 and multiples of K.

Where is the first occurrence of a multiple of K in the sequence 7,77,777,\ldots? (Also see Output and Sample Input/Output below.)

If the sequence contains no multiples of K, print -1 instead.

Constraints

1 \leq K \leq 10^6

K is an integer.

Input

Input is given from Standard Input in the following format:

K

Output

Print an integer representing the position of the first occurrence of a multiple of K. (For example, if the first occurrence is the fourth element of the sequence, print 4.)

Sample Input 1

101

Sample Output 1

4

None of 7, 77, and 777 is a multiple of 101, but 7777 is.

Sample Input 2

2

Sample Output 2

-1

All elements in the sequence are odd numbers; there are no multiples of 2.

Sample Input 3

999983

Sample Output 3

999982


{-# LANGUAGE BangPatterns #-}
import           Control.Exception           (assert)
import           Control.Monad
import           Control.Monad.Primitive
import qualified Control.Monad.ST            as ST
import qualified Data.Array.IO               as IO
import qualified Data.Array.ST               as ST
import qualified Data.Array.Unboxed          as A
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Foldable
import           Data.List
import qualified Data.Map.Strict             as Map
import           Data.Maybe
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as Set
import qualified Data.Vector                 as VB
import qualified Data.Vector.Mutable         as VBM
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM
import           Debug.Trace

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
getIntVec n = V.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

readInteger = fst . fromJust . BS.readInteger
readIntegerList = map readInteger . BS.words
getInteger = readInteger <$> BS.getLine
getIntegerList = readIntegerList <$> BS.getLine

inf :: Int
inf = 10^18

data Mode = UpdateLow | UpdateHigh deriving Eq

main = do
  n <- getInt
  as <- getIntList

  let solve (b:bs) x mode stocks money
        | mode == UpdateLow && b <= x = solve bs b mode stocks money
        | mode == UpdateLow && b >  x =
          let newStocks = money `div` x
              money' = money - x * newStocks
          in
            solve bs b UpdateHigh (stocks + newStocks) money'
        | mode == UpdateHigh && b >= x = solve bs b mode stocks money
        | otherwise =
          let money' = money + stocks * x
          in
            solve bs b UpdateLow 0 money'
      solve [] x mode stocks money = money + x * stocks

  print $ solve as inf UpdateLow 0 1000

Score: 400 points

Problem Statement

To become a millionaire, M-kun has decided to make money by trading in the next N days. Currently, he has 1000 yen and no stocks - only one kind of stock is issued in the country where he lives.

He is famous across the country for his ability to foresee the future. He already knows that the price of one stock in the next N days will be as follows:

A_1 yen on the 1-st day, A_2 yen on the 2-nd day, ..., A_N yen on the N-th day.

In the i-th day, M-kun can make the following trade any number of times (possibly zero), within the amount of money and stocks that he has at the time.

Buy stock: Pay A_i yen and receive one stock.

Sell stock: Sell one stock for A_i yen.

What is the maximum possible amount of money that M-kun can have in the end by trading optimally?

Constraints

2 \leq N \leq 80

100 \leq A_i \leq 200

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the maximum possible amount of money that M-kun can have in the end, as an integer.

Sample Input 1

7
100 130 130 130 115 115 150

Sample Output 1

1685

In this sample input, M-kun has seven days of trading. One way to have 1685 yen in the end is as follows:

Initially, he has 1000 yen and no stocks.

Day 1: Buy 10 stocks for 1000 yen. Now he has 0 yen.

Day 2: Sell 7 stocks for 910 yen. Now he has 910 yen.

Day 3: Sell 3 stocks for 390 yen. Now he has 1300 yen.

Day 4: Do nothing.

Day 5: Buy 1 stock for 115 yen. Now he has 1185 yen.

Day 6: Buy 10 stocks for 1150 yen. Now he has 35 yen.

Day 7: Sell 11 stocks for 1650 yen. Now he has 1685 yen.

There is no way to have 1686 yen or more in the end, so the answer is 1685.

Sample Input 2

6
200 180 160 140 120 100

Sample Output 2

1000

In this sample input, it is optimal to do nothing throughout the six days, after which we will have 1000 yen.

Sample Input 3

2
157 193

Sample Output 3

1216

In this sample input, it is optimal to buy 6 stocks in Day 1 and sell them in Day 2, after which we will have 1216 yen.


main = do
  x <- readLn
  putStr $ unlines  $ map (\n-> show . length $ [(x,y,z) | x <- [1.. sqrt n], y<- [1..sqrt n], z<- [1..sqrt n], (x^2+y^2+z^2+x*y+y*z+z*x)==n]) [1..x]

Score : 300 points

Problem Statement

Let f(n) be the number of triples of integers (x,y,z) that satisfy both of the following conditions:

1 \leq x,y,z

x^2 + y^2 + z^2 + xy + yz + zx = n

Given an integer N, find each of f(1),f(2),f(3),\ldots,f(N).

Constraints

All values in input are integers.

1 \leq N \leq 10^4

Input

Input is given from Standard Input in the following format:

N

Output

Print N lines. The i-th line should contain the value f(i).

Sample Input 1

20

Sample Output 1

0
0
0
0
0
1
0
0
0
0
3
0
0
0
0
0
3
3
0
0

For n=6, only (1,1,1) satisfies both of the conditions. Thus, f(6) = 1.

For n=11, three triples, (1,1,2), (1,2,1), and (2,1,1), satisfy both of the conditions. Thus, f(6) = 3.

For n=17, three triples, (1,2,2), (2,1,2), and (2,2,1), satisfy both of the conditions. Thus, f(17) = 3.

For n=18, three triples, (1,1,3), (1,3,1), and (3,1,1), satisfy both of the conditions. Thus, f(18) = 3.


import           Control.Monad
import           Data.List

main :: IO ()
main = do
  n <- readLn
  jList <- replicateM n getLine
  let
    app :: [String] -> [(String, Int)]
    app jl = map (\x -> (x, count x jl)) ["AC", "WA", "TLE", "RE"]
      where
        count :: String -> [String] -> Int
        count _ [] = 0
        count str (x:xs) = if str == x then 1 + (count str xs) else count str xs
    afterApp = app jList
  mapM_ (\x -> putStrLn $ (fst x) ++ " x " ++ (show $ snd x)) afterApp

Score : 200 points

Problem Statement

Takahashi is participating in a programming contest called AXC002, and he has just submitted his code to Problem A.

The problem has N test cases.

For each test case i (1\leq i \leq N), you are given a string S_i representing the verdict for that test case. Find the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively.

See the Output section for the output format.

Constraints

1 \leq N \leq 10^5

S_i is AC, WA, TLE, or RE.

Input

Input is given from Standard Input in the following format:

N
S_1
\vdots
S_N

Output

Let C_0, C_1, C_2, and C_3 be the numbers of test cases for which the verdict is AC, WA, TLE, and RE, respectively. Print the following:

AC x C_0
WA x C_1
TLE x C_2
RE x C_3

Sample Input 1

6
AC
TLE
AC
AC
WA
TLE

Sample Output 1

AC x 3
WA x 1
TLE x 2
RE x 0

We have 3, 1, 2, and 0 test case(s) for which the verdict is AC, WA, TLE, and RE, respectively.

Sample Input 2

10
AC
AC
AC
AC
AC
AC
AC
AC
AC
AC

Sample Output 2

AC x 10
WA x 0
TLE x 0
RE x 0


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

readInt = fst . fromJust . BS.readInteger
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

solve p = h + t
  where
    h = head p
    t = (* 2) $ sum $ take (length p `div` 2) $ tail p

main = do
  n  <- getInt
  p <- getIntList
  let p' = (sortBy . flip) compare p
  putStr $ show $ solve p'

Score: 400 points

Problem Statement

Quickly after finishing the tutorial of the online game ATChat, you have decided to visit a particular place with N-1 players who happen to be there. These N players, including you, are numbered 1 through N, and the friendliness of Player i is A_i.

The N players will arrive at the place one by one in some order. To make sure nobody gets lost, you have set the following rule: players who have already arrived there should form a circle, and a player who has just arrived there should cut into the circle somewhere.

When each player, except the first one to arrive, arrives at the place, the player gets comfort equal to the smaller of the friendliness of the clockwise adjacent player and that of the counter-clockwise adjacent player. The first player to arrive there gets the comfort of 0.

What is the maximum total comfort the N players can get by optimally choosing the order of arrivals and the positions in the circle to cut into?

Constraints

All values in input are integers.

2 \leq N \leq 2 \times 10^5

1 \leq A_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \dots A_N

Output

Print the maximum total comfort the N players can get.

Sample Input 1

4
2 2 1 3

Sample Output 1

7

By arriving at the place in the order Player 4, 2, 1, 3, and cutting into the circle as shown in the figure, they can get the total comfort of 7.

They cannot get the total comfort greater than 7, so the answer is 7.

Sample Input 2

7
1 1 1 1 1 1 1

Sample Output 2

6


{-# LANGUAGE MultiWayIf #-}

module Main where
import           Prelude
import           Control.Monad
import           Data.Monoid
import qualified Data.Array                    as A
import qualified Data.Array.IO                 as AIO
import qualified Data.Array.Unboxed            as AU
import qualified Data.ByteString               as BS
import qualified Data.ByteString.Char8         as BSC8
import           Data.Char
import           Data.List
import qualified Data.Map.Strict               as M
import           Data.Maybe
import           Data.Ord
import qualified Data.Set                      as S
import qualified Data.Vector                   as V
import           Data.Vector.Algorithms.Search
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM
import           Debug.Trace
--import qualified Data.Heap                     as H
import qualified Data.Sequence                 as SQ
import qualified Data.Graph.Inductive.PatriciaTree
                                               as G
import qualified Data.Graph.Inductive.Graph    as G
import           Data.Int
import           Data.Bits

main = do
  --aN       <- getI
  --[aA, aB] <- getIL
  --aS       <- getLine
  aN <- getI
  aA <- VU.fromList . sortBy (comparing Down) <$> getIL

  let leng = VU.length aA :: Int
  let aaa  = div leng 2 :: Int
  let bbb = VU.fromList $ if odd leng
        then scanl1 (\acc x -> mod (acc + x) leng) $replicate leng aaa
        else scanl1 (\acc x -> mod (acc + x) leng)
                    $take
                    leng
                    $cycle
                    [aaa - 1, aaa]

  point <- VUM.replicate aN 0 :: IO (VUM.IOVector Int)

  mapM_
    (\x -> do
      let target = bbb VU.! (x+1)

      VUM.write point (target) (aA VU.! x)
    )
    [0 .. leng -2 ]

  pointF <- VU.freeze point
  let ans = VU.foldl (+) 0 pointF
  print ans
  return ()
{-
hMaxPoint :: Int
hMaxPoint = 101
hMaximum :: H.Heap Int -> Int
hMaximum h = hMaxPoint - (H.minimum h)
hInsertMax :: Int -> H.Heap Int -> H.Heap Int
hInsertMax x = H.insert (hMaxPoint - x)
hDeleteMax :: H.Heap Int -> H.Heap Int
hDeleteMax = H.deleteMin
-}

{-
aroundSquare y x h w =
  [ aYX
  | aYX@(aY, aX) <- [(y - 1, x), (y, x - 1), (y + 1, x), (y, x + 1), (y, x)]
  , aY >= 0
  , aY <= (h - 1)
  , aX >= 0
  , aX <= (w - 1)
  ]
-}

splitReadBSC8 :: BSC8.ByteString -> [Int]
splitReadBSC8 bs =
  let (bs1, newBs) = BSC8.splitAt 1 bs
  in  if newBs == BSC8.empty
        then [test $ BSC8.readInt bs1]
        else (test $ BSC8.readInt bs1) : (splitReadBSC8 newBs)
  where test (Just (i, _)) = i

read2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> IO Char
read2DimChar vec y x = do
  vecY <- VM.read vec y
  VUM.read vecY x
write2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> Char -> IO ()
write2DimChar vec y x t = do
  vecY <- VM.read vec y
  VUM.write vecY x t

readTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> IO Int
readTwoDimVec vec y x = do
  vecY <- VM.read vec y
  VUM.read vecY x
writeTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> Int -> IO ()
writeTwoDimVec vec y x t = do
  vecY <- VM.read vec y
  VUM.write vecY x t

getVUI :: IO (VU.Vector Int)
getVUI = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine

getRepVUI :: Int -> IO (VU.Vector Int)
getRepVUI n =
  VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace)
    .   BSC8.unlines
    <$> replicateM n BSC8.getLine

getVS :: IO (V.Vector Char)
getVS = V.fromList <$> getLine

getVUC :: IO (VU.Vector Char)
getVUC = VU.fromList <$> getLine

readI :: BSC8.ByteString -> Int
readI = fst . fromJust . BSC8.readInt

readIL :: BSC8.ByteString -> [Int]
readIL = map readI . BSC8.words

readIT2 :: BSC8.ByteString -> (Int, Int)
readIT2 bs =
  let words = BSC8.words bs in (readI $ head words, readI $ last words)

getI :: IO Int
getI = readI <$> BSC8.getLine

getIL :: IO [Int]
getIL = readIL <$> BSC8.getLine

getIT2 :: IO (Int, Int)
getIT2 = readIT2 <$> BSC8.getLine

getIT2Order :: IO (Int, Int)
getIT2Order =
  getIL >>= \x@[xz, xo] -> if xz > xo then return (xo, xz) else return (xz, xo)

getNIS :: Int -> IO [(Int, BSC8.ByteString)]
getNIS 0 = return []
getNIS n = do
  [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
  next         <- getNIS (n - 1)
  return ((readI aFst, aSnd) : next)

il2Words :: [Int] -> String
il2Words = unwords . map show

il2Lines :: [Int] -> String
il2Lines = unlines . map show

p :: Int -> Int
p x = x - 1

--modNum = 10 ^ 9 + 7
--modulus = 1000000007
modulus = 2019

newtype MInt = M Int

instance Num MInt where
  (M a) + (M b) = M $ mod (a + b) modulus

  (M a) - (M b) = M $ mod (a - b) modulus

  (M a) * (M b) = M $ mod (a * b) modulus

  fromInteger a = M $ mod (fromInteger a) modulus

  abs (M a) = M $ abs a

  signum (M a) = M $ signum a

instance Show MInt where
  show (M a) = show (mod a modulus)

int2MInt :: Int -> MInt
int2MInt a = M (mod a modulus)

mInt2Int :: MInt -> Int
mInt2Int (M a) = a

{-
factsMod :: V.Vector MInt
factsMod = V.scanl (\acc x -> M x * acc) 1 $ V.generate 2000000 (+ 1)

factMod :: Int -> MInt
factMod = (factsMod V.!)
-}

factMod :: Int -> MInt
factMod n | n == 0    = 1
          | n == 1    = 1
          | otherwise = M n * (factMod (n - 1))

factDivMod :: Int -> Int -> MInt
factDivMod n k | n == k    = M 1
               | otherwise = M n * (factDivMod (n - 1) k)

powMod :: MInt -> MInt -> MInt
powMod n mK@(M k) | k == 0       = M 1
                  | k == 1       = n
                  | mod k 2 == 0 = powMod (n ^ 2) (M (div k 2))
                  | otherwise    = n * powMod (n ^ 2) (M (div k 2))

invMod :: MInt -> MInt
invMod (M 0) = error "inverse of 0"
invMod x     = powMod x (M (modulus - 2))

{-
combiMod :: Int -> Int -> MInt
combiMod n k
  | n < 0 || k < 0 || k > n = 0
  | otherwise = factMod n * invMod (factMod (n - k)) * invMod (factMod k)
-}
combiMod :: Int -> Int -> MInt
combiMod n k | n < 0 || k < 0 || k > n = 0
             | k > n - k = factDivMod n k * invMod (factMod (n - k))
             | otherwise = factDivMod n (n - k) * invMod (factMod k)

combi :: Int -> Int -> Int
combi n k | n < 0 || k < 0 || k > n = 0
          | k == n                  = 1
          | otherwise               = div (div (fact n) (fact (n - k))) (fact k)

{-w
primes :: Integral a => [a]
primes = map fromIntegral $ [2, 3] ++ primes'
 where
  primes' = [5] ++ f 1 7 primes'
  f m s (p : ps) = [ n | n <- ns, gcd m n == 1 ] ++ f (m * p) (p * p) ps
    where ns = [ x + y | x <- [s, s + 6 .. p * p - 2], y <- [0, 4] ]

prime n = primes !! n
primes = sieve [2 ..]
sieve (p : xs) = p : sieve [ x | x <- xs, x `mod` p /= 0 ]
-}
fact :: Int -> Int
fact 0         = 1
fact n | n > 0 = n * fact (n - 1)

knappsackWDP :: Int -> [(Int, Int)] -> VU.Vector Int
knappsackWDP maxW [] = VU.replicate (maxW + 1) 0
knappsackWDP maxW ((w, v) : xs) =
  let tailDP = knappsackWDP maxW xs
  in  VU.generate (maxW + 1) $ \i -> if w <= i
        then max (tailDP VU.! i) (tailDP VU.! (i - w) + v)
        else tailDP VU.! i

knappsackVDP :: Int -> Int -> Int -> [(Int, Int)] -> VU.Vector Int
knappsackVDP maxW maxV n [] = VU.cons 0 $ VU.replicate (n * maxV) maxW
knappsackVDP maxW maxV n ((w, v) : xs) =
  let tailDP = knappsackVDP maxW maxV n xs
  in  VU.generate (n * maxV + 1) $ \i -> if v <= i
        then min (tailDP VU.! i) (tailDP VU.! (i - v) + w)
        else tailDP VU.! i

knappsackMinVol
  :: AIO.IOArray (Int, Int) Int
  -> VU.Vector Int
  -> VU.Vector Int
  -> Int
  -> Int
  -> IO Int
knappsackMinVol dp volumeVec valueVec dpSize maxVolume = do
  mapM_
    (\i -> mapM_
      (\v -> do
        let volume = volumeVec VU.! i
            value  = valueVec VU.! i
        newdp <- if (v + value) > dpSize
          then AIO.readArray dp (i, v)
          else do
            dpIVm <- AIO.readArray dp (i, v + value)
            dpIV  <- AIO.readArray dp (i, v)
            return (min (dpIVm - volume) dpIV)
        AIO.writeArray dp (i + 1, v) newdp
      )
      (reverse [0 .. dpSize])
    )
    [0 .. VU.length valueVec - 1]
  foldM
    (\acc x -> do
      num <- AIO.readArray dp (VU.length volumeVec, x)
      return $ if num <= maxVolume then x else acc
    )
    0
    [0 .. dpSize]

lcsTable :: BS.ByteString -> BS.ByteString -> V.Vector (VU.Vector Int)
lcsTable xs ys = V.scanl step (VU.replicate (m + 1) 0) xs'
 where
  n   = BS.length xs
  m   = BS.length ys
  xs' = V.generate n $ BSC8.index xs :: V.Vector Char
  ys' = VU.generate m $ BSC8.index ys :: VU.Vector Char
  step :: VU.Vector Int -> Char -> VU.Vector Int
  step v x = VU.scanl innerStep 0 (VU.zip3 v (VU.tail v) ys')
   where
    innerStep :: Int -> (Int, Int, Char) -> Int
    innerStep a (b, c, y) | x == y    = 1 + b
                          | otherwise = max a c
{-
main = do
xs <- BS.getLine
ys <- BS.getLine
print $ VU.last $ V.last $ lcsTable xs ys
-}

myFilter :: (a -> Bool) -> [a] -> ([a], [a])
myFilter _pred [] = ([], [])
myFilter pred (x : xs)
  | pred x    = let (l, r) = myFilter pred xs in (x : l, r)
  | otherwise = let (l, r) = myFilter pred xs in (l, x : r)

--UnionFindデータ構造
type UF_PARENT = VUM.IOVector Int
type UF_RANK = VUM.IOVector Int
type UF = (UF_PARENT, UF_RANK)
uf_makeSet :: Int -> IO UF
uf_makeSet n = do
  parent <- VU.thaw $ VU.generate n id
  rank   <- VUM.replicate n 0
  return (parent, rank)
uf_union :: UF -> Int -> Int -> IO ()
uf_union unionFind@(parents, ranks) x y = do
  xRoot     <- uf_find unionFind x
  yRoot     <- uf_find unionFind y
  xRootRank <- VUM.read ranks xRoot
  yRootRank <- VUM.read ranks yRoot
  if
    | xRootRank > yRootRank -> VUM.write parents yRoot xRoot
    | xRootRank < yRootRank -> VUM.write parents xRoot yRoot
    | xRoot /= yRoot -> do
      VUM.write parents yRoot xRoot
      VUM.write ranks xRoot (xRootRank + 1)
    | otherwise -> return ()

uf_find :: UF -> Int -> IO Int
uf_find unionFind@(parents, ranks) x = do
  xParent <- VUM.read parents x
  if xParent == x
    then return x
    else do
      xRootParent <- uf_find unionFind xParent
      VUM.write parents x xRootParent
      return xRootParent

--UnDirectedGraph(無向グラフ)データ構造
type UDG = M.Map Int [Int]
list2UDG :: [(Int, Int)] -> M.Map Int [Int]
list2UDG = foldl
  (\acc x ->
    let lr = M.insertWith (++) (fst x) [snd x] acc
    in  M.insertWith (++) (snd x) [fst x] lr
  )
  M.empty


main = do
    putStrLn.show.solve.read=<<getLine
solve a = a + a*a + a*a*a

Score : 100 points

Problem Statement

Given an integer a as input, print the value a + a^2 + a^3.

Constraints

1 \leq a \leq 10

a is an integer.

Input

Input is given from Standard Input in the following format:

a

Output

Print the value a + a^2 + a^3 as an integer.

Sample Input 1

2

Sample Output 1

14

When a = 2, we have a + a^2 + a^3 = 2 + 2^2 + 2^3 = 2 + 4 + 8 = 14.

Print the answer as an input. Outputs such as 14.0 will be judged as incorrect.

Sample Input 2

10

Sample Output 2

1110


import Control.Monad
main :: IO ()
main = do
    [s,t] <- replicateM 2 getLine
    print $ sum $ zipWith (\x y -> if x /= y then 1 else 0) s t

Score : 200 points

Problem Statement

Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so.

Operation: Choose one character of S and replace it with a different character.

Constraints

S and T have lengths between 1 and 2\times 10^5 (inclusive).

S and T consists of lowercase English letters.

S and T have equal lengths.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the answer.

Sample Input 1

cupofcoffee
cupofhottea

Sample Output 1

4

We can achieve the objective in four operations, such as the following:

First, replace the sixth character c with h.

Second, replace the eighth character f with t.

Third, replace the ninth character f with t.

Fourth, replace the eleventh character e with a.

Sample Input 2

abcde
bcdea

Sample Output 2

5

Sample Input 3

apple
apple

Sample Output 3

0

No operations may be needed to achieve the objective.


import Data.Char

main = getLine >>= putStrLn.judge.isUpper.head

judge True = "A"
judge False = "a"

Score : 100 points

Problem Statement

An uppercase or lowercase English letter \alpha will be given as input.
If \alpha is uppercase, print A; if it is lowercase, print a.

Constraints

\alpha is an uppercase (A - Z) or lowercase (a - z) English letter.

Input

Input is given from Standard Input in the following format:

α

Output

If \alpha is uppercase, print A; if it is lowercase, print a.

Sample Input 1

B

Sample Output 1

A

B is uppercase, so we should print A.

Sample Input 2

a

Sample Output 2

a

a is lowercase, so we should print a.


{-# LANGUAGE BangPatterns #-}
import           Control.Exception           (assert)
import           Control.Monad
import           Control.Monad.Primitive
import qualified Control.Monad.ST            as ST
import qualified Data.Array.IO               as IO
import qualified Data.Array.ST               as ST
import qualified Data.Array.Unboxed          as A
import           Data.Bits
import qualified Data.ByteString.Char8       as BS
import           Data.Char
import           Data.Foldable
import           Data.List
import qualified Data.Map.Strict             as Map
import           Data.Maybe
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as Set
import qualified Data.Vector                 as VB
import qualified Data.Vector.Mutable         as VBM
import qualified Data.Vector.Unboxed         as V
import qualified Data.Vector.Unboxed.Mutable as VM
import           Debug.Trace

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
getIntVec n = V.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine

readInteger = fst . fromJust . BS.readInteger
readIntegerList = map readInteger . BS.words
getInteger = readInteger <$> BS.getLine
getIntegerList = readIntegerList <$> BS.getLine

inf :: Int
inf = 10^18

main = do
  (a:_) <- getLine
  if isLower a
    then putStrLn "a"
    else putStrLn "A"


import Data.Bool
import Data.Char
main = putChar . bool 'A' 'a' . isLower =<< getChar


import Data.List

main = do
    _:k:_ <- map read . words <$> getLine
    ps <- map read . words <$> getLine
    print $ solve k ps

solve :: Int -> [Int] -> Int
solve k = sum . take k . sort

Score : 200 points

Problem Statement

A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)

Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.

Constraints

1 \leq K \leq N \leq 1000

1 \leq p_i \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 \ldots p_N

Output

Print an integer representing the minimum possible total price of fruits.

Sample Input 1

5 3
50 100 80 120 80

Sample Output 1

210

This shop sells Fruit 1, 2, 3, 4, and 5 for 50 yen, 100 yen, 80 yen, 120 yen, and 80 yen, respectively.

The minimum total price for three kinds of fruits is 50 + 80 + 80 = 210 yen when choosing Fruit 1, 3, and 5.

Sample Input 2

1 1
1000

Sample Output 2

1000


import Data.List
import Data.Maybe

main = interact $ show . sol . read

sol = reverse . unfoldr f . pred

f x = if x<0 then Nothing else Just (α!!r,q-1)
  where (q,r) = x `quotRem` 26

α = ['a'..'z']

Score : 300 points

Problem Statement

1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:

the dogs numbered 1,2,\cdots,26 were respectively given the names a, b, ..., z;

the dogs numbered 27,28,29,\cdots,701,702 were respectively given the names aa, ab, ac, ..., zy, zz;

the dogs numbered 703,704,705,\cdots,18277,18278 were respectively given the names aaa, aab, aac, ..., zzy, zzz;

the dogs numbered 18279,18280,18281,\cdots,475253,475254 were respectively given the names aaaa, aaab, aaac, ..., zzzy, zzzz;

the dogs numbered 475255,475256,\cdots were respectively given the names aaaaa, aaaab, ...;

and so on.

To sum it up, the dogs numbered 1, 2, \cdots were respectively given the following names:

a, b, ..., z, aa, ab, ..., az, ba, bb, ..., bz, ..., za, zb, ..., zz, aaa, aab, ..., aaz, aba, abb, ..., abz, ..., zzz, aaaa, ...

Now, Roger asks you:

"What is the name for the dog numbered N?"

Constraints

N is an integer.

1 \leq N \leq 1000000000000001

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer to Roger's question as a string consisting of lowercase English letters.

Sample Input 1

2

Sample Output 1

b

Sample Input 2

27

Sample Output 2

aa

Sample Input 3

123456789

Sample Output 3

jjddja


main=readLn>>=putStr.reverse.f
f 0=""
f n=(toEnum$(n-1)`mod`26+97):(f$div(n-1)26)


import qualified Data.Vector.Unboxed as V
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.List
import Data.Maybe

main = do
  n <- getInt
  putStrLn $ solve n

solve n = go n []
  where
    go n cs
	  | n == 0 = cs
      | otherwise = let (p, q) = divMod n 26 in go p (chr (q - 1 + ord 'a') : cs)

getInt :: IO Int
getInt = readLn

second :: (b -> c) -> (a, b) -> (a, c)
second f (a, b) = (a, f b)

readInt :: BS.ByteString -> Maybe (Int, BS.ByteString)
readInt = fmap (second BS.tail) . BS.readInt

readIntVec :: Int -> IO (V.Vector Int)
readIntVec n = V.unfoldrN n readInt <$> BS.getLine

readIntList :: IO [Int]
readIntList = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine

readIntPair :: IO (Int, Int)
readIntPair = do
  v <- readIntVec 2
  return (v V.! 0, v V.! 1)


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE BangPatterns #-}

-- Default Imports

import Control.Monad
import Control.Monad.ST
import Control.Monad.Trans.Class

import qualified Control.Monad.Reader as Reader
import Control.Monad.Reader (Reader, ReaderT, runReader, runReaderT)

import qualified Data.Array.MArray as MArray
import qualified Data.Array.ST as STArray
import Data.Array.ST (STArray, STUArray, runSTArray, runSTUArray)
import Data.Ix (Ix)

import qualified Data.Bits as Bits
import Data.Bits ((.&.), (.|.))

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)

import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map)
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import Data.Set (Set)

import qualified Data.Vector as Vector
import qualified Data.Vector.Generic as GVector
import qualified Data.Vector.Mutable as MVector
import Data.Vector.Mutable (STVector)
import qualified Data.Vector.Unboxed as UVector

import Numeric

import Debug.Trace
-- ----------

-- Custom Import Here

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

-- Default Definitions

type Vector = Vector.Vector
-- type GVector = GVector.Vector
type UVector = UVector.Vector

readIntToList :: ByteString -> [Int]
readIntToList = List.unfoldr (fmap (second $ BS.dropWhile Char.isSpace) . BS.readInt)

readToList :: Read a => ByteString -> [a]
readToList = List.unfoldr $ fmap (mapTaken . mapRemain) . span' (not . Char.isSpace)
	where
		mapTaken  = first $ read . BS.unpack
		mapRemain = second $ BS.dropWhile Char.isSpace
		span' pred s
			| BS.null taken = Nothing
			| otherwise     = Just (taken, remain')
			where
				(taken, remain) = BS.span pred s
				remain' = BS.dropWhile Char.isSpace remain

readToListN :: Read a => Int -> ByteString -> [a]
readToListN n = take n . readToList

readIntToVector :: ByteString -> Vector Int
readIntToVector = Vector.unfoldr (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToUVector :: ByteString -> UVector.Vector Int
readIntToUVector = UVector.unfoldr (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToVectorN :: Int -> ByteString -> Vector.Vector Int
readIntToVectorN n = Vector.unfoldrN n (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

readIntToUVectorN :: Int -> ByteString -> UVector.Vector Int
readIntToUVectorN n = UVector.unfoldrN n (fmap stripRemain . BS.readInt)
	where stripRemain = second $ BS.dropWhile Char.isSpace

first :: (a -> a') -> (a, b) -> (a', b)
first f (a, b) = (f a, b)

second :: (b -> b') -> (a, b) -> (a, b')
second f (a, b) = (a, f b)

average :: Fractional a => [a] -> a
average xs = sum xs / (fromIntegral . length) xs

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

genName :: Int -> String
genName 0 = ""
genName n = Char.chr (Char.ord 'a' + fromIntegral (n `mod` 26) - 1) : genName (n `div` 26)

main :: IO ()
main = do
	n <- read <$> getLine
	putStrLn $ reverse $ genName n


import Data.List

main :: IO ()
main = do
    _ <- getLine
    xs <- map (read :: String -> Int) . words <$> getLine
    q <- readLn
    let xs' = [(head ys, length ys) | ys <- group xs]
    analyze q xs'
        where
            analyze n xs = do
                [b, c] <- map read . words <$> getLine
                let replicated = repTarget b c xs
                    merged = merge b 0 xs
                putStrLn $ show $ sum $ map (\x -> fst x * snd x) replicated
                if n == 1
                    then return ()
                    else analyze (n - 1) replicated
            repTarget _ _ [] = []
            repTarget cur next ((b, c):xs)
                | b == cur = (next, c) : xs
                | otherwise = (b, c) : (repTarget cur next xs)
            merge v l [] = (v, l) : []
            merge v l ((b, c):xs)
                | v == b = merge v (l + c) xs
                | otherwise = (b, c) : (merge v l xs)

Score : 400 points

Problem Statement

You have a sequence A composed of N positive integers: A_{1}, A_{2}, \cdots, A_{N}.

You will now successively do the following Q operations:

In the i-th operation, you replace every element whose value is B_{i} with C_{i}.

For each i (1 \leq i \leq Q), find S_{i}: the sum of all elements in A just after the i-th operation.

Constraints

All values in input are integers.

1 \leq N, Q, A_{i}, B_{i}, C_{i} \leq 10^{5}

B_{i} \neq C_{i}

Input

Input is given from Standard Input in the following format:

N
A_{1} A_{2} \cdots A_{N}
Q
B_{1} C_{1}
B_{2} C_{2}
\vdots
B_{Q} C_{Q}

Output

Print Q integers S_{i} to Standard Output in the following format:

S_{1}
S_{2}
\vdots
S_{Q}

Note that S_{i} may not fit into a 32-bit integer.

Sample Input 1

4
1 2 3 4
3
1 2
3 4
2 4

Sample Output 1

11
12
16

Initially, the sequence A is 1,2,3,4.

After each operation, it becomes the following:

2, 2, 3, 4

2, 2, 4, 4

4, 4, 4, 4

Sample Input 2

4
1 1 1 1
3
1 2
2 1
3 5

Sample Output 2

8
4
4

Note that the sequence A may not contain an element whose value is B_{i}.

Sample Input 3

2
1 2
3
1 100
2 100
100 1000

Sample Output 3

102
200
2000


import Data.Bits
import qualified Data.ByteString.Char8 as C
import qualified Data.Vector.Unboxed as U

main = C.interact $ put . sol . get

get = U.unfoldr (C.readInt . C.dropWhile (<'0'))

put = C.unwords . fmap (C.pack . show) . U.toList

sol v = U.map (xor p) u
  where
  u = U.tail v
  p = U.foldr1 xor u

Score : 500 points

Problem Statement

There are N Snuke Cats numbered 1, 2, \ldots, N, where N is even.

Each Snuke Cat wears a red scarf, on which his favorite non-negative integer is written.

Recently, they learned the operation called xor (exclusive OR).

What is xor?

For n non-negative integers x_1, x_2, \ldots, x_n, their xor, x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is defined as follows:

When x_1~\textrm{xor}~x_2~\textrm{xor}~\ldots~\textrm{xor}~x_n is written in base two, the digit in the 2^k's place (k \geq 0) is 1 if the number of integers among x_1, x_2, \ldots, x_n whose binary representations have 1 in the 2^k's place is odd, and 0 if that count is even.

For example, 3~\textrm{xor}~5 = 6.

They wanted to use this operation quickly, so each of them calculated the xor of the integers written on their scarfs except his scarf.

We know that the xor calculated by Snuke Cat i, that is, the xor of the integers written on the scarfs except the scarf of Snuke Cat i is a_i.
Using this information, restore the integer written on the scarf of each Snuke Cat.

Constraints

All values in input are integers.

2 \leq N \leq 200000

N is even.

0 \leq a_i \leq 10^9

There exists a combination of integers on the scarfs that is consistent with the given information.

Input

Input is given from Standard Input in the following format:

N
a_1 a_2 \ldots a_N

Output

Print a line containing N integers separated with space.

The i-th of the integers from the left should represent the integer written on the scarf of Snuke Cat i.

If there are multiple possible solutions, you may print any of them.

Sample Input 1

4
20 11 9 24

Sample Output 1

26 5 7 22

5~\textrm{xor}~7~\textrm{xor}~22 = 20

26~\textrm{xor}~7~\textrm{xor}~22 = 11

26~\textrm{xor}~5~\textrm{xor}~22 = 9

26~\textrm{xor}~5~\textrm{xor}~7 = 24

Thus, this output is consistent with the given information.