{-# LANGUAGE BangPatterns #-} {-# LANGUAGE MagicHash #-} import Control.Monad import Control.Monad.State import Data.Bits import Data.Coerce import Data.Char import GHC.Exts import qualified Data.ByteString.Char8 as BSC8 import qualified Data.Vector.Fusion.Stream.Monadic as VFSM import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Unboxed.Mutable as VUM inf :: Int inf = 1 .<<. 30 - 1 {-# INLINE inf #-} main :: IO () main = do n <- readLn :: IO Int xs <- parseN1 n ms <- VUM.unsafeNew (1 .<<. n) :: IO (VUM.IOVector Int) dp <- VUM.replicate (1 .<<. n) inf rep (1 .<<. n) $ \i -> do rep n $ \j -> when (i .&. (1 .<<. j) /= 0) $ VUM.unsafeModify ms (+ xs VU.! j) i VUM.unsafeModify ms (`mod` 1000) i VUM.unsafeWrite dp 0 0 rep (1 .<<. n) $ \i -> rep n $ \j -> do let next = i .|. (1 .<<. j) item <- VUM.unsafeRead ms i let value = max 0 (xs VU.! j - item) dpi <- VUM.unsafeRead dp i VUM.unsafeModify dp (min (dpi + value)) next print =<< VUM.unsafeRead dp (1 .<<. n - 1) type CParser a = StateT BSC8.ByteString Maybe a runCParser :: CParser a -> BSC8.ByteString -> Maybe (a, BSC8.ByteString) runCParser = runStateT {-# INLINE runCParser #-} int :: CParser Int int = coerce $ BSC8.readInt . BSC8.dropWhile isSpace {-# INLINE int #-} parseN1 :: Int -> IO (VU.Vector Int) parseN1 n = VU.unfoldrN n (runCParser int) <$> BSC8.getContents {-# INLINE parseN1 #-} infixl 8 .<<., .>>., .>>>. infixl 6 .^. (.<<.) :: Bits b => b -> Int -> b (.<<.) = unsafeShiftL {-# INLINE (.<<.) #-} (.>>.) :: Bits b => b -> Int -> b (.>>.) = unsafeShiftR {-# INLINE (.>>.) #-} (.>>>.) :: Int -> Int -> Int (.>>>.) (I# x#) (I# i#) = I# (uncheckedIShiftRL# x# i#) {-# INLINE (.>>>.) #-} (.^.) :: Bits b => b -> b -> b (.^.) = xor {-# INLINE (.^.) #-} stream :: Monad m => Int -> Int -> VFSM.Stream m Int stream !l !r = VFSM.Stream step l where step x | x < r = return $ VFSM.Yield x (x + 1) | otherwise = return $ VFSM.Done {-# INLINE [0] step #-} {-# INLINE [1] stream #-} rep :: Monad m => Int -> (Int -> m ()) -> m () rep n = flip VFSM.mapM_ (stream 0 n) {-# INLINE rep #-}