Problem:
Score : 800 points

Problem Statement

Given are integers N and X. For each integer k between 0 and X (inclusive), find the answer to the following question, then compute the sum of all those answers, modulo 998244353.

Let us repeat the following operation on the integer k. Operation: if the integer is currently odd, subtract 1 from it and divide it by 2; otherwise, divide it by 2 and add 2^{N-1} to it. How many operations need to be performed until k returns to its original value? (The answer is considered to be 0 if k never returns to its original value.)

Constraints

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

0 \leq X < 2^N

X is given in binary and has exactly N digits. (In case X has less than N digits, it is given with leading zeroes.)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
X

Output

Print the sum of the answers to the questions for the integers between 0 and X (inclusive), modulo 998244353.

Sample Input 1

3
111

Sample Output 1

40

For example, for k=3, the operation changes k as follows: 1,0,4,6,7,3. Therefore the answer for k=3 is 6.

Sample Input 2

6
110101

Sample Output 2

616

Sample Input 3

30
001110011011011101010111011100

Sample Output 3

549320998

Solution in Haskell (GHC 7.10.3) (judge verdict: Wrong Answer)

{-# 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, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -O2 #-}

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.Data
import Data.Typeable
import GHC.Natural
import Numeric.Natural
import GHC.Integer.GMP.Internals (BigNat(..))
import GHC.Generics
import System.IO
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.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
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.Attoparsec.ByteString.Char8 as Atto
import qualified Data.Primitive.ByteArray as PBA
import Debug.Trace
import GHC.Exts (build, Int(..), Int#, Word(..), Word#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#, uncheckedShiftL#, or#, ByteArray#,
                Addr#)
import qualified Data.Vector.Fusion.Bundle as VFB
import qualified Data.Vector.Fusion.Bundle.Monadic as VFBM
import qualified Data.Vector.Fusion.Bundle.Size as VFBS
import qualified Data.Vector.Fusion.Stream.Monadic as VFSM
import qualified Data.Vector.Fusion.Util as VFU
import GHC.Exts (build, Addr#, plusAddr#, ltAddr#, Word(..), Word#,
                 Int(..),
                 indexInt8OffAddr#, isTrue#)

main :: IO ()
main = do
  n <- readInt <$> getLine
  k <- bsToNatural <$> BS.getLine
  print $ query n k

query :: Int -> Natural -> Rem
query !n !k = (2*) $ VU.sum $ VU.zipWith (*) resultVec
              $ VU.map (Rem . quot n) divisors
  where
    nOdd = n `shiftR` countTrailingZeros n
    (oddPrimes, divisors) = prmDivsAndDivs nOdd
    countImmut = VU.map (\ !d -> count n d k) divisors
    resultVec = VU.create $ do
      store <- VU.unsafeThaw countImmut
      VU.forM_ oddPrimes $ \(!p,!e) -> do
        VU.foldM'
          (\ !i (!j,!d,!dDivp) -> do
              !sj <- VUM.read store j
              let Just iNew = (i+) <$> VU.elemIndex dDivp (VU.drop i divisors)
              VUM.modify store (subtract sj) iNew
              return (iNew+1))
          0
          $ VU.map (\(!j,!d,!q,!r) -> (j,d,q))
          $ VU.filter (\(!j,!d,!q,!r) -> r == 0)
          $ VU.map (\(!j,!d) -> let (!q,!r) = quotRem d p in (j,d,q,r))
          $ VU.indexed divisors
      return store

-- d must be an odd divisor of n, which is the number of half-repeats.
count :: Int -> Int -> Natural -> Rem
count !n !d !k = fromIntegral rep + if tested <= k then 1 else 0
  where
    q = n `quot` d --length of half-period
    rep = shiftR k $ n-q
    rev = (bit q - 1) `xor` rep
    fullPer = shiftL rev q .|. rep
    tested = shiftL rep (n-q) .|. makeRepeat (shiftR d 1) fullPer (shiftL q 1)

makeRepeat :: Int -> Natural -> Int -> Natural
makeRepeat !count !nat !len
  | count <= 0 = 0
  | otherwise  = go 0 count nat len
  where
    go !acc !cnt !nat !len
      | cnt == 1  = shiftL acc len .|. nat
      | otherwise = go (if testBit cnt 0 then shiftL acc len .|. nat else acc)
                       (shiftR cnt 1) (shiftL nat len .|. nat) (shiftL len 1)

prmDivsAndDivs :: Int -> (VU.Vector (Int,Int), VU.Vector Int)
prmDivsAndDivs x = (prmDivs, divs)
  where
    !prmDivs = primeDecpFBVec x
    !totSize = VU.foldl' (\ k (!p,!e) -> (e+1) * k) 1 prmDivs
    go :: VUM.MVector s Int -> VU.Vector (Int,Int) -> Int -> Int -> ST s Int
    go !divsMut !ps !off !acc
      | VU.null ps  = (<$ VUM.unsafeWrite divsMut off acc) $! off+1
    go !divsMut !ps !off !acc
      = VU.foldM' (go divsMut ps') off $ VU.iterateN (e+1) (*p) acc
      where ps' = VU.unsafeInit ps; !(!p,!e) = VU.unsafeLast ps
    divs = VU.create $ do
      divsMut <- VUM.new totSize
      !_ <- go divsMut prmDivs 0 1
      return divsMut

#define MODULUS 998244353
type RemRep = Int

modulus :: RemRep
modulus = MODULUS
-- SEE BELOW for the parameter factMax


newtype instance VU.Vector Rem
  = VRem { unVRem :: VU.Vector RemRep }
newtype instance VUM.MVector s Rem
  = VMRem { unVMRem :: VUM.MVector s RemRep }
instance VUM.Unbox Rem

instance VGM.MVector VUM.MVector Rem where
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVMRem) $ VGM.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f x y (VMRem v) -> VMRem $ f x y v)
      $ VGM.basicUnsafeSlice
  {-# INLINE basicOverlaps #-}
  basicOverlaps = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicOverlaps
  {-# INLINE basicUnsafeNew #-}
  basicUnsafeNew = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeNew
  {-# INLINE basicInitialize #-}
  basicInitialize = coerce `asTypeOf` (. unVMRem) $ VGM.basicInitialize
  {-# INLINE basicUnsafeReplicate #-}
  basicUnsafeReplicate !n
    = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeReplicate n
    . unRem
  {-# INLINE basicUnsafeRead #-}
  basicUnsafeRead (VMRem v) !i = VGM.basicUnsafeRead v i >>=
    (return $!) . Rem
  {-# INLINE basicUnsafeWrite #-}
  basicUnsafeWrite (VMRem v) !n = VGM.basicUnsafeWrite v n . unRem
  {-# INLINE basicClear #-}
  basicClear = coerce `asTypeOf` (. unVMRem) $ VGM.basicClear
  {-# INLINE basicSet #-}
  basicSet (VMRem v) = VGM.basicSet v . unRem
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeCopy
  {-# INLINE basicUnsafeMove #-}
  basicUnsafeMove = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeMove
  {-# INLINE basicUnsafeGrow #-}
  basicUnsafeGrow (VMRem v) !n
    = fmap (coerce `asTypeOf` VMRem) $ VGM.basicUnsafeGrow v n

instance VG.Vector VU.Vector Rem where
  {-# INLINE basicUnsafeFreeze #-}
  basicUnsafeFreeze (VMRem v)
    = fmap (coerce `asTypeOf` VRem) $ VG.basicUnsafeFreeze v
  {-# INLINE basicUnsafeThaw #-}
  basicUnsafeThaw (VRem v)
    = fmap (coerce `asTypeOf` VMRem) $ VG.basicUnsafeThaw v
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVRem) $ VG.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f i l (VRem v) -> VRem $ f i l v)
      $ VG.basicUnsafeSlice
  {-# INLINE basicUnsafeIndexM #-}
  basicUnsafeIndexM (VRem v) !i =
    VG.basicUnsafeIndexM v i >>= (return $!) . Rem
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy
    = coerce `asTypeOf` (\f (VMRem mv) (VRem v) -> f mv v)
      $ VG.basicUnsafeCopy
  {-# INLINE elemseq #-}
  elemseq = const seq

newtype Rem = Rem {unRem :: RemRep} deriving Eq
instance Num Rem where
  Rem x - Rem y = Rem $ x-y + if x >= y then 0 else modulus
  negate (Rem x) = Rem $ modulus - x
  x + y = x - (-y)
  fromInteger x = Rem $ fromInteger (x `mod` MODULUS)
  Rem x * Rem y = Rem $ (x * y) `rem` modulus
  abs = id
  signum (Rem 0) = Rem 0
  signum _ = Rem 1

instance Show Rem where
  showsPrec = coerce (showsPrec :: Int -> RemRep -> ShowS)


{-# SPECIALIZE extEuc :: RemRep -> RemRep -> (RemRep,RemRep,RemRep) #-}
{-# INLINE extEuc #-}
extEuc :: (Integral a) => a -> a -> (a,a,a)
extEuc x0 y0
  = loop (signum x0) 0 (abs x0) 0 (signum y0) (abs y0)
  where
    loop !a !b !x !c !d 0 = (a,b,x)
    loop !a !b !x !c !d !y
      = loop c d y (a - q*c) (b - q*d) z
      where
        (q,z) = x `quotRem` y

{-# SPECIALIZE invMod :: RemRep -> RemRep -> Maybe RemRep #-}
{-# INLINE invMod #-}
invMod :: (Integral a) => a -> a -> Maybe a
invMod x m
  | g == 1 = Just r'
  | otherwise = Nothing
  where
    (_,r,g) = extEuc m x
    r' = r `mod` m

instance Fractional Rem where
  recip (Rem x) = Rem $ fromJust $ invMod x modulus
  fromRational p = fromInteger (numerator p) / fromInteger (denominator p)

{-# INLINE floorLog2 #-}
floorLog2 :: FiniteBits i => i -> Int
floorLog2 x = finiteBitSize x - countLeadingZeros x - 1


data PrDecpState i
  = PrDecpState2 !i
  | PrDecpStatePreN !i !Addr# -- ^ N for No exponent
  | PrDecpStatePreE !i !i !Addr# {-# UNPACK #-} !Int -- ^ E for exponent
  | PrDecpStateN !i !i !Addr#
  | PrDecpStateE !i !i !Addr# {-# UNPACK #-} !Int
  | PrDecpStateLast !i
  | PrDecpStateDone


{-# INLINE primeDecpFBVec #-}
primeDecpFBVec :: (Integral i, FiniteBits i, VG.Vector v (i,Int))
  => i -> v (i,Int)
primeDecpFBVec = VG.unstream . primeDecpFBBundle 

{-# INLINE [1] primeDecpFBBundle #-}
primeDecpFBBundle :: (Integral i, FiniteBits i, Monad m)
  => i -> VFBM.Bundle m v (i,Int)
primeDecpFBBundle n
  = VFBM.fromStream (primeDecpFBStream n)
    $ VFBS.Max $ VFU.delay_inline ubDistinctPrimeCount n

{-# INLINE ubDistinctPrimeCount #-}
ubDistinctPrimeCount :: (Integral i, FiniteBits i) => i -> Int
ubDistinctPrimeCount x
  | x < 6      = 1 
  | x < 30     = 2
  | log2x < 7  = 3 -- floorLog2 (2*3*5*7)       = 7
  | log2x < 11 = 4 -- floorLog2 (2*3*5*7*11)    = 11
  | log2x < 14 = 5 -- floorLog2 (2*3*5*7*11*13) = 14
  | otherwise  = 6 + shiftR (log2x-14) 2 -- 17 > 16 = 2^4
  where log2x = floorLog2 x

{-# INLINE [1] primeDecpFBStream #-}
primeDecpFBStream :: forall i m. (Integral i, FiniteBits i, Monad m)
  => i -> VFSM.Stream m (i,Int)
primeDecpFBStream n
  = VFSM.Stream step $ PrDecpState2 n
  where
    preTable# :: Addr#
    preTable# = "\3\5\7"#
    preEnd# = preTable# `plusAddr#` 2#
    {-# NOINLINE addTable# #-}
    addTable# :: Addr#
    addTable# = "\2\4\2\4\6\2\6\4\&\2\4\6\6\2\06\4\02\
                \\6\4\6\8\4\2\4\2\&\4\8\6\4\6\02\4\06\
                \\2\6\6\4\2\4\6\2\&\6\4\2\4\2\10\2\10"#
    addEnd# = addTable# `plusAddr#` 47#
    firstInTable = 11 :: i
    {-# INLINE valNext #-}
    valNext :: i -> Addr# -> (# i, Addr# #)
    valNext x ptr#
      | isTrue# (ptr# `ltAddr#` addEnd#)
      = (# next, ptr# `plusAddr#` 1# #)
      | otherwise = (# next, addTable# #)
      where
        next = (x+) $ fromIntegral
               $ I# (indexInt8OffAddr# ptr# 0#)
    {-# INLINE [0] step #-}
    step (PrDecpState2 n)
      | n <= 1
      = return $ VFSM.Done
      | e <= 0
      = return $ VFSM.Skip $ PrDecpStatePreN n preTable#
      | q > 1
      = return $ VFSM.Yield (2,e) $ PrDecpStatePreN q preTable#
      | otherwise
      = return $ VFSM.Yield (2,e) $ PrDecpStateDone
      where e = countTrailingZeros n
            q = n `unsafeShiftR` e
    step (PrDecpStatePreN n ptr#)
      | r == 0
      = return $ VFSM.Skip $ PrDecpStatePreE q p ptr# 1
      | p >= q
      = return $ VFSM.Yield (n,1) $ PrDecpStateDone
      | isTrue# (ltAddr# ptr# preEnd#)
      = return $ VFSM.Skip $ PrDecpStatePreN n (plusAddr# ptr# 1#)
      | otherwise
      = return $ VFSM.Skip $ PrDecpStateN n firstInTable addTable#
      where !(!q,!r) = n `quotRem` p
            p = fromIntegral $ I# (indexInt8OffAddr# ptr# 0#)
    step (PrDecpStatePreE n p ptr# e)
      | r == 0
      = return $ VFSM.Skip $ PrDecpStatePreE q p ptr# $ e+1
      | p >= q
      = return $ VFSM.Yield (p,e) $ PrDecpStateLast n
      | isTrue# (ltAddr# ptr# preEnd#)
      = return $ VFSM.Yield (p,e) $ PrDecpStatePreN n (plusAddr# ptr# 1#)
      | otherwise
      = return $ VFSM.Yield (p,e) $ PrDecpStateN n firstInTable addTable#
      where !(!q,!r) = n `quotRem` p
    step (PrDecpStateN n p ptr#)
      | r == 0
      = return $ VFSM.Skip $ PrDecpStateE q p ptr# 1
      | p < q
      = let !(# !p1, ptr1# #) = valNext p ptr#
        in return $ VFSM.Skip $ PrDecpStateN n p1 ptr1#
      | otherwise
      = return $ VFSM.Yield (n,1) $ PrDecpStateDone
      where !(!q,!r) = n `quotRem` p
    step (PrDecpStateE n p ptr# e)
      | r == 0
      = return $ VFSM.Skip $ PrDecpStateE q p ptr# $ e+1
      | p < q
      = let !(# !p1, ptr1# #) = valNext p ptr#
        in return $ VFSM.Yield (p,e) $ PrDecpStateN n p1 ptr1#
      | otherwise
      = return $ VFSM.Yield (p,e) $ PrDecpStateLast n
      where !(!q,!r) = n `quotRem` p
    step (PrDecpStateLast 1)
      = return $ VFSM.Done
    step (PrDecpStateLast n)
      = return $ VFSM.Yield (n,1) $ PrDecpStateDone
    step PrDecpStateDone
      = return VFSM.Done


wordSizeInBits = finiteBitSize (undefined :: Word)
sizeOfHSWord = wordSizeInBits `shiftR` 3

-- Only the '1' chars in the input are treated as bit 1;
-- all the other as 0. 
bsToNatural :: BS.ByteString -> Natural
bsToNatural input
  | BS.length str <= wordSizeInBits = NatS# (bsToWord# str)
  | otherwise
     = let !(PBA.ByteArray ba#) = runST $ do
             arr <- PBA.newByteArray (limbLen * sizeOfHSWord)
             let go !i !bs
                   | BS.null bs = return ()
                   | otherwise = do
                       let (rest,now) = BS.splitAt (BS.length bs - 64) bs
                       PBA.writeByteArray arr i $! bsToWord now
                       go (i+1) rest
             go 0 str
             PBA.unsafeFreezeByteArray arr
       in NatJ# (BN# ba#)    
  where
    str = snd $ BS.break (=='1') input
    limbLen = (BS.length str + wordSizeInBits - 1) `shiftR` lenShift
    lenShift | wordSizeInBits == 64 = 6
             | wordSizeInBits == 32 = 5

-- | Given an wordsize long or shorter bytestring consisting of '0' and '1',
--   written in lexical order, returns an corresponding Word#.
{-# INLINE bsToWord# #-}
bsToWord# :: BS.ByteString -> Word#
bsToWord# bs = let !(W# w#) = bsToWord bs in w#

{-# INLINE bsToWord #-}
bsToWord :: BS.ByteString -> Word
bsToWord bs = foldl' (.|.) 0 $ map (shiftR top) $ BS.elemIndices '1' bs
  where !top = bit (BS.length bs - 1)

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

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

#define INS(t,f) instance ShowAsBuilder t where \
  { {-# INLINE showAsBuilder #-}; 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, VG.Vector v a) => ShowAsBuilder (v a) where
  showAsBuilder = v2BSpcSep

{-# INLINE putBuilder #-}
putBuilder = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
{-# INLINE printVecInLines #-}
printVecInLines = putBuilder . v2BLines
{-# INLINE printVecInSpcSepLn #-}
printVecInSpcSepLn = putBuilder . v2BSpcSepLn

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


v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
{-# INLINE v2BSpcSepLnWith #-}
v2BSpcSepLnWith = v2BSpcSepPostfWith "\n"
{-# INLINE v2BSpcSepWith #-}
v2BSpcSepWith = v2BSpcSepPostfWith ""
{-# INLINE v2BConcatWith #-}
v2BConcatWith showFct = VG.foldr ((<>) . showFct) mempty
{-# INLINE v2BLinesWith #-}
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
{-# INLINE v2BSpcSepPostf #-}
v2BSpcSepPostf = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
{-# INLINE v2BSpcSepPostfWith #-}
v2BSpcSepPostfWith = vecToBuilder "" " "

{-# INLINE vecToBuilder #-}
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)


{-# INLINE vecToBuilder_ #-}
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

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

rInt :: StateT BSL.ByteString Maybe Int
IL(rInt) = StateT $ BSL.readInt . BSL.dropWhile (<'!')
rIntS :: StateT BS.ByteString Maybe Int
IL(rIntS) = StateT $ BS.readInt . BS.dropWhile (<'!')

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 N(f,g,h,a,m)\
  IL(f) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e);\
  f=A.newArray;\
  IL(g) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e);\
  g=A.newArray_;\
  IL(h) :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> [e] -> m (a i e);\
  h=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 IL