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

m = 63

ps = V.fromList $ take m  [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
                           31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
                           73, 79, 83, 89, 97, 101, 103, 107, 109,
                           113, 127, 131, 137, 139, 149, 151, 157,
                           163, 167, 173, 179, 181, 191, 193, 197,
                           199, 211, 223, 227, 229, 233, 239, 241,
                           251, 257, 263, 269, 271, 277, 281, 283,
                           293, 307, 311, 313, 317, 331, 337, 347,
                           349, 353, 359, 367, 373, 379, 383, 389,
                           397, 401, 409, 419, 421, 431, 433, 439,
                           443, 449, 457, 461, 463, 467, 479, 487,
                           491, 499, 503, 509, 521, 523, 541, 547,
                           557, 563, 569, 571, 577, 587, 593, 599,
                           601, 607, 613, 617, 619, 631, 641, 643,
                           647, 653, 659, 661, 673, 677, 683, 691,
                           701, 709, 719, 727, 733, 739, 743, 751,
                           757, 761, 769, 773, 787, 797, 809, 811,
                           821, 823, 827, 829, 839, 853, 857, 859,
                           863, 877, 881, 883, 887, 907, 911, 919,
                           929, 937, 941, 947, 953, 967, 971, 977,
                           983, 991, 997]

num2pbits n i b | i >= m = b
                | otherwise = let x = (1::Int) `shiftL` i
                                  p = ps V.! i
                                  b' = if n `mod` p == 0
                                       then b + x
                                       else b
                              in if p < n
                                 then num2pbits n (i+1) b'
                                 else b'

main = do
  n <- getInt
  as <- getIntVec n

  let as' = V.map (\x -> num2pbits x 0 0) as
      band = V.foldr1 (.&.) as' -- band == 0 => setwise coprime

      checkPairwise i d | i >= n = True
                        | otherwise = let x = as' V.! i
                                      in if d .&. x /= 0
                                         then False
                                         else checkPairwise (i+1) (d .|. x)

      ans | checkPairwise 0 0 = "pairwise coprime"
          | band == 0         = "setwise coprime"
          | otherwise         = "not coprime"

  putStrLn ans


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

ps = VB.fromList $ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
                    31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
                    73, 79, 83, 89, 97, 101, 103, 107, 109,
                    113, 127, 131, 137, 139, 149, 151, 157,
                    163, 167, 173, 179, 181, 191, 193, 197,
                    199, 211, 223, 227, 229, 233, 239, 241,
                    251, 257, 263, 269, 271, 277, 281, 283,
                    293, 307, 311, 313, 317, 331, 337, 347,
                    349, 353, 359, 367, 373, 379, 383, 389,
                    397, 401, 409, 419, 421, 431, 433, 439,
                    443, 449, 457, 461, 463, 467, 479, 487,
                    491, 499, 503, 509, 521, 523, 541, 547,
                    557, 563, 569, 571, 577, 587, 593, 599,
                    601, 607, 613, 617, 619, 631, 641, 643,
                    647, 653, 659, 661, 673, 677, 683, 691,
                    701, 709, 719, 727, 733, 739, 743, 751,
                    757, 761, 769, 773, 787, 797, 809, 811,
                    821, 823, 827, 829, 839, 853, 857, 859,
                    863, 877, 881, 883, 887, 907, 911, 919,
                    929, 937, 941, 947, 953, 967, 971, 977,
                    983, 991, 997]

m = VB.length ps

num2pbits n i b | i >= m = b
                | otherwise = let x = (1::Integer) `shiftL` i
                                  p = ps VB.! i
                                  b' = if n `mod` p == 0
                                       then b + x
                                       else b
                              in if p < n
                                 then num2pbits n (i+1) b'
                                 else b'

main = do
  n <- getInt
  as_t <- getIntegerList

  let as = VB.fromList as_t

  let as' = VB.map (\x -> num2pbits x 0 (0::Integer)) as
      band = VB.foldr1 (.&.) as' -- band == 0 => setwise coprime

      checkPairwise i d | i >= n = True
                        | otherwise = let x = as' VB.! i
                                      in if d .&. x /= 0
                                         then False
                                         else checkPairwise (i+1) (d .|. x)

      ans | checkPairwise 0 (0::Integer) = "pairwise coprime"
          | band == 0         = "setwise coprime"
          | otherwise         = "not coprime"

  putStrLn ans

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

Score : 500 points

Problem Statement

We have N integers. The i-th number is A_i.

\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.

\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.

Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.

Here, GCD(\ldots) denotes greatest common divisor.

Constraints

2 \leq N \leq 10^6

1 \leq A_i\leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

Sample Input 1

3
3 4 5

Sample Output 1

pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

Sample Input 2

3
6 10 15

Sample Output 2

setwise coprime

Since GCD(6,10)=2, they are not pairwise coprime. However, since GCD(6,10,15)=1, they are setwise coprime.

Sample Input 3

3
6 10 16

Sample Output 3

not coprime

GCD(6,10,16)=2, so they are neither pairwise coprime nor setwise coprime.

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.


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    n' <- getInt
    as' <- getIntList
    let (o,as) = partition (== 1) as'
    let lo = length o
    let n = length as
    let ps = concatMap factorize as
    let vec = VU.create $ do
            v <- VUM.replicate 1000001 (0 :: Int)
            forM_ ps $ \i -> do
                VUM.modify v succ i
            return v
    let pmax = VU.maximum $ VU.drop 2 vec
    let ans | n == 0 = "pairwise coprime"
            | pmax == 1 = "pairwise coprime"
            | pmax /= n = "setwise coprime"
            | lo /= 0 = "setwise coprime"
            | otherwise = "not coprime"
    putStrLn ans

f n k
  | n < k = n
  | n `mod` k == 0 = f (n `div` k) k
  | otherwise = f (n `mod` k) k

primes = map fromIntegral primes'
  where
    primes' = [2, 3, 5] ++ f 5 7 (drop 2 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]]

factorize 1 = [1]
factorize n = format $ factorize' n primes
  where
    format ps = map head $ group ps
    factorize' n ps@(p:ps')
      | p * p > n = [n]
      | rem n p == 0 = p : factorize' (div n p) ps
      | otherwise = factorize' n ps'


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, BinaryLiterals, CPP, DerivingStrategies  #-}
{-# LANGUAGE DerivingVia, FlexibleContexts, FlexibleInstances       #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, KindSignatures, LambdaCase #-}
{-# LANGUAGE MagicHash, MultiParamTypeClasses, MultiWayIf           #-}
{-# LANGUAGE NumericUnderscores, OverloadedStrings, PatternSynonyms #-}
{-# LANGUAGE RankNTypes, RecordWildCards, ScopedTypeVariables       #-}
{-# LANGUAGE StandaloneDeriving, TupleSections, TypeApplications    #-}
{-# LANGUAGE TypeFamilies, TypeInType, UnboxedTuples, ViewPatterns  #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.Reader
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bifunctor
import           Data.Bool
import qualified Data.ByteString                   as B
import qualified Data.ByteString.Builder           as B
import qualified Data.ByteString.Char8             as C
import qualified Data.ByteString.Internal          as B
import qualified Data.ByteString.Unsafe            as B
import           Data.Char
import qualified Data.Foldable                     as F
import           Data.Function
import           Data.Functor.Identity
import qualified Data.IntMap.Strict                as IM
import qualified Data.IntSet                       as IS
import qualified Data.List                         as L
import qualified Data.Map.Strict                   as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive
import           Data.Proxy
import           Data.Ratio
import           Data.Semigroup
import qualified Data.Set                          as S
import           Data.Tuple
import qualified Data.Vector                       as V
import qualified Data.Vector.Algorithms.Intro      as Intro
import qualified Data.Vector.Fusion.Stream.Monadic as MS
import qualified Data.Vector.Fusion.Bundle.Monadic as MB
import           Data.Vector.Fusion.Util
import qualified Data.Vector.Generic               as G
import qualified Data.Vector.Generic.Mutable       as GM
import qualified Data.Vector.Mutable               as VM
import qualified Data.Vector.Primitive             as P
import qualified Data.Vector.Primitive.Mutable     as PM
import qualified Data.Vector.Unboxed               as U
import qualified Data.Vector.Unboxed.Mutable       as UM
import           Debug.Trace
import           Foreign                           hiding (void)
import           GHC.Exts
import           GHC.TypeLits
import           System.IO
import           Unsafe.Coerce

#define MOD 1000000007

main :: IO ()
main = do
    n <- readLn @Int
    xs <- U.unfoldrN n (runParser int) <$> C.getLine
    print $ solve n xs

data Res
    = PairwiseCoprime
    | SetwiseCoprime
    | NotCoprime

instance Show Res where
    show PairwiseCoprime = "pairwise coprime"
    show SetwiseCoprime = "setwise coprime"
    show NotCoprime = "not coprime"

solve :: Int -> U.Vector Int -> Res
solve n xs
    | isPairwise xs = PairwiseCoprime
    | U.foldl' gcd 0 xs == 1 = SetwiseCoprime
    | otherwise = NotCoprime

naiveIsPairwise :: U.Vector Int -> Bool
naiveIsPairwise xs = and[ gcd (xs U.! i) (xs U.! j) == 1| i<-[0..n-1],j<-[i+1..n-1]]
  where
    n = U.length xs

isPairwise :: U.Vector Int -> Bool
isPairwise xs = runST $ do
    freq <- UM.replicate 1100100 (0::Int)
    U.forM_ xs $ \x -> do
        let ps = map head.L.group $ primeFactors x
        forM_ ps $ \p -> do
            UM.unsafeModify freq (+1)  p
    (<=1) . U.maximum <$> U.unsafeFreeze freq

smallPrimes :: (Integral i) => [i]
smallPrimes = 2 : [ n | n<-[3,5..1000], all ((>0).rem n) $ takeWhile (\x->x*x<=n) smallPrimes]
{-# SPECIALIZE smallPrimes :: [Int] #-}

primeFactors n | n < 2 = []
primeFactors n = go n smallPrimes
  where
    go !n pps@(p:ps)
        | n < p * p = [n]
        | r > 0     = go n ps
        | otherwise = p : go q pps
      where
        (q, r) = quotRem n p
    go n [] = [n]
{-# SPECIALIZE primeFactors :: Int -> [Int] #-}
-------------------------------------------------------------------------------
-- Utils
-------------------------------------------------------------------------------
rep :: (Monad m) => Int -> (Int -> m ()) -> m ()
rep n = flip MS.mapM_ (stream 0 n)
{-# INLINE rep #-}
rev :: (Monad m) => Int -> (Int -> m ()) -> m ()
rev !n = flip MS.mapM_ (streamR 0 n)
{-# INLINE rev #-}
stream :: (Monad m) => Int -> Int -> MS.Stream m Int
stream !l !r = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream #-}
streamR :: (Monad m) => Int -> Int -> MS.Stream m Int
streamR !l !r = MS.Stream step (r - 1) where { step x | x >= l = return $ MS.Yield x (x - 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] streamR #-}
stream' :: (Monad m) => Int -> Int -> Int -> MS.Stream m Int
stream' !l !r !d = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + d) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream' #-}
infixl 8 `shiftRL`, `unsafeShiftRL`
shiftRL :: Int -> Int -> Int
shiftRL = unsafeShiftRL
{-# INLINE shiftRL #-}
unsafeShiftRL :: Int -> Int -> Int
unsafeShiftRL (I# x#) (I# i#) = I# (uncheckedIShiftRL# x# i#)
{-# INLINE unsafeShiftRL #-}
type Parser a = StateT C.ByteString Maybe a
runParser :: Parser a -> C.ByteString -> Maybe (a, C.ByteString)
runParser = runStateT
{-# INLINE runParser #-}
int :: Parser Int
int = coerce $ C.readInt . C.dropWhile isSpace
{-# INLINE int #-}
int1 :: Parser Int
int1 = fmap (subtract 1) int
{-# INLINE int1 #-}
char :: Parser Char
char = coerce C.uncons
{-# INLINE char #-}
byte :: Parser Word8
byte = coerce B.uncons
{-# INLINE byte #-}
skipSpaces :: Parser ()
skipSpaces = modify' (C.dropWhile isSpace)
{-# INLINE skipSpaces #-}
lowerBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
lowerBoundM low high p = go low high where { go !low !high | high <= low = return high | otherwise = p mid >>= bool (go (mid + 1) high) (go low mid) where { mid = low + unsafeShiftRL (high - low) 1}}
{-# INLINE lowerBoundM #-}
upperBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
upperBoundM low high p = do { flg <- p high; if flg then return high else subtract 1 <$!> lowerBoundM low high (fmap not . p)}
{-# INLINE upperBoundM #-}
lowerBound :: Int -> Int -> (Int -> Bool) -> Int
lowerBound low high p = runIdentity (lowerBoundM low high (return . p))
{-# INLINE lowerBound #-}
upperBound :: Int -> Int -> (Int -> Bool) -> Int
upperBound low high p = runIdentity (upperBoundM low high (return . p))
{-# INLINE upperBound #-}


{-# 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
  [h, w, m] <- getIntList
  dh <- VM.new h
  VM.set dh (0::Int)
  dw <- VM.new w
  VM.set dw (0::Int)

  let readInputs :: Int -> Set.Set (Int, Int) -> Int -> Int -> IO (Set.Set (Int, Int), Int, Int)
      readInputs i s my mx
        | i >= m = return (s, my, mx)
        | otherwise = do
            [h', w'] <- getIntList
            let h = h' - 1
                w = w' - 1
                s' = (h, w) `Set.insert` s
            ty <- VM.read dh h
            VM.write dh h (ty + 1)
            tx <- VM.read dw w
            VM.write dw w (tx + 1)
            let my' = max (ty + 1) my
                mx' = max (tx + 1) mx
            readInputs (i+1) s' my' mx'

  (s, my, mx) <- readInputs 0 (Set.empty) 0 0

  let getIs i j d mx is | i >= j = return is
                        | otherwise = do
                            t <- VM.read d i
                            let is' | t == mx = (i:is)
                                    | otherwise = is
                            getIs (i+1) j d mx is'

  ys <- getIs 0 h dh my []
  xs <- getIs 0 w dw mx []

  let found = or [not $ (y, x) `Set.member` s | y <- ys, x <- xs]
      d | found = 0
        | otherwise = 1

  print $ my + mx - d

Score : 500 points

Problem Statement

We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).

Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.

Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

Constraints

All values in input are integers.

1 \leq H, W \leq 3 \times 10^5

1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)

1 \leq h_i \leq H

1 \leq w_i \leq W

\left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

Input

Input is given from Standard Input in the following format:

H W M
h_1 w_1
\vdots
h_M w_M

Output

Print the answer.

Sample Input 1

2 3 3
2 2
1 1
1 3

Sample Output 1

3

We can destroy all the targets by placing the bomb at \left(1, 2\right).

Sample Input 2

3 3 4
3 3
3 1
1 1
1 2

Sample Output 2

3

Sample Input 3

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

Sample Output 3

6


import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.Vector as V
import Debug.Trace as De

-- 入出力ライブラリ（コピペ） --
readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine
getIntNList n = map readIntList <$> replicateM (fromIntegral n) BS.getLine

-- 関数 --
func :: Int -> V.Vector Int -> [Int]
func nn av = solve 0 0 0
  where
    solve :: Int -> Int -> Int -> [Int]
    solve n px qx
      | n == 300100 = []
      | px == nn = ((px-qx):(solve (n+1) px px))
      | (av V.! px) /= n = ((px-qx):(solve (n+1) px px))
      | (av V.! qx) == n = solve n (px+1) qx

get1 :: [Int] -> Int
get1 x = (x!!0)

get2 :: [Int] -> Int
get2 x = (x!!1)

hantei :: (Int, Int) -> Bool
hantei x
  | fst(x) == 0 = True
  | otherwise = False

reflect :: [Int] -> Int -> [Int]
reflect x border = map hikizan x
  where
    hikizan :: Int -> Int
    hikizan t = t - border

tansaku :: Int -> V.Vector Int -> V.Vector Int -> V.Vector Int -> V.Vector Int -> Int
tansaku n xv yv ix iy = solve 0
  where
    solve :: Int -> Int
    solve pos
      | pos == n = 0
      | otherwise = newnum + (solve (pos+1))
        where newnum = if ((ix V.! (xv V.! pos)) == 1 && (iy V.! (yv V.! pos)) == 1) then 1 else 0

main = do
  -- 入力 --
  [h, w, n] <- (map read . words) <$> getLine
  a <- getIntNList n

  -- パース --
  let x = map get1 a
  let y = map get2 a
  let xw = (V.fromList x) :: V.Vector Int
  let yw = (V.fromList y) :: V.Vector Int
  let xs = sort x
  let ys = sort y
  let xv = (V.fromList xs) :: V.Vector Int
  let yv = (V.fromList ys) :: V.Vector Int

  -- 本質部分 --
  let numx = func n xv
  let numy = func n yv
  let maxx = maximum numx
  let maxy = maximum numy
  let evalx = reflect numx maxx
  let evaly = reflect numy maxy
  let ex = zip evalx [0..300100]
  let ey = zip evaly [0..300100]
  let fx = filter hantei ex
  let fy = filter hantei ey
  let gx = snd (unzip fx)
  let gy = snd (unzip fy)
  let gx2 = (V.fromList gx) :: V.Vector Int
  let gy2 = (V.fromList gy) :: V.Vector Int

  -- 探索パート --
  let szx = length gx
  let szy = length gy
  let hx = func szx gx2
  let hy = func szy gy2
  let ix = (V.fromList hx) :: V.Vector Int
  let iy = (V.fromList hy) :: V.Vector Int
  let ret = tansaku n xw yw ix iy

  -- 答えを出力 --
  let ans = if (ret == (szx * szy)) then (maxx + maxy - 1) else (maxx + maxy)
  putStrLn $ show ans


{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable, FlexibleInstances,
  MultiParamTypeClasses, TypeApplications, RecordWildCards,
  NumericUnderscores #-}
{-# OPTIONS_GHC -O2 #-}

#define PHASE_FUSED [1]
#define PHASE_INNER [0]
#define INLINE_FUSED INLINE PHASE_FUSED
#define INLINE_INNER INLINE PHASE_INNER

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import Data.Functor.Identity
import Data.Data
import Data.Typeable
import GHC.Generics
import System.IO
import System.IO.Unsafe (unsafeDupablePerformIO, unsafePerformIO)
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString as BSW
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSLW
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Unsafe as BSU
import qualified Data.ByteString.Internal as BSU
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Vector.Fusion.Bundle.Monadic as VFBM
import qualified Data.Vector.Fusion.Bundle as VFB
import qualified Data.Vector.Fusion.Stream.Monadic as VFSM
import qualified Data.Vector.Fusion.Bundle.Size as VFBS
import qualified Data.Vector.Fusion.Util as VFU
import qualified Data.Vector.Algorithms.Intro as VAIT
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import Unsafe.Coerce
import Foreign.ForeignPtr
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#, Addr#, Ptr(..))

main :: IO ()
main = do
  [h,w,m] <- map readInt . words <$> getLine
  blocks <- do
    blocks <- VU.unsafeThaw =<< getVecURest m
      (liftA2 (,) (subtract 1 <$> rIntL) (subtract 1 <$> rIntL))
    VAIT.sort blocks
    VU.unsafeFreeze blocks
  let !xCount = VU.accumulate (+) (VU.replicate h (0::Int))
                $ VU.map (,1) $ fst $ VU.unzip blocks
      !yCount = VU.accumulate (+) (VU.replicate w (0::Int))
                $ VU.map (,1) $ snd $ VU.unzip blocks
      !xCtMax = VU.maximum xCount
      !yCtMax = VU.maximum yCount
      xMaxs  = VU.elemIndices xCtMax xCount
      !yMaxs = VU.elemIndices yCtMax yCount
      testDup = (`VU.all` xMaxs) $ \ !x ->
        (`VU.all` yMaxs) $ \ !y -> binElem (x,y) blocks
  print $ xCtMax + yCtMax - if testDup then 1 else 0
  return ()

binElem :: (VG.Vector v a, Ord a) => a -> v a -> Bool
binElem a vec = maybe False (a==) $ vec VG.!? findIdxGeqSorted vec a

findIdxLeqSorted :: (VG.Vector v a, Ord a) => v a -> a -> Int
{-# INLINE findIdxLeqSorted #-}
findIdxLeqSorted = findIdxLeqSortedBy compare

findIdxLtSorted :: (VG.Vector v a, Ord a) => v a -> a -> Int
{-# INLINE findIdxLtSorted #-}
findIdxLtSorted = findIdxLtSortedBy compare

findIdxGeqSorted :: (VG.Vector v a, Ord a) => v a -> a -> Int
{-# INLINE findIdxGeqSorted #-}
findIdxGeqSorted = findIdxGeqSortedBy compare

findIdxGtSorted :: (VG.Vector v a, Ord a) => v a -> a -> Int
{-# INLINE findIdxGtSorted #-}
findIdxGtSorted = findIdxGtSortedBy compare

findIdxLeqSortedBy :: VG.Vector v a => (a -> a -> Ordering) -> v a -> a -> Int
{-# INLINE findIdxLeqSortedBy #-}
findIdxLeqSortedBy cmp vec a
  = binSearchLeftMax ((/=GT) . (`cmp` a) . VG.unsafeIndex vec)
                     (-1) (VG.length vec)

findIdxLtSortedBy :: VG.Vector v a => (a -> a -> Ordering) -> v a -> a -> Int
{-# INLINE findIdxLtSortedBy #-}
findIdxLtSortedBy cmp vec a
  = binSearchLeftMax ((==LT) . (`cmp` a) . VG.unsafeIndex vec)
                     (-1) (VG.length vec)

findIdxGeqSortedBy :: VG.Vector v a => (a -> a -> Ordering) -> v a -> a -> Int
{-# INLINE findIdxGeqSortedBy #-}
findIdxGeqSortedBy cmp vec a
  = binSearchRightMin ((/=LT) . (`cmp` a) . VG.unsafeIndex vec)
                     (-1) (VG.length vec)

findIdxGtSortedBy :: VG.Vector v a => (a -> a -> Ordering) -> v a -> a -> Int
{-# INLINE findIdxGtSortedBy #-}
findIdxGtSortedBy cmp vec a
  = binSearchRightMin ((==GT) . (`cmp` a) . VG.unsafeIndex vec)
                     (-1) (VG.length vec)

binSearchLeftMax,binSearchRightMin :: (Int -> Bool) -> Int -> Int -> Int
{-# INLINE binSearchLeftMax #-}
binSearchLeftMax = coerce
  (binSearchLeftMaxM :: (Int -> Identity Bool) -> Int -> Int -> Identity Int)
{-# INLINE binSearchRightMin #-}
binSearchRightMin = coerce
  (binSearchRightMinM :: (Int -> Identity Bool) -> Int -> Int -> Identity Int)

binSearchLeftMaxM :: (Monad m) => (Int -> m Bool) -> Int -> Int -> m Int
{-# INLINE binSearchLeftMaxM #-}
binSearchLeftMaxM f = go
  where
    go le gt | gt - le <= 1 = return le
             | otherwise = do
                 let !mid = le + (gt - le) `shiftR` 1
                 test <- f mid
                 if test then go mid gt else go le mid

binSearchRightMinM :: (Monad m) => (Int -> m Bool) -> Int -> Int -> m Int
{-# INLINE binSearchRightMinM #-}
binSearchRightMinM f = go
  where
    go lt ge | ge - lt <= 1 = return ge
             | otherwise = do
                 let !mid = lt + (ge - lt) `shiftR` 1
                 test <- f mid
                 if test then go lt mid else go mid ge

#define IL(f) {-# INLINE f #-}; f

IL(putBuilder) = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
IL(printVecInLines) = putBuilder . v2BLines
IL(printVecInSpcSepLn) = putBuilder . v2BSpcSepLn

class ShowAsBuilder a where
  showAsBuilder :: a -> BSB.Builder
  default showAsBuilder :: (Show a) => a -> BSB.Builder
  IL(showAsBuilder) = BSB.string8 . show

-- Inconsistent with show
instance (ShowAsBuilder a, VG.Vector v a) => ShowAsBuilder (v a) where
  IL(showAsBuilder) = v2BSpcSep

#define INS(t,f) instance ShowAsBuilder t where { IL(showAsBuilder)=f }
INS(Int,BSB.intDec)
INS(Int8,BSB.int8Dec)
INS(Int16,BSB.int16Dec)
INS(Int32,BSB.int32Dec)
INS(Int64,BSB.int64Dec)
INS(Word,BSB.wordDec)
INS(Word8,BSB.word8Dec)
INS(Word16,BSB.word16Dec)
INS(Word32,BSB.word32Dec)
INS(Word64,BSB.word64Dec)
INS(Integer,BSB.integerDec)
INS(Float,BSB.floatDec)
INS(Double,BSB.doubleDec)
-- INS(String,BSB.string8) -- Inconsistent with Show
-- INS(BS.ByteString,BSB.byteString) -- Inconsistent with Show
-- INS(BSL.ByteString,BSB.lazyByteString) -- Inconsisitent with Show
#undef INS

-- Inconsistent with Show
instance (ShowAsBuilder a, ShowAsBuilder b) => ShowAsBuilder (a,b) where
  IL(showAsBuilder) = showTupAsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c) =>
  ShowAsBuilder (a,b,c) where
  IL(showAsBuilder) = showTup3AsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  ShowAsBuilder (a,b,c,d) where
  IL(showAsBuilder) = showTup4AsBuilder

IL(showTupAsBuilderWith)
  :: (a -> BSB.Builder) -> (b -> BSB.Builder) -> (a,b) -> BSB.Builder
showTupAsBuilderWith showA showB
  = \(a,b) -> (showA a <>) $ BSB.char7 ' ' <> showB b
IL(showTupAsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b)
  => (a,b) -> BSB.Builder
showTupAsBuilder = showTupAsBuilderWith showAsBuilder showAsBuilder

IL(showTup3AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (a,b,c) -> BSB.Builder
showTup3AsBuilderWith showA showB showC
  = \(a,b,c) -> (showA a <>) $ (BSB.char7 ' ' <>) $ (showB b <>)
                $ (BSB.char7 ' ' <>) $ showC c
IL(showTup3AsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c)
  => (a,b,c) -> BSB.Builder
showTup3AsBuilder
  = showTup3AsBuilderWith showAsBuilder showAsBuilder showAsBuilder

IL(showTup4AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (d -> BSB.Builder) -> (a,b,c,d) -> BSB.Builder
showTup4AsBuilderWith showA showB showC showD
  = \(a,b,c,d) -> (showA a <>) $ (BSB.char7 ' ' <>)
                  $ showTup3AsBuilderWith showB showC showD (b,c,d)
IL(showTup4AsBuilder) ::
  (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  (a,b,c,d) -> BSB.Builder
showTup4AsBuilder = showTup4AsBuilderWith showAsBuilder showAsBuilder
                    showAsBuilder showAsBuilder

v2BSpcSepLn, v2BSpcSep, v2BConcat, v2BLines ::
  (VG.Vector v a, ShowAsBuilder a)
  => v a -> BSB.Builder
IL(v2BSpcSepLn) = v2BSpcSepLnWith showAsBuilder
IL(v2BSpcSep) = v2BSpcSepWith showAsBuilder
IL(v2BConcat) = v2BConcatWith showAsBuilder
IL(v2BLines) = v2BLinesWith showAsBuilder

v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepLnWith) = v2BSpcSepPostfWith $ BS.singleton '\n'
IL(v2BSpcSepWith) = v2BSpcSepPostfWith BS.empty
IL(v2BConcatWith) showFct = VG.foldr ((<>) . showFct) mempty
IL(v2BLinesWith) showFct
  = VG.foldr (\ a -> (showFct a <>) . (BSB.char7 '\n' <>)) mempty

v2BSpcSepPostf :: (VG.Vector v a, ShowAsBuilder a)
  => BS.ByteString -- ^ postfix
  -> v a -> BSB.Builder
IL(v2BSpcSepPostf) = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepPostfWith) = vecToBuilder BS.empty $ BS.singleton ' '

IL(vecToBuilder) :: (VG.Vector v a)
  => BS.ByteString -- ^ prefix
  -> BS.ByteString -- ^ separator
  -> BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder !prefix !separator !postfix
  = vecToBuilder_ (BSB.byteString prefix)
                  (BSB.byteString separator)
                  (BSB.byteString postfix)

IL(vecToBuilder_) :: (VG.Vector v a)
  => BSB.Builder -- ^ prefix
  -> BSB.Builder -- ^ separator
  -> BSB.Builder -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder_ !prefix !separator !postfix showFct = \vec -> prefix <>
  VG.foldr
  (\ a rest !prefx -> prefx <> (showFct a <> rest separator))
  (const postfix) vec mempty

IL(evalVals) :: [a] -> [a]
evalVals xs = build $ \c n -> foldr (c $!) n xs
IL(forceVals) :: (NFData a) => [a] -> [a]
forceVals xs = build $ \c n -> foldr (c $!!) n xs

IL(readLnWith) :: StateT BS.ByteString Maybe a -> IO a
readLnWith parser = fromJust . evalStateT parser <$> BS.getLine
IL(readContentWith) :: StateT BSL.ByteString Maybe a -> IO a
readContentWith parser = fromJust . evalStateT parser <$> BSL.getContents

IL(getVecGLn) :: (VG.Vector v a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (v a)
getVecGLn n s = VG.unfoldrN n (runStateT s) <$> BS.getLine
IL(getVecGRest) :: (VG.Vector v a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (v a)
getVecGRest n s = VG.unfoldrN n (runStateT s) <$> BSL.getContents
IL(getVecLn) :: Int -> StateT BS.ByteString Maybe a -> IO (V.Vector a)
getVecLn = getVecGLn
IL(getVecRest) :: Int -> StateT BSL.ByteString Maybe a -> IO (V.Vector a)
getVecRest = getVecGRest
IL(getVecULn) :: (VU.Unbox a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (VU.Vector a)
getVecULn = getVecGLn
IL(getVecURest) :: (VU.Unbox a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (VU.Vector a)
getVecURest = getVecGRest

IL(rIntL) :: StateT BSL.ByteString Maybe Int
rIntL = skipSpecialL $ StateT BSL.readInt
IL(rIntS) :: StateT BS.ByteString Maybe Int
rIntS = skipSpecialS $ StateT BS.readInt
IL(rStrL) :: (MonadState BSL.ByteString m) => m BS.ByteString
rStrL = skipSpecialL $ BSL.toStrict <$> state (BSL.span (>='!'))
IL(rStrS) :: (MonadState BS.ByteString m) => m BS.ByteString
rStrS = skipSpecialS $ state $ BS.span (>='!')
IL(rCharL) :: StateT BSL.ByteString Maybe Char
rCharL = StateT BSL.uncons
IL(rCharS) :: StateT BS.ByteString Maybe Char
rCharS = StateT BS.uncons
IL(rCharWL) :: StateT BSL.ByteString Maybe Word8
rCharWL = StateT BSLW.uncons
IL(rCharWS) :: StateT BS.ByteString Maybe Word8
rCharWS = StateT BSW.uncons
IL(dropSpecialL) :: (MonadState BSL.ByteString m) => m ()
dropSpecialL = modify $ BSL.dropWhile (<'!')
IL(dropSpecialS) :: (MonadState BS.ByteString m) => m ()
dropSpecialS = modify $ BS.dropWhile (<'!')
IL(skipSpecialL) :: (MonadState BSL.ByteString m) => m a -> m a
skipSpecialL = (dropSpecialL *>)
IL(skipSpecialS) :: (MonadState BS.ByteString m) => m a -> m a
skipSpecialS = (dropSpecialS *>)

IL(linToMat) :: (VG.Vector v a) => Int -> Int -> v a -> V.Vector (v a)
linToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VG.slice (i*w) w lvec)

IL(mLinToMat) :: (VGM.MVector v a) => Int -> Int -> v s a -> V.Vector (v s a)
mLinToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VGM.slice (i*w) w lvec)

IL(unsafeAddrToSVec) :: Int -> Addr# -> VS.Vector Word8
unsafeAddrToSVec n addr
  = (`VS.unsafeFromForeignPtr0` n)
    $ unsafeDupablePerformIO
    $ newForeignPtr_ $ Ptr addr

IL(vEvalElemsId) :: (VG.Vector v a) => v a -> v a
vEvalElemsId = vMapFoldl (\ !_ !x -> (x,())) ()

IL(vEvalElems) :: (VG.Vector v a) => v a -> ()
vEvalElems = VG.foldl' (\ !_ !_ -> ()) ()

IL(vMapFoldl) :: (VG.Vector v b, VG.Vector v c) =>
  (a -> b -> (c,a)) -> a -> v b -> v c
vMapFoldl f a
  = VG.unstream . VFB.inplace (streamMapFoldl f a) id . VG.stream

streamMapFoldl :: (Functor m) =>
  (a -> b -> (c,a)) -> a -> VFSM.Stream m b -> VFSM.Stream m c
{-# INLINE_FUSED streamMapFoldl #-}
streamMapFoldl f a (VFSM.Stream step s) = VFSM.Stream step1 (a,s)
  where
    {-# INLINE_INNER step1 #-}
    step1 (a0,s0) =  (<$> step s0) $ \r -> case r of
      VFSM.Yield b s1 -> case f a0 b of (c,a1) -> VFSM.Yield c (a1,s1)
      VFSM.Skip    s1 -> VFSM.Skip (a0,s1)
      VFSM.Done       -> VFSM.Done

IL(svecToBS) :: VS.Vector Word8 -> BS.ByteString
svecToBS vec = BSU.fromForeignPtr ptr 0 len
  where (ptr, len) = VS.unsafeToForeignPtr0 vec

unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()
IL(whenM) = (. flip when) . (>>=)
IL(unlessM) = (. flip unless) . (>>=)

IL(wrA) = A.writeArray
IL(rdA) = A.readArray
IL(mdA) = \arr f !i -> do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' = \arr f !i -> do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
IL(swapA) = \arr !i !j -> do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

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

#define TS(f,a,m,init)\
  IL(f) :: forall e i s. (C(a,m) A.Ix i) => (i,i) -> init m (a i e); f
#define N(f,g,h,a,m)\
  TS(f,a,m,e->)=A.newArray;\
  TS(g,a,m,)=A.newArray_;\
  TS(h,a,m,[e]->)=A.newListArray
#define C(a,m)
N(newIOA,newIOA_,newIOAL,IOArray,IO)
N(newSTA,newSTA_,newSTAL,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,newIOUAL,IOUArray,IO)
N(newSTUA,newSTUA_,newSTUAL,STUArray s,ST s)
#undef C
#undef N
#undef TS

#undef IL


{-# OPTIONS_GHC -Wno-tabs #-}
{-# 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 Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
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 :: IO [Int]
readIntToList = List.unfoldr (fmap (second $ BS.dropWhile Char.isSpace) . BS.readInt) <$> BS.getLine

readToList :: Read a => IO [a]
readToList = List.unfoldr (fmap (mapTaken . mapRemain) . span' (not . Char.isSpace)) <$> BS.getLine
	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 -> IO [a]
readToListN n = take n <$> readToList

readToTuple :: Read a => IO (a, a)
readToTuple = do
	[a, b] <- readToList
	return (a, b)

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

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

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

readIntToUVectorN :: Int -> IO (UVector.Vector Int)
readIntToUVectorN n = UVector.unfoldrN n (fmap stripRemain . BS.readInt) <$> BS.getLine
	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

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

data STGrid s = STGrid {
	stXs :: STVector s Int,
	stYs :: STVector s Int,
	stBombs :: Set (Int, Int)
}

data Grid = Grid {
	xs :: Vector Int,
	ys :: Vector Int,
	bombs :: Set (Int, Int)
} deriving Show

freezeGrid :: STGrid s -> ST s Grid
freezeGrid (STGrid xs ys bombs) = do
	xs' <- Vector.unsafeFreeze xs
	ys' <- Vector.unsafeFreeze ys
	return $ Grid xs' ys' bombs

addToGrid :: STGrid s -> (Int, Int) -> ST s (STGrid s)
addToGrid (STGrid xs ys bombs) (y, x) = do
	MVector.modify xs (+ 1) (x - 1)
	MVector.modify ys (+ 1) (y - 1)
	let bombs' = Set.insert (x - 1, y - 1) bombs
	return $ STGrid xs ys bombs'

genGrid :: Int -> Int -> [(Int, Int)] -> Grid
genGrid h w bs = runST $ do
	init <- STGrid <$> MVector.replicate w 0 <*> MVector.replicate h 0 <*> pure Set.empty
	result <- foldM addToGrid init bs
	freezeGrid result

maxIndexes :: Vector Int -> (Int, [Int])
maxIndexes xs = foldr (maxIndexes' xs) (-1, []) [0..(Vector.length xs - 1)]

maxIndexes' :: Vector Int -> Int -> (Int, [Int]) -> (Int, [Int])
maxIndexes' xs i (m, cands)
	| i == Vector.length xs = (m, cands)
	| m' == m    = (m, i : cands)
	| m' > m     = (m', [i])
	| otherwise  = (m, cands)
	where m' = xs Vector.! i

main :: IO ()
main = do
	[h, w, m] <- readIntToList
	bs <- replicateM m readToTuple
	let grid = genGrid h w bs
	let (maxX, candsX) = maxIndexes (xs grid)
	let (maxY, candsY) = maxIndexes (ys grid)
	let cands = (,) <$> candsX <*> candsY
	print $ maxX + maxY - if all (flip Set.member $ bombs grid) cands
		then 1
		else 0


main = do
  n <- readLn
  putStrLn $ show (1000 - n)

Score : 100 points

Problem Statement

We will buy a product for N yen (the currency of Japan) at a shop.

If we use only 1000-yen bills to pay the price, how much change will we receive?

Assume we use the minimum number of bills required.

Constraints

1 \leq N \leq 10000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the amount of change as an integer.

Sample Input 1

1900

Sample Output 1

100

We will use two 1000-yen bills to pay the price and receive 100 yen in change.

Sample Input 2

3000

Sample Output 2

0

We can pay the exact price.


main = do
    input  <- getLine
    let result = 1000 - mod (read input :: Int) 1000
    putStrLn $ show (if result == 1000 then 0 else result)


main = do
    n <- readLn
    print $ (10000 - n) `mod` 1000


main = do
  s <- tail . lines <$> getContents
  mapM_ (putStrLn . f s) ["AC", "WA", "TLE", "RE"]
  where f s j = j ++ " x " ++ show (length $ filter (== j) s)


module Main where

getChange :: Integer -> Integer
getChange n
	| n `mod` 1000 == 0 = 0
	| otherwise = 1000 - (n `mod` 1000)

thisLine :: String -> String
thisLine ('\n':_) = ""
thisLine (x:xs) = x : thisLine xs

main :: IO ()
main = interact $ show . getChange . read -- . thisLine


toInt :: String -> Int
toInt = read :: String -> Int

main = do
  n <- toInt <$> getLine
  let m = mod n 1000
  print $ if m == 0 then m else 1000 - m


main :: IO ()
main = do
  n <- readLn
  putStrLn $ show ((1000 - (n `mod` 1000)) `mod` 1000)


{-# OPTIONS_GHC -O2 #-}
main :: IO ()
main = do
    n <- (flip mod 1000) <$> readLn :: IO Int
    print $ if n == 0 then 0 else 1000 - n


{-# OPTIONS_GHC -O2 #-}
main :: IO ()
main = do
    n <- readLn :: IO Int
    print $ 1000 - (n `mod` 1000)


import Control.Applicative

main :: IO ()
main = solve <$> readLn >>= print

solve :: Int -> Int
solve = flip mod 1000 . (1000 -) . flip mod 1000


main = print . (`mod` 1000) . negate =<< readLn


main :: IO ()
main = do
    a <- readLn
    let res = a `mod` 1000
    putStrLn $ show $ 1000 - res


module Main where
import qualified Control.Monad as C
import qualified Data.Char as C
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Array as A

int = read :: String -> Int
getWord :: IO String
getWord = do
  c <- getChar
  if C.isSpace c
  then
    return []
  else do
    ws <- getWord
    return (c:ws)
getInt = fmap int getWord
replace pred a = map (\x -> if pred x then a else x)

main = interact $ printer . solver . parser
parser = int
printer = unlines . (:[]) . show

solver x = (1000 - (x `mod` 1000)) `mod` 1000


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

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    n <- getInt
    let a = minimum . filter (>= 0) $ map (subtract n) [1000,2000..10000]
    print a


module Main where

main :: IO ()
main = do
  n <- readLn :: IO Int
  print $ if n `mod` 1000 == 0 then 0 else 1000 - n `mod` 1000


{-# LANGUAGE PartialTypeSignatures #-}
module Main (main) where

import Control.Monad
import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.List as L

main :: IO ()
main = do
  [d] <- readInts
  scoreTable <- readInts
  replicateM d readInts >>= output d . solve

solve :: [[Int]] -> _
solve xs = xs

output :: Int -> _ -> IO ()
output d _ = mapM_ print $ take d $ cycle [26,25..1]

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine

Problem Statement

AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to schedule contests for D days so that user satisfaction is as high as possible. For every day, AtCoder will hold exactly one contest, and each contest will end on that day. The satisfaction is calculated as follows.

The satisfaction at the beginning of day 1 is 0. Satisfaction can be negative.

Holding contests increases satisfaction. The amount of increase will vary depending on a variety of factors. Specifically, we know in advance that holding a contest of type i on day d will increase the satisfaction by s_{d,i}.

If a particular type of contest is not held for a while, the satisfaction decreases. Each contest type i has an integer c_i, and at the end of each day d=1,2,...,D, the satisfaction decreases as follows. Let \mathrm{last}(d,i) be the last day before day d (including d) on which a contest of type i was held. If contests of type i have never been held yet, we define \mathrm{last}(d,i)=0. At the end of day d, the satisfaction decreases by \sum _{i=1}^{26}c_i \times (d-\mathrm{last}(d,i)).

Please schedule contests on behalf of AtCoder.
If the satisfaction at the end of day D is S, you will get a score of \max(10^6 + S, 0).
There are 50 test cases, and the score of a submission is the total scores for each test case.
You can make submissions multiple times, and the highest score among your submissions will be your score.

Constraints

D = 365

Each c_i is an integer satisfying 0\leq c_i \leq 100.

Each s_{d,i} is an integer satisfying 0\leq s_{d,i} \leq 20000.

Input

Input is given from Standard Input in the following format:

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}

Output

Let t_d (1\leq t_d \leq 26) be the type of the contest that will be held at day d.
Print D integers t_d to Standard Output in the following format:

t_1
t_2
\vdots
t_D

Any output that does not follow the above format may result in 0 pointsWA for that test case.

Input Generation

Each integer c_i and s_{d,i} is generated independently and uniformly at random from the integers in the range described in the problem statement.

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192

Sample Output 1

1
17
13
14
13

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case. The final satisfaction with this output is 79325, so the score is 1079325.

Input generator, score calculator, and visualizer

Beginner's Guide

If you don't know what to do, proceed to problem B or C.


{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeApplications #-}
module Main (main) where

import Control.Monad
import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.IntSet as Set
import qualified Data.List as L
import System.Random

main :: IO ()
main = do
  [d] <- readInts
  cs <- readInts
  dss <- replicateM d readInts
  -- replicateM d readInts >>= output d . solve 0
  -- let fmt s = show s ++ "\n"
  -- replicateM_ 365 $ (randomRIO @Int (1,26) >>= appendFile "tester/example/test.out" . fmt)
  replicateM_ 365 $ (randomRIO @Int (1,26) >>= print)
  -- return ()

solve :: Int -> [[Int]] -> [Int]
solve n dss
  | n < 365 = solve' n (dss !! n) : solve (n+1) dss
  | otherwise = []

solve' :: (Num a1, Ord a2, Ord a1, Enum a1) => p -> [a2] -> a1
solve' n dss = 1 + (snd $ maximum $ zip dss [0..] )

output :: Int -> [Int] -> IO ()
output d = mapM_ print

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine


{-# LANGUAGE PartialTypeSignatures #-}
module Main (main) where

import Control.Monad
import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.IntSet as Set
import qualified Data.List as L

main :: IO ()
main = do
  [d] <- readInts
  cs <- readInts
  replicateM d readInts >>= output d . solve 0

solve :: Int -> [[Int]] -> [Int]
solve n dss
  | n < 365 = solve' n (dss !! n) : solve (n+1) dss
  | otherwise = []

solve' :: (Num a1, Ord a2, Ord a1, Enum a1) => p -> [a2] -> a1
solve' n dss = 1 + (snd $ maximum $ zip dss [0..] )

output :: Int -> [Int] -> IO ()
output d = mapM_ print

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine


import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.List
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector as V

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    d <- getInt
    cs <- VU.fromList <$> getIntList
    ss <- V.fromList . map VU.fromList <$> replicateM d getIntList
    let ts = VU.create $ do
            vec <- VUM.replicate d (0 :: Int)
            forM_ [0..d-1] $ \day -> do
                let con = ss V.! day
                let t = snd . VU.maximum $ VU.imap (\i c -> (c,i)) con
                VUM.write vec day t
            return vec

    let result = VU.create $ do
             sat <- VUM.replicate (d+1) (0 :: Int)
             res <- VUM.replicate (d+1) (0 :: Int)
             ld <- VUM.replicate 26 (0 :: Int)
             decs <- VUM.replicate 26 (0 :: Int)
             forM_ [1..d] $ \day -> do
                 let contest = ts VU.! (day - 1)
                 let inc = ss V.! (day - 1) VU.! contest
                 VUM.write ld contest day
                 forM_ [0..25] $ \con -> do
                     let dec = cs VU.! con
                     lday <- VUM.read ld con
                     VUM.write decs con $ dec * (day - lday)
                 s <- VUM.read sat (day - 1)
                 VUM.write sat day (s + inc)
                 forM_ [0..25] $ \con -> do
                     dec <- VUM.read decs con
                     VUM.modify sat (subtract dec) day
                 VUM.write res day (contest + 1)
             return res
    VU.mapM_ print $ VU.tail result


{-# LANGUAGE PartialTypeSignatures #-}
module Main (main) where

import Control.Monad
import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.List as L

main :: IO ()
main = do
  [d] <- readInts
  cs <- readInts
  replicateM d readInts >>= output d . solve

solve :: [[Int]] -> _
solve xs = xs

output :: Int -> _ -> IO ()
output d _ = mapM_ print $ take d [1..26]

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine


{-# 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 qualified Data.Heap as H
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC8
import           Data.Char
import           Data.Function
import qualified Data.Graph.Inductive.Graph as G
import qualified Data.Graph.Inductive.PatriciaTree as G
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

main = do
  --aN       <- getI
  --[aA, aB] <- getIL
  --aS       <- getLine
  [aN, aM, aK] <- getIL
  aA <- getVUI
  aB <- getVUI
  let scanSumA = VU.scanl (+) 0 aA
  let scanSumB = VU.scanl (+) 0 aB
  print
    $ if
      | VU.head aA > aK && VU.head aB > aK -> 0
      | otherwise -> scan scanSumB scanSumB aK
  return ()
  where
    scan scanSumX scanSumY k = VU.maximum
      $ VU.imap
        (\i x -> (+ i) $ binarySearchFirstTrueList (\y -> (k - x) < y) scanSumY)
      $ VU.takeWhile (< k) scanSumX

--雑多系
p :: Int -> Int
p x = x - 1

t :: Int -> (Int, Int)
t x = (x, 1)

orDefault def f t = if f t == False
                    then def
                    else t

--入力系
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

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

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

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

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

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

binarySearchFirstTrueList f list =
  let lenl = VU.length list
  in binarySearchFirstTrueListP f list (-1) lenl

binarySearchFirstTrueListP f list l r =
  let i = l + (div (r - l) 2)
      test = f (list VU.! i)
  in if
       | test && i - l == 1 -> i
       | test && i - l /= 1 -> binarySearchFirstTrueListP f list l i
       | not test && r - i == 1 -> r
       | otherwise -> binarySearchFirstTrueListP f list 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
{-

--周りのマス

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 >= 1
  , aY <= h
  , aX >= 1
  , aX <= w
  , (aY /= y) || (aX /= x)]

-}

Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.


import           Data.List
import           Data.Maybe

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

solve :: Int -> [Int] -> [Int] -> Int
solve k an bm = fromJust (findIndex (==a) ans) + fromJust (findIndex (==b) bms) + 2
  where
    (a, b) = maximumBy (\(a, b) (c, d)-> (a + b) `compare` (c + d)) xs
    xs = [(a, b) | a <- ans , b <- bms, a + b <= k]
    ans = tail $ scanl' (+) 0 an
    bms = tail $ scanl' (+) 0 bm


import           Control.Monad (replicateM)
import           Data.List (findIndex)

main :: IO ()
main = do
  [n, m, k] <- map read . words <$> getLine :: IO [Int]
  [as, bs] <- replicateM 2 $ scanl1 (+) . map read . words <$> getLine
    :: IO [[Int]]
  let ans1 = (maximum . map (length . takeWhile (<= k))) [as, bs]
      ans2 = maximum
        $ (++) [0] -- for empty list
        $ zipWith (+) [1 ..]
        $ (flip map) ((takeWhile (<= k)) as)
        $ \n -> (length . takeWhile (<= k - n)) bs
  print $ max ans1 ans2


{-# LANGUAGE BangPatterns #-}

import Control.Monad
import Data.Array.Unboxed
import Data.Bits
import Data.Char
import Data.Coerce
import Data.Function
import Data.Int
import Data.IORef
import Data.List
import Data.Maybe
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = do
  [n, m, k] <- getIntList
  as <- getIntList
  bs <- getIntList
  print $ solve n m k as bs

solve :: Int -> Int -> Int -> [Int] -> [Int] -> Int
solve n m k as bs = (go `on` f) as bs
  where
    f = V.fromList . scanl (+) 0
    go av bv = maximum [ i + j | i <- [0..n], let k' = k - av V.! i, k' >= 0, let j = fst (bisearch ((<= k') . (bv V.!)) (0, m))]

-- input

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

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

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

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

-- search

bisearch :: (Int -> Bool) -> (Int, Int) -> (Int, Int)
bisearch check = bis
  where
    bis (l, r)
      | l + 1 == r = (l, r)
      | check mid  = bis (mid, r)
      | otherwise  = bis (l, mid)
      where
        mid = l + (r - l) `div` 2


{-# LANGUAGE BangPatterns #-}

import Control.Monad
import Data.Coerce
import Data.Bits
import Data.Char
import Data.Int
import Data.IORef
import Data.List
import Data.Maybe
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.ByteString.Char8 as BS

main = do
  [n, m, k] <- getIntList
  as <- getIntList
  bs <- getIntList
  print $ solve k as bs

solve k as bs = maximum . zipWith (+) [0..] $ map (go (f as)) (f bs)
  where
    f = takeWhile (<=k) . scanl (+) 0
    go xs y = (subtract 1) . length $ takeWhile (<=(k-y)) xs

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

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

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

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


import Data.List

main :: IO ()
main = do
    [_, _, k] <- map read . words <$> getLine
    as <- map read . words <$> getLine
    bs <- map read . words <$> getLine
    let as' = takeWhile (\x -> snd x <= k) [(n, sum (take n as)) | n <- [0..length as]]
        bs' = [last $ takeWhile (\y -> x + snd y <= k) [(m, sum (take m bs)) | m <- [0..length bs]] | (a, x) <- as']
        tmp = zipWith (\(a, x) (b, y) -> a + b) as' bs'
        res = maximum tmp
    putStrLn $ show res


module Main where

import qualified Data.ByteString.Char8         as BS
import qualified Data.ByteString.Lazy.Char8    as BSL
import qualified Data.ByteString.Builder       as BSB
import           Data.Char                      ( isSpace )
import           Data.List                      ( unfoldr )
import qualified Data.Vector                   as V
import qualified Data.Vector.Mutable           as VM
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM
import qualified Data.Vector.Generic           as VG
import qualified Data.Vector.Generic.Mutable   as VGM
import Data.Vector.Algorithms.Search
import           Control.Monad                  ( forM )

main :: IO ()
main = do
  [n, m, k] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  as <- VU.unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  bs <- VU.unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  as' <- VU.thaw $ VU.scanl1' (+) as
  bs' <- VU.thaw $ VU.scanl1' (+) bs
  ansA <- solve as' bs' k
  ansB <- solve bs' as' k
  print $ max ansA ansB

solve as' bs' k = do
  -- get index of maximum cost of as
  i <- binarySearchR as' k
  anss <- if i == 0
    then do
      j <- binarySearchR bs' k
      return $ VU.singleton j
    else
      VU.forM (VU.enumFromN 0 i) $ \i' -> do
        accumA <- VUM.read as' i'
        j <- binarySearchR bs' (k-accumA)
        return (i' + j + 1)
  return $ VU.maximum anss


import Data.List

main :: IO ()
main = do
    [_, _, k] <- map read . words <$> getLine
    as <- map read . words <$> getLine
    bs <- map read . words <$> getLine
    let as' = takeWhile (\x -> snd x <= k) [(n, sum (take n as)) | n <- [0..length as]]
        bs' = [ (a + b, x + y) | (a, x) <- as', (b, y) <- takeWhile (\y -> x + snd y <= k) [(m, sum (take m bs)) | m <-  [0..length bs]]]
        res = fst $ last $ sortOn snd bs'
    putStrLn $ show res


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

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

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

calc [] [] _ n = n
calc (a : as) [] t n
  | a > t = n
  | otherwise = calc as [] (t - a) (n + 1)
calc [] (b : bs) t n
  | b > t = n
  | otherwise = calc [] bs (t - b) (n + 1)
calc (a : as) (b : bs) t n
  | minimum [a, b] > t = n
  | a >= b = calc (a : as) bs (t - b) (n + 1)
  | otherwise = calc as (b : bs) (t - a) (n + 1)

main = do
  [n, m, k] <- getIntList
  as <- getIntList
  bs <- getIntList
  print $ calc as bs k 0


import Data.List
readIntList :: IO [Int]
readIntList = map read . words <$> getLine

f :: [Int] -> [Int] -> Int -> Int -> Int
f (a:as) (b:bs) count limit
   | a <= b && limit >= a = f as ([b] ++ bs) (count + 1) (limit - a)
   | a > b && limit >= b = f ([a] ++ as) bs (count + 1) (limit - b)
   | otherwise = count
f [] b count limit = f1 b count limit
f a [] count limit = f1 a count limit

f1 :: [Int] -> Int -> Int -> Int
f1 (x:xs) count limit
   | limit >= x = f1 xs (count + 1) (limit - x )
   | otherwise = count
f1 [] count limit = count

main = do
    [_, _, k] <- readIntList
    a <- readIntList
    b <- readIntList
    let ret = f a b 0 k
    print ret


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

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    [n,m,k] <- getIntList
    as <- getIntList
    bs <- getIntList
    let sa = takeWhile (<=k) $ scanl (+) 0 as
        sb = takeWhile (<=k) $ scanl (+) 0 bs
    let ansa = maximum $ solve k (length sa - 1) (reverse sa) sb
        ansb = maximum $ solve k (length sb - 1) (reverse sb) sa
    print $ max ansa ansb

solve k l [] _ = [0]
solve k l _ [] = [0]
solve k l (a:sa) (b:sb)
    | a + b <= k = l : solve k (l+1) (a:sa) sb
    | a + b > k = solve k (l-1) sa (b:sb)


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

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    [n,m,k] <- getIntList
    as <- getIntList
    bs <- getIntList
    let sa = reverse $ takeWhile (<k) $ scanl (+) 0 as
        sb = takeWhile (<k) $ scanl (+) 0 bs
        ans = zipWith (\a i -> i + length (takeWhile (< k-a) sb)) sa [0..]
    print . maximum $ solve k (length sa - 1) sa sb

solve k l [] _ = [0]
solve k l _ [] = [0]
solve k l (a:sa) (b:sb)
    | a + b <= k = l : solve k (l+1) (a:sa) sb
    | a + b > k = solve k (l-1) sa (b:sb)


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

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words
getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

main = do
    [n,m,k] <- getIntList
    as <- getIntList
    bs <- getIntList
    let sa = takeWhile (< k) $ scanl (+) 0 as
        sb = tail $ scanl (+) 0 bs
        ans = zipWith (\a i -> i + length (takeWhile (< k-a) sb)) sa [0..]
    print $ maximum ans


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

import Control.Arrow
import Control.Concurrent
import Control.Monad
import Data.Bits
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Complex
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 :: IO ()
main = do
    [n,m,k] <- r'
    as <- r'
    bs <- r'
    let aScan = zip [1..] $ scanl1 (+) as
    let bScan = scanl1 (+) bs

    -- print aScan
    -- print bScan

    let difs = filter (snd . second (>0)) $ map (second (k -)) aScan
    -- print difs
    let res = map (\(iA,a) -> case findIndex (> a) bScan of
                Just iB -> iA + iB
                Nothing -> iA + m
            ) difs
    --
    print $ case res of [] -> 0
                        r -> maximum r


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

main = do
	[ n, m, k ] <- readInts
	as <- readIntegers
	bs <- readIntegers
	print $ length $ takeWhile ( <= fromIntegral k ) $ scanl1 (+) $ solve as bs

solve as [] = as
solve [] bs = bs
solve (a:as) (b:bs)
	| a <= b = a : solve as (b:bs)
	| otherwise = b : solve (a:as) bs


main = readLn >>= print . solve
solve n = sum $ map f [1..n] where
  f x = g x (div n x)
  g d n = d * sum [1..n]

Score : 400 points

Problem Statement

For a positive integer X, let f(X) be the number of positive divisors of X.

Given a positive integer N, find \sum_{K=1}^N K\times f(K).

Constraints

1 \leq N \leq 10^7

Input

Input is given from Standard Input in the following format:

N

Output

Print the value \sum_{K=1}^N K\times f(K).

Sample Input 1

4

Sample Output 1

23

We have f(1)=1, f(2)=2, f(3)=2, and f(4)=3, so the answer is 1\times 1 + 2\times 2 + 3\times 2 + 4\times 3 =23.

Sample Input 2

100

Sample Output 2

26879

Sample Input 3

10000000

Sample Output 3

838627288460105

Watch out for overflows.


module Main where

import           Control.Arrow
import           Data.List
import qualified Data.Vector.Unboxed           as VU
import qualified Data.Vector.Unboxed.Mutable   as VUM

main :: IO ()
main = do
  n <- readLn::IO Int
  print $ VU.sum $ VU.map (f n) $ VU.enumFromN (1::Int) n
  where
    f n k = let y = n `div` k in y * (y + 1) * k `div` 2


{-# OPTIONS_GHC -O2 #-}

-- editorial (??)
main = do
    n <- readLn
    print $ sum $ map (\x ->
                let y = div n x
                in  div (y*(y+1)*x) 2
            ) [1..n]


import Data.List (group)

primes =
    let
        f (p : ps) = p : (filter $ (/= 0) . (`mod` p)) ps
    in
        f [ 2 .. ]

primeFactors n = [ x | x <- takeWhile (\y -> y * y <= n) primes, n `mod` x == 0 ]

factorize 1 = []
factorize n =
    let
        x = case primeFactors n of
            []     -> n
            p : ps -> p
    in
        x : factorize (n `div` x)

f k = k * (product . map (+ 1) . map length . group . factorize $ k)

toInt :: String -> Int
toInt = read

main = do
    n <- toInt <$> getLine

    print . sum . map f $ [ 1 .. n ]


import Data.List

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

sol as = length $ f mx as'
  where
  as' = sort as
  mx = last as'

f _ [] = []
f mx (a:as) = if a `elem` as
    then f mx' as'
    else if a*2>mx
      then a:as
      else a:f mx' as'
  where
  as' = filter ((>0) . (`rem` a)) as
  mx' = last as'

Score : 400 points

Problem Statement

Given is a number sequence A of length N.

Find the number of integers i \left(1 \leq i \leq N\right) with the following property:

For every integer j \left(1 \leq j \leq N\right) such that i \neq j , A_j does not divide A_i.

Constraints

All values in input are integers.

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

1 \leq A_i \leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N

Output

Print the answer.

Sample Input 1

5
24 11 8 3 16

Sample Output 1

3

The integers with the property are 2, 3, and 4.

Sample Input 2

4
5 5 5 5

Sample Output 2

0

Note that there can be multiple equal numbers.

Sample Input 3

10
33 18 45 28 8 19 89 86 2 4

Sample Output 3

5


import Data.List

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

sol as = length $ f mx as'
  where
  as' = sort as
  mx = last as'

f _ [] = []
f mx (a:as) = if a*2>mx then a:as else
  if a `elem` as
    then f mx' as'
    else a:f mx' as'
  where
  as' = filter ((>0) . (`rem` a)) as
  mx' = last as'


import Data.List

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

sol = length . f . sort

f [] = []
f (a:as) = if a `elem` as then f as' else a:f as'
  where
  as' = filter ((>0) . (`rem` a)) as


{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}
module Main (main) where
-- module ABC.ABC170.D where

import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.List as L
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.Vector.Generic.Mutable as MGV
import qualified Data.Vector.Algorithms.Merge as V
import Control.Monad.ST
import Control.Monad

main :: IO ()
main = do
  [n] <- readInts
  readIntsV >>= output . solve n

solve :: Int -> Vector Int -> Int
solve n vec = V.sum $ runST $ do
  mvec <- V.thaw vec
  V.sort mvec
  forM_ [0..n-1] $ \i -> do
    x <- MV.unsafeRead mvec i
    y <- MV.unsafeRead mvec (i+1)

    when (x > 0) $ do
      MV.write mvec i 1

      if x==y
      then MV.write mvec i 0
      else
        forM_ [i+1..n-1] $ \j -> do
          y <- MV.unsafeRead mvec j
          when (y > 0) $ do
            -- when (x==y) $ MV.write mvec i 0
            when (y `mod` x == 0) $ MV.write mvec j 0
  V.unsafeFreeze mvec

output :: Int -> IO ()
output = print

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine

readIntsV :: IO (Vector Int)
readIntsV = V.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine


{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}
module Main (main) where
-- module ABC.ABC170.D where

import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.List as L
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.Vector.Generic.Mutable as MGV
import qualified Data.Vector.Algorithms.Merge as V
import Control.Monad.ST
import Control.Monad

main :: IO ()
main = do
  [n] <- readInts
  readIntsV >>= output . solve n

solve :: Int -> Vector Int -> Int
solve n vec = V.sum $ runST $ do
  mvec <- V.thaw vec
  V.sort mvec
  forM_ [0..n-1] $ \i -> do
    x <- MV.unsafeRead mvec i
    when (x > 0) $ do
      MV.write mvec i 1
      forM_ [i+1..n-1] $ \j -> do
        y <- MV.unsafeRead mvec j
        when (y > 0) $ do
          when (x==y) $ MV.write mvec i 0
          when (y `mod` x == 0) $ MV.write mvec j 0
  V.unsafeFreeze mvec

output :: Int -> IO ()
output = print

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine

readIntsV :: IO (Vector Int)
readIntsV = V.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine


{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE BangPatterns #-}

module Main where

import Debug.Trace
import qualified Data.Map.Strict as Map

main :: IO ()
main = do
  getLine
  s <- map read . words <$> getLine
  --a `traceShow`
  print $ solve s

solve :: [Int] -> Int
solve s = length . filter (\ss -> (Map.findWithDefault 0 ss t) == 1) $ s
  where
    mx = (maximum s) + 1
    t = build mx Map.empty s

type Table = Map.Map Int Int

build :: Int -> Table -> [Int] -> Table
build mx t [] = t
build mx t (s:ss) = build mx t' ss
  where
    t' = if (Map.findWithDefault 0 s t) > 0 then Map.insertWith (+) s 1 t else foldr (\a tt -> Map.insertWith (+) a 1 tt) t [s, s*2 .. mx]


{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE BangPatterns #-}
module Main (main) where

import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.List as L

main :: IO ()
main = do
  [n] <- readInts
  readInts >>= output . solve n . L.sort

solve :: Int -> [Int] -> Int
solve _ [] = 0
solve n (x:xs) = let (c1,l1) = go 1 x xs in fromEnum c1 + solve n l1
  where
    go !m _ []
      | m == n = (0,[])
      | otherwise = (1,[])
    go !m a (b:bs)
      | (b `mod` a) == 0 = let (c,l) = go (m+1) a bs in (c,l)
      | otherwise = let (c,l) = go m a bs in (c,b:l)

output :: Int -> IO ()
output = print

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine


import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import qualified Data.Vector.Unboxed.Mutable as VUM

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

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

fill table (c : cs) = do
  point <- VUM.read table c
  VUM.write table c (point+1)
  when (cs /= []) $ fill table cs

fillVector table (a : as) n = do
  point <- VUM.read table a
  if point == 0 || point == 1
    then do
      if point == 1
        then do
          VUM.write table a 2
        else do
          let diva = n `div` a
          let cs = map (\x -> x * a) [1 .. diva]
          fill table cs
      when (as /= []) $ fillVector table as n
  else do
    when (as /= []) $ fillVector table as n

seek table (a : as) xs = do
  if as == []
    then return xs
    else do
      point <- VUM.read table a
      let xs' = if point == 1 then a : xs else xs
      seek table as xs'

main = do
  n <- getInt
  as <- getIntList
  if length as == 0
    then print 0
    else do
      let m = maximum as
      table <- VUM.replicate (m + 1) 0 :: IO (VUM.IOVector Int)
      fillVector table as m
      rs <- seek table as []
      print $ length rs


import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.Set as Set
import qualified Data.Vector.Unboxed.Mutable as VUM

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

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

ordNub :: (Ord a) => [a] -> [a]
ordNub l = go Set.empty l
  where
    go _ [] = []
    go s (x : xs) =
      if x `Set.member` s
        then go s xs
        else x : go (Set.insert x s) xs

fill table (c : cs) = do
  VUM.write table c False
  when (cs /= []) $ fill table cs

fillVector table (a : as) n = do
  let diva = n `div` a
  if  (diva >= 2)
    then do
      let cs = map (\x -> x * a) [2 .. diva]
      fill table cs
      when (as /= []) $ fillVector table as n
    else do
      when (as /= []) $ fillVector table as n

seek table (a : as) xs = do
  if as == []
    then return xs
    else do
      point <- VUM.read table a
      let xs' = if point == True then a : xs else xs
      seek table as xs'

main = do
  n <- getInt
  as <- getIntList
  let as' = ordNub as
  let ds = as \\ as'
  if length as' == 0
    then print 0
    else do
      let m = maximum as'
      table <- VUM.replicate (m + 1) True :: IO (VUM.IOVector Bool)
      fillVector table as' m
      rs <- seek table as' []
      print $ length (filter (\x -> x `notElem` ds) rs)


import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.List (sort, group)
import Data.Heap (Heap)
import qualified Data.Heap as H
import Data.Maybe (fromJust)
import Data.Bool (bool)

main :: IO ()
main = do
  let
    unsafeNext :: Heap (H.Entry Int [Int]) -> (Int, Heap (H.Entry Int [Int]))
    unsafeNext = f . fromJust . H.viewMin
      where
        f :: (H.Entry Int [Int], Heap (H.Entry Int [Int])) -> (Int, Heap (H.Entry Int [Int]))
        f (H.Entry x (x' : xs), h) = (x, H.insert (H.Entry x' xs) h)
    unsafeDropWhile :: (Int -> Bool) -> Heap (H.Entry Int [Int]) -> Heap (H.Entry Int [Int])
    unsafeDropWhile p = f
      where
        f :: Heap (H.Entry Int [Int]) -> Heap (H.Entry Int [Int])
        f h | p x       = f h'
            | otherwise = h
          where
            (x, h') = unsafeNext h :: (Int, Heap (H.Entry Int [Int]))
    f :: [(Int, Int)] -> (Int, Heap (H.Entry Int [Int]))
    f = foldl step (0, H.empty)
      where
        step :: (Int, Heap (H.Entry Int [Int])) -> (Int, Int) -> (Int, Heap (H.Entry Int [Int]))
        step (_, h) (x, l) | H.null h  = (bool l 0 (l == 1), H.insert (H.Entry (2 * x) (map (x *) [3..])) h)
        step (k, h) (x, l) | x < y     = (k + bool l 0 (l == 1), H.insert (H.Entry (2 * x) (map (x *) [3..])) h')
                           | otherwise = (k + l, h'')
          where
            h' = unsafeDropWhile (< x) h :: Heap (H.Entry Int [Int])
            (y, h'') = unsafeNext h' :: (Int, Heap (H.Entry Int [Int]))
  n <- unsafeTextToInt <$> T.getLine :: IO Int
  as <- map unsafeTextToInt . T.words <$> T.getLine :: IO [Int]
  print . (n -) . fst . f . map ((,) <$> head <*> length) . group . sort $ as

unsafeTextToInt :: T.Text -> Int
unsafeTextToInt s = case T.signed T.decimal s of
  Right (n, _) -> n
{-# INLINE unsafeTextToInt #-}


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE TypeApplications #-}
-- {-# LANGUAGE BangPatterns #-}
import Data.Char (isSpace)
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

main = do
  n <- readLn @Int
  xs <- U.unfoldrN n (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  let m = U.maximum xs
  let vec :: U.Vector Int
      vec = U.create $ do
        vec <- UM.replicate (m+1) 0
        U.forM_ xs $ \x -> do
          UM.modify vec (+ 1) x
          forM_ [2*x,3*x..m] $ \i -> do
            UM.modify vec (+ 2) i
        return vec
  print $ length [ () | x <- U.toList xs, vec U.! x <= 1 ]


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

main = do
  li <- BS.getLine
  let Just (n,_) = BS.readInt li
  li <- BS.getLine
  let as = unfoldr (BS.readInt . BS.dropWhile isSpace) li
  let ans = compute n as
  print ans

-- 整列して、複数あるものは問題外。自分と同じ値で割り切れる。
-- 自分より大きい値は気にしなくていい。より小さい値だけが問題。
-- そこに、自分を割り切る数がなければセーフ。
-- セーフな値だけを、今後試せば十分。
compute :: Int -> [Int] -> Int
compute n as = length $ loop [] $ group $ sort as

loop _ [] = []
loop bs ([a]:as)
  | f    = () : loop (a:bs) as
  | True =      loop    bs  as
  where
    f = all ((0 /=).(mod a)) bs
loop bs ((a:_):as) = loop (a:bs) as


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import qualified Data.ByteString.Char8 as C
import Data.List
import Data.Ord
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as UM

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

lim = 1000010
main = do
    n <- readLn :: IO Int
    as <- sort<$>r'

    arr <- UM.replicate lim True

    solve arr (-1) as

    arrF <- U.freeze arr

    print =<< count arr as 0

solve :: UM.IOVector Bool -> Int -> [Int] -> IO ()
solve arr lst [] = return ()
solve arr lst (a:as)
    | lst == a  = do
        UM.write arr a False
        solve arr lst (dropWhile (==a) as)
solve arr lst (a:as) = do
    b <- UM.read arr a
    when b $
        forM_ [a*2,a*3..lim-1] (\i -> UM.write arr i False)
    solve arr a as

count :: UM.IOVector Bool -> [Int] -> Int -> IO Int
count arr [] ac = return ac
count arr (a:as) !ac = do
    b <- UM.read arr a
    if b then count arr as (ac+1)
            else count arr as ac


module Main where

import Debug.Trace
import Data.List

main :: IO ()
main = do
  getLine
  s <- map read . words <$> getLine
  --a `traceShow`
  print $ solve s

solve :: [Int] -> Int
--solve s = (\a -> a `traceShow` length a). parse mx . group $ s'
solve s = length . parse mx . group $ s'
  where
    s' = sort s
    mx = last s'

parse :: Int -> [[Int]] -> [Int]
parse mx (s:ss)
  | length s > 1 = parse mx t
  | otherwise = s':(parse mx t)
  where
    t = if mx `div` s' == 0 then ss else (filter ((/= 0) . (`mod` s') . head) $ ss)
    s' = head s

parse _ [] = []


{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE BangPatterns #-}
module Main (main) where

import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.List as L

main :: IO ()
main = do
  [n] <- readInts
  readInts >>= output . length . g

g :: [Int] -> [Int]
g [] = []
g (x:xs) = x : g (filter (\y -> x `mod`y == 0) xs)

solve :: Int -> [Int] -> _
solve n xs = go 0 1 1 xs xs
  where
    go !c !i !j [] _ = c
    go !c !i !j (y:ys) [] = go (c+1) (i+1) 1 ys xs
    go !c !i !j a@(y:ys) (z:zs) =
      if i == j
        then go c i (j+1) a zs
        else if y `mod` z == 0
              then go c (i+1) 1 ys xs
              else go c i (j+1) a zs

output :: _ -> IO ()
output = print

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine


{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE BangPatterns #-}
module Main (main) where

import qualified Data.ByteString.Char8 as C8
import qualified Data.Char as C
import qualified Data.List as L

main :: IO ()
main = do
  [n] <- readInts
  readInts >>= output . solve n

solve :: Int -> [Int] -> _
solve n xs = go 0 1 1 xs xs
  where
    go !c !i !j [] _ = c
    go !c !i !j (y:ys) [] = go (c+1) (i+1) 1 ys xs
    go !c !i !j a@(y:ys) (z:zs) =
      if i == j
        then go c i (j+1) a zs
        else if y `mod` z == 0
              then go c (i+1) 1 ys xs
              else go c i (j+1) a zs

output :: _ -> IO ()
output = print

-- utils
readInts :: IO [Int]
readInts = L.unfoldr (C8.readInt . C8.dropWhile C.isSpace) <$> C8.getLine