An array of positive integers a1, a2, ..., an is given. Let us consider its arbitrary subarray al, al + 1..., ar, where 1 ≤ l ≤ r ≤ n. For every positive integer s denote by Ks the number of occurrences of s into the subarray. We call the power of the subarray the sum of products Ks·Ks·s for every positive integer s. The sum contains only finite number of nonzero summands as the number of different values in the array is indeed finite.You should calculate the power of t given subarrays.

First line contains two integers n and t (1 ≤ n, t ≤ 200000) — the array length and the number of queries correspondingly. Second line contains n positive integers ai (1 ≤ ai ≤ 106) — the elements of the array. Next t lines contain two positive integers l, r (1 ≤ l ≤ r ≤ n) each — the indices of the left and the right ends of the corresponding subarray.

Output t lines, the i-th line of the output should contain single positive integer — the power of the i-th query subarray. Please, do not use %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d).

NoteConsider the following array (see the second sample) and its [2, 7] subarray (elements of the subarray are colored):  Then K1 = 3, K2 = 2, K3 = 1, so the power is equal to 32·1 + 22·2 + 12·3 = 20.

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe         #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import           Data.Bits
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8     as B
import           Data.Char
import qualified Data.Foldable             as F
import           Data.Int
import qualified Data.List                 as L
import           Data.Monoid
import qualified Data.Traversable          as T
import           Data.Word
import           System.IO
--
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    [n, t] <- map read.words <$> getLine
    xs <- L.unfoldr (runStateT parseInt) <$> B.getLine
    lrs <- L.unfoldr (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents
    res <- solve n t xs lrs
    builder <- F.foldrM (\i b -> do
        r <- peekElemOff res i
        return $! int64Dec r <> char7 '\n' <> b
      ) mempty [0..t-1]
    hPutBuilder stdout builder
    free res

nothing :: Int64
nothing = -1

limit :: Int
limit = 1000000

solve :: Int -> Int -> [Int] -> [(Int, Int)] -> IO (Ptr Int64)
solve n t xs lrs = do
    arr <- mallocArray n
    result <- mallocArray t
    freq <- mallocArray (limit + 1)
    pokeArray arr xs
    pokeArray result $ replicate t nothing
    pokeArray freq $ replicate (limit + 1) 0
    let ctx = MoCtx arr result freq
    pokeElemOff freq (head xs) 1
    sorted <- moSort t lrs
    void $ foldlM (step ctx) (MoS 0 0 (fromIntegral $ head xs)) sorted
    free arr >> free freq
    return result

moSort :: Int -> [(Int, Int)] -> IO [MoQuery]
moSort m lrs = do
    left <- mallocArray m :: IO (Ptr Int)
    right <- mallocArray m :: IO (Ptr Int)
    encoded <- mallocArray m :: IO (Ptr Word64)
    let step :: (Ptr Word64, Ptr Word64) -> Int -> IO (Ptr Word64, Ptr Word64)
        step (arr, buf) k = do
          pokeArray buf $ replicate m 0
          freq <- mallocArray 0x10000 :: IO (Ptr Int)
          pokeArray freq $ replicate 0x10000 0
          flip traverse_ [0..m-1] $ \i -> do
              masked <- fromIntegral . (.&. 0xffff).(`unsafeShiftR` k) <$> peekElemOff arr i
              peekElemOff freq masked >>= pokeElemOff freq masked . (+1)
          flip traverse_ [1..0xffff] $ \i -> do
              f <- peekElemOff freq (i - 1)
              peekElemOff freq i >>= pokeElemOff freq i . (+f)
          flip traverse_ [1-m..0] . (.negate) $ \i -> do
              ai <- peekElemOff arr i
              let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff
              j <- subtract 1 <$> peekElemOff freq masked
              pokeElemOff freq masked j
              pokeElemOff buf j ai
          return (buf, arr)

    F.for_ (zipWith mkMoQuery lrs [0..]) $ \q@(MoQ l r qi) -> do
        pokeElemOff left qi l
        pokeElemOff right qi r
        pokeElemOff encoded qi $ moEncode q

    buf <- mallocArray m :: IO (Ptr Word64)
    (sorted, used) <- foldlM step (encoded, buf) [16, 32, 48]
    free used

    res <- T.forM [0..m-1] $ \i -> do
        qi <- moDecode <$> peekElemOff sorted i
        li <- peekElemOff left qi
        ri <- peekElemOff right qi
        return $! MoQ li ri qi
    free left
    free right
    free sorted
    return res

moBlockSize :: Int
moBlockSize = 450
{-# INLINE moBlockSize #-}

data MoQuery = MoQ
    { getL          :: {-# UNPACK #-} !Int
    , getR          :: {-# UNPACK #-} !Int
    , getQueryIndex :: {-# UNPACK #-} !Int
    } deriving Eq

instance Ord MoQuery where
    compare (MoQ lx rx _) (MoQ ly ry _) =
        case compare ql (quot ly moBlockSize) of
            EQ | testBit ql 0 -> compare ry rx
               | otherwise -> compare rx ry
            res -> res
      where
        !ql = quot lx moBlockSize

moEncode :: MoQuery -> Word64
moEncode (MoQ l r qi) = unsafeShiftL l' 36 .|. unsafeShiftL r' 18 .|. fromIntegral qi
  where
    l' = fromIntegral $ quot l moBlockSize
    r' | testBit l' 0 = unsafeShiftL 1 18 - fromIntegral r
       | otherwise = fromIntegral r

moDecode :: Word64 -> Int
moDecode bits = fromIntegral $ bits .&. (unsafeShiftL 1 18 - 1)

data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

mkMoQuery :: (Int, Int) -> Int -> MoQuery
mkMoQuery (l, r) i = MoQ l r i

data MoContext = MoCtx
    { getArray  :: !(Ptr Int)
    , getResult :: !(Ptr Int64)
    , getFreq   :: !(Ptr Int)
    }

step :: MoContext -> MoState -> MoQuery -> IO MoState
step (MoCtx arr result freq) = \(MoS l0 r0 acc) (MoQ l r qi) -> do
    let add = \i -> do
            x <- peekElemOff arr i
            f <- peekElemOff freq x
            pokeElemOff freq x (f + 1)
            acc <- peekElemOff result qi
            pokeElemOff result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x
        {-# INLINE add #-}
    let remove = \i -> do
            x <- peekElemOff arr i
            f <- peekElemOff freq x
            pokeElemOff freq x (f - 1)
            acc <- peekElemOff result qi
            pokeElemOff result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x
        {-# INLINE remove #-}
    pokeElemOff result qi acc
    traverse_ add [r0+1..r]
    traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]
    traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]
    traverse_ remove [l0..l-1]
    res <- peekElemOff result qi
    return $! MoS l r res
{-# INLINE step #-}

intSqrt :: Int -> Int
intSqrt x = floor.sqrt $ fromIntegral x

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

traverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()
traverse_ f = foldr((>>).f)(return())
{-# INLINE traverse_ #-}
foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE FlexibleInstances   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Trans.State
import           Data.Bits
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8     as B
import           Data.Char
import qualified Data.Foldable             as F
import           Data.Function
import           Data.Int
import qualified Data.List                 as L
import           Data.Monoid
import qualified Data.Traversable          as T
import           Data.Word
import           System.IO
--
import           Foreign.ForeignPtr.Safe
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    [n, t] <- map read.words <$> getLine
    xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine
    lrs <- _AMunfoldrN t (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents
    res <- solve n t xs lrs
    builder <- _AMfoldr' (\x b -> int64Dec x <> char7 '\n' <> b) mempty res
    hPutBuilder stdout builder
    hFlush stdout

limit :: Int
limit = 1000000

solve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)
solve _ t arr lrs = do
    result <- _AMunsafeNew t
    freq <- _AMreplicate (limit + 1) 0
    let ctx = MoCtx arr lrs result freq
    h <- _AMunsafeRead arr 0
    _AMunsafeWrite freq h 1
    sorted <- moSort t lrs
    void $ _AMfoldl'M (\mos encoded ->
        step ctx mos $ moDecode encoded
      )(MoS 0 0 (fromIntegral h)) sorted
    return result

moSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)
moSort m lrs = do
    encoded <- _AMunsafeNew m

    _AMifor_ lrs $ \i (l, r) ->
        _AMunsafeWrite encoded i $ moEncode l r i

    radixSort64 encoded
    return encoded

radixSort64 :: CMArray Word64 -> IO ()
radixSort64 arr0@(CMA o n _) = assert (o == 0) $ do
    buf <- _AMunsafeNew n
    freq <- _AMunsafeNew 0x10000
    void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]
  where
    step (arr, buf, freq) k = do
        _AMset buf 0
        _AMset freq 0
        _AMfor_ arr $ \x -> do
            let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff
            _AMunsafeModify freq masked (+1)
        for_ [1..0xffff] $ \i -> do
            f <- _AMunsafeRead freq (i - 1)
            _AMunsafeModify freq i (+f)
        _AMrfor_ arr $ \ai -> do
            let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff
            j <- subtract 1 <$> _AMunsafeRead freq masked
            _AMunsafeWrite freq masked j
            _AMunsafeWrite buf j ai
        return (buf, arr, freq)

moBlockSize :: Int
moBlockSize = 450
{-# INLINE moBlockSize #-}

moEncode :: Int -> Int -> Int -> Word64
moEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi
  where
    l' = fromIntegral $ quot l moBlockSize
    r' | testBit l' 0 = 0xfffff - fromIntegral r
       | otherwise = fromIntegral r
{-# INLINE moEncode #-}

moDecode :: Word64 -> Int
moDecode bits = fromIntegral $ bits .&. 0xfffff
{-# INLINE moDecode #-}

data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

data MoContext = MoCtx
    { getArray  :: !(CMArray Int)
    , getQuery  :: !(CMArray (Int, Int))
    , getResult :: !(CMArray Int64)
    , getFreq   :: !(CMArray Int)
    }

step :: MoContext -> MoState -> Int -> IO MoState
step (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do
    let add i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f + 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x
    let remove i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f - 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x
    _AMunsafeWrite result qi acc
    (l, r) <- _AMunsafeRead query qi
    traverse_ add [r0+1..r]
    traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]
    traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]
    traverse_ remove [l0..l-1]
    res <- _AMunsafeRead result qi
    return $! MoS l r res

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

traverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()
traverse_ f = foldr((>>).f)(return())
{-# INLINE traverse_ #-}

for_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()
for_ = flip traverse_
{-# INLINE for_ #-}

foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

data CMArray a = CMA
    {-# UNPACK #-} !Int            -- ^ offset
    {-# UNPACK #-} !Int            -- ^ length
    {-# UNPACK #-} !(ForeignPtr a) -- ^ array
    deriving (Eq, Show)

_AMlength :: CMArray a -> Int
_AMlength (CMA _ l _) = l

_AMunsafeTail :: CMArray a -> CMArray a
_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc
{-# INLINE _AMunsafeTail #-}

_AMunsafeTake :: Int -> CMArray a -> CMArray a
_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc
{-# INLINE _AMunsafeTake #-}

_AMunsafeDrop :: Int -> CMArray a -> CMArray a
_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc
{-# INLINE _AMunsafeDrop #-}

_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)
_AMunsafeNew n = do
        arr <-  mallocForeignPtrArray n
        return $! CMA 0 n arr
{-# INLINE _AMunsafeNew #-}

_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)
_AMreplicate n x = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr -> do
        flip fix 0 $ \loop !i ->
            when (i < n) $ do
                pokeElemOff arr i x
                loop $ i + 1
        return $ CMA 0 n ptr
{-# INLINE _AMreplicate #-}

_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)
_AMunfoldrN n f x0 = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr ->
        fix `flip` 0 `flip` x0 $ \loop !i !x ->
            case f x of
                Just (y, x') -> do
                    pokeElemOff arr i y
                    loop (i + 1) x'
                Nothing -> return $ CMA 0 n ptr
{-# INLINE _AMunfoldrN #-}

_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a
_AMunsafeRead (CMA _ l ptr) i = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr i
{-# INLINE _AMunsafeRead #-}

_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMunsafeWrite (CMA _ l ptr) i x = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        pokeElemOff arr i x
{-# INLINE _AMunsafeWrite #-}

_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMunsafeModify (CMA _ l ptr) i f = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr i >>= pokeElemOff arr i . f
{-# INLINE _AMunsafeModify #-}

_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a
_AMreadArray (CMA o l ptr) i = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o)
{-# INLINE _AMreadArray #-}

_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMwriteArray (CMA o l ptr) i x = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        pokeElemOff arr (i + o) x
{-# INLINE _AMwriteArray #-}

_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMmodifyArray (CMA o l ptr) i f = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f
{-# INLINE _AMmodifyArray #-}

_AMset :: (Storable a) => CMArray a -> a -> IO ()
_AMset (CMA o l ptr) x = withForeignPtr ptr $ \arr -> do
    let end = o + l
    flip fix o $ \loop !i ->
        when (i < end) $ do
            pokeElemOff arr i x
            loop (i + 1)
{-# INLINE _AMset #-}

_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a
_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f acc ai
{-# INLINE _AMfoldl' #-}

_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a
_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] x0
  where
    step k i = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f ai acc
{-# INLINE _AMfoldr' #-}

_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a
_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        f acc ai >>= k
{-# INLINE _AMfoldl'M #-}

_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMtraverse_ #-}

_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMfor_ = flip _AMtraverse_
{-# INLINE _AMfor_ #-}

_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMrtraverse_ #-}

_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMrfor_ = flip _AMrtraverse_
{-# INLINE _AMrfor_ #-}

_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()
_AMitraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f i ai >> k
{-# INLINE _AMitraverse_ #-}

_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()
_AMifor_ = flip _AMitraverse_
{-# INLINE _AMifor_ #-}

instance (Storable a) => Storable (a, a) where
    sizeOf _ = 2 * sizeOf (undefined :: a)
    {-# INLINE sizeOf #-}
    alignment _ = alignment (undefined :: a)
    {-# INLINE alignment #-}
    peek p  = do
        let pa = castPtr p
        !a <- peek pa
        !b <- peekElemOff pa 1
        return (a, b)
    {-# INLINE peek #-}
    poke p (a, b) = do
        let pa = castPtr p
        poke pa a
        pokeElemOff pa 1 b
    {-# INLINE poke #-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE FlexibleInstances   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Trans.State
import           Data.Bits
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8     as B
import           Data.Char
import qualified Data.Foldable             as F
import           Data.Function
import           Data.Int
import qualified Data.List                 as L
import           Data.Monoid
import qualified Data.Traversable          as T
import           Data.Word
import           System.IO
--
import           Foreign.ForeignPtr.Safe
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    [n, t] <- map read.words <$> getLine
    xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine
    lrs <- _AMunfoldrN t (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents
    res <- solve n t xs lrs
    _AMfree xs >> _AMfree lrs
    builder <- _AMfoldr' (\x b -> int64Dec x <> char7 '\n' <> b) mempty res
    hPutBuilder stdout builder
    hFlush stdout

limit :: Int
limit = 1000000

solve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)
solve _ t arr lrs = do
    result <- _AMunsafeNew t
    freq <- _AMreplicate (limit + 1) 0
    let ctx = MoCtx arr lrs result freq
    h <- _AMunsafeRead arr 0
    _AMunsafeWrite freq h 1
    sorted <- moSort t lrs
    void $ _AMfoldl'M (\mos encoded ->
        step ctx mos $ moDecode encoded
      )(MoS 0 0 (fromIntegral h)) sorted
    _AMfree freq >> _AMfree sorted
    return result

moSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)
moSort m lrs = do
    encoded <- _AMunsafeNew m

    _AMifor_ lrs $ \i (l, r) ->
        _AMunsafeWrite encoded i $ moEncode l r i

    radixSort64 encoded
    return encoded

radixSort64 :: CMArray Word64 -> IO ()
radixSort64 arr0@(CMA o n _) = assert (o == 0) $ do
    buf <- _AMunsafeNew n
    freq <- _AMunsafeNew 0x10000
    void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]
    _AMfree buf >> _AMfree freq
  where
    step (arr, buf, freq) k = do
        _AMset buf 0
        _AMset freq 0
        _AMfor_ arr $ \x -> do
            let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff
            _AMunsafeModify freq masked (+1)
        for_ [1..0xffff] $ \i -> do
            f <- _AMunsafeRead freq (i - 1)
            _AMunsafeModify freq i (+f)
        _AMrfor_ arr $ \ai -> do
            let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff
            j <- subtract 1 <$> _AMunsafeRead freq masked
            _AMunsafeWrite freq masked j
            _AMunsafeWrite buf j ai
        return (buf, arr, freq)

moBlockSize :: Int
moBlockSize = 450
{-# INLINE moBlockSize #-}

moEncode :: Int -> Int -> Int -> Word64
moEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi
  where
    l' = fromIntegral $ quot l moBlockSize
    r' | testBit l' 0 = 0xfffff - fromIntegral r
       | otherwise = fromIntegral r
{-# INLINE moEncode #-}

moDecode :: Word64 -> Int
moDecode bits = fromIntegral $ bits .&. 0xfffff
{-# INLINE moDecode #-}

data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

data MoContext = MoCtx
    { getArray  :: !(CMArray Int)
    , getQuery  :: !(CMArray (Int, Int))
    , getResult :: !(CMArray Int64)
    , getFreq   :: !(CMArray Int)
    }

step :: MoContext -> MoState -> Int -> IO MoState
step (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do
    let add i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f + 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x
    let remove i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f - 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x
    _AMunsafeWrite result qi acc
    (l, r) <- _AMunsafeRead query qi
    traverse_ add [r0+1..r]
    traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]
    traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]
    traverse_ remove [l0..l-1]
    res <- _AMunsafeRead result qi
    return $! MoS l r res

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

traverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()
traverse_ f = foldr((>>).f)(return())
{-# INLINE traverse_ #-}

for_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()
for_ = flip traverse_
{-# INLINE for_ #-}

foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

data CMArray a = CMA
    {-# UNPACK #-} !Int
    {-# UNPACK #-} !Int
    {-# UNPACK #-} !(Ptr a)
    deriving (Eq, Show)

_AMlength :: CMArray a -> Int
_AMlength (CMA _ l _) = l

_AMunsafeTail :: CMArray a -> CMArray a
_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc
{-# INLINE _AMunsafeTail #-}

_AMunsafeTake :: Int -> CMArray a -> CMArray a
_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc
{-# INLINE _AMunsafeTake #-}

_AMunsafeDrop :: Int -> CMArray a -> CMArray a
_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc
{-# INLINE _AMunsafeDrop #-}

_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)
_AMunsafeNew n = do
        arr <-  mallocArray n
        return $! CMA 0 n arr
{-# INLINE _AMunsafeNew #-}

_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)
_AMreplicate n x = do
    arr <- mallocArray n
    flip fix 0 $ \loop !i ->
        when (i < n) $ do
            pokeElemOff arr i x
            loop $ i + 1
    return $ CMA 0 n arr
{-# INLINE _AMreplicate #-}

_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)
_AMunfoldrN n f x0 = do
    arr <- mallocArray n
    fix `flip` 0 `flip` x0 $ \loop !i !x ->
        case f x of
            Just (y, x') -> do
                pokeElemOff arr i y
                loop (i + 1) x'
            Nothing -> return $ CMA 0 n arr
{-# INLINE _AMunfoldrN #-}

_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a
_AMunsafeRead (CMA _ l arr) i = assert (0 <= i && i < l)
    $ peekElemOff arr i
{-# INLINE _AMunsafeRead #-}

_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMunsafeWrite (CMA _ l arr) i x = assert (0 <= i && i < l)
    $ pokeElemOff arr i x
{-# INLINE _AMunsafeWrite #-}

_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMunsafeModify (CMA _ l arr) i f = assert (0 <= i && i < l)
    $ peekElemOff arr i >>= pokeElemOff arr i . f
{-# INLINE _AMunsafeModify #-}

_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a
_AMreadArray (CMA o l arr) i = assert (0 <= i && i < l)
    $ peekElemOff arr (i + o)
{-# INLINE _AMreadArray #-}

_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMwriteArray (CMA o l arr) i x = assert (0 <= i && i < l)
    $ pokeElemOff arr (i + o) x
{-# INLINE _AMwriteArray #-}

_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMmodifyArray (CMA o l arr) i f = assert (0 <= i && i < l)
    $ peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f
{-# INLINE _AMmodifyArray #-}

_AMset :: (Storable a) => CMArray a -> a -> IO ()
_AMset (CMA o l arr) x = do
    let end = o + l
    flip fix o $ \loop !i ->
        when (i < end) $ do
            pokeElemOff arr i x
            loop (i + 1)
{-# INLINE _AMset #-}

_AMfree :: (Storable a) => CMArray a -> IO ()
_AMfree (CMA _ _ arr) = free arr

_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a
_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f acc ai
{-# INLINE _AMfoldl' #-}

_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a
_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] x0
  where
    step k i = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f ai acc
{-# INLINE _AMfoldr' #-}

_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a
_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        f acc ai >>= k
{-# INLINE _AMfoldl'M #-}

_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMtraverse_ #-}

_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMfor_ = flip _AMtraverse_
{-# INLINE _AMfor_ #-}

_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]
  where
    step i k = do
        ai <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMrtraverse_ #-}

_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMrfor_ = flip _AMrtraverse_
{-# INLINE _AMrfor_ #-}

_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()
_AMitraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]
  where
    step i k = do
        ai <- _AMunsafeRead arr i
        f i ai >> k
{-# INLINE _AMitraverse_ #-}

_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()
_AMifor_ = flip _AMitraverse_
{-# INLINE _AMifor_ #-}

instance (Storable a) => Storable (a, a) where
    sizeOf _ = 2 * sizeOf (undefined :: a)
    {-# INLINE sizeOf #-}
    alignment _ = alignment (undefined :: a)
    {-# INLINE alignment #-}
    peek p  = do
        let pa = castPtr p
        !a <- peek pa
        !b <- peekElemOff pa 1
        return (a, b)
    {-# INLINE peek #-}
    poke p (a, b) = do
        let pa = castPtr p
        poke pa a
        pokeElemOff pa 1 b
    {-# INLINE poke #-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE FlexibleInstances   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Trans.State
import           Data.Bits
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8     as B
import           Data.Char
import qualified Data.Foldable             as F
import           Data.Function
import           Data.Int
import qualified Data.List                 as L
import           Data.Monoid
import qualified Data.Traversable          as T
import           Data.Word
import           System.IO
--
import           Foreign.ForeignPtr.Safe
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    [n, t] <- map read.words <$> getLine
    xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine
    lrs <- _AMunfoldrN t (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents
    res <- solve n t xs lrs
    builder <- _AMfoldr' (\x b -> int64Dec x <> char7 '\n' <> b) mempty res
    hPutBuilder stdout builder
    hFlush stdout

limit :: Int
limit = 1000000

solve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)
solve _ t arr lrs = do
    result <- _AMunsafeNew t
    freq <- _AMreplicate (limit + 1) 0
    let ctx = MoCtx arr lrs result freq
    h <- _AMunsafeRead arr 0
    _AMunsafeWrite freq h 1
    sorted <- moSort t lrs
    void $ _AMfoldl'M (\mos encoded ->
        step ctx mos $ moDecode encoded
      )(MoS 0 0 (fromIntegral h)) sorted
    return result

moSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)
moSort m lrs = do
    encoded <- _AMunsafeNew m

    _AMifor_ lrs $ \i (l, r) ->
        _AMunsafeWrite encoded i $ moEncode l r i

    radixSort64 encoded
    return encoded

radixSort64 :: CMArray Word64 -> IO ()
radixSort64 arr0@(CMA o n _) = assert (o == 0) $ do
    buf <- _AMunsafeNew n
    freq <- _AMunsafeNew 0x10000
    void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]
  where
    step (arr, buf, freq) k = do
        _AMset buf 0
        _AMset freq 0
        _AMfor_ arr $ \x -> do
            let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff
            _AMunsafeModify freq masked (+1)
        for_ [1..0xffff] $ \i -> do
            f <- _AMunsafeRead freq (i - 1)
            _AMunsafeModify freq i (+f)
        _AMrfor_ arr $ \ai -> do
            let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff
            j <- subtract 1 <$> _AMunsafeRead freq masked
            _AMunsafeWrite freq masked j
            _AMunsafeWrite buf j ai
        return (buf, arr, freq)

moBlockSize :: Int
moBlockSize = 450
{-# INLINE moBlockSize #-}

moEncode :: Int -> Int -> Int -> Word64
moEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi
  where
    l' = fromIntegral $ quot l moBlockSize
    r' | testBit l' 0 = 0xfffff - fromIntegral r
       | otherwise = fromIntegral r
{-# INLINE moEncode #-}

moDecode :: Word64 -> Int
moDecode bits = fromIntegral $ bits .&. 0xfffff
{-# INLINE moDecode #-}

data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

data MoContext = MoCtx
    { getArray  :: !(CMArray Int)
    , getQuery  :: !(CMArray (Int, Int))
    , getResult :: !(CMArray Int64)
    , getFreq   :: !(CMArray Int)
    }

step :: MoContext -> MoState -> Int -> IO MoState
step (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do
    let add i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f + 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x
    let remove i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f - 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x
    _AMunsafeWrite result qi acc
    (l, r) <- _AMunsafeRead query qi
    traverse_ add [r0+1..r]
    traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]
    traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]
    traverse_ remove [l0..l-1]
    res <- _AMunsafeRead result qi
    return $! MoS l r res

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

traverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()
traverse_ f = foldr((>>).f)(return())
{-# INLINE traverse_ #-}

for_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()
for_ = flip traverse_
{-# INLINE for_ #-}

foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

data CMArray a = CMA
    {-# UNPACK #-} !Int            -- ^ offset
    {-# UNPACK #-} !Int            -- ^ length
    {-# UNPACK #-} !(ForeignPtr a) -- ^ array
    deriving (Eq, Show)

_AMlength :: CMArray a -> Int
_AMlength (CMA _ l _) = l

_AMunsafeTail :: CMArray a -> CMArray a
_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc
{-# INLINE _AMunsafeTail #-}

_AMunsafeTake :: Int -> CMArray a -> CMArray a
_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc
{-# INLINE _AMunsafeTake #-}

_AMunsafeDrop :: Int -> CMArray a -> CMArray a
_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc
{-# INLINE _AMunsafeDrop #-}

_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)
_AMunsafeNew n = do
        arr <-  mallocForeignPtrArray n
        return $! CMA 0 n arr
{-# INLINE _AMunsafeNew #-}

_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)
_AMreplicate n x = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr -> do
        flip fix 0 $ \loop !i ->
            when (i < n) $ do
                pokeElemOff arr i x
                loop $ i + 1
        return $ CMA 0 n ptr
{-# INLINE _AMreplicate #-}

_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)
_AMunfoldrN n f x0 = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr ->
        fix `flip` 0 `flip` x0 $ \loop !i !x ->
            case f x of
                Just (y, x') -> do
                    pokeElemOff arr i y
                    loop (i + 1) x'
                Nothing -> return $ CMA 0 n ptr
{-# INLINE _AMunfoldrN #-}

_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a
_AMunsafeRead (CMA _ l ptr) i = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr i
{-# INLINE _AMunsafeRead #-}

_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMunsafeWrite (CMA _ l ptr) i x = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        pokeElemOff arr i x
{-# INLINE _AMunsafeWrite #-}

_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMunsafeModify (CMA _ l ptr) i f = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr i >>= pokeElemOff arr i . f
{-# INLINE _AMunsafeModify #-}

_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a
_AMreadArray (CMA o l ptr) i = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o)
{-# INLINE _AMreadArray #-}

_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMwriteArray (CMA o l ptr) i x = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        pokeElemOff arr (i + o) x
{-# INLINE _AMwriteArray #-}

_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMmodifyArray (CMA o l ptr) i f = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f
{-# INLINE _AMmodifyArray #-}

_AMset :: (Storable a) => CMArray a -> a -> IO ()
_AMset (CMA o l ptr) x = withForeignPtr ptr $ \arr -> do
    let end = o + l
    flip fix o $ \loop !i ->
        when (i < end) $ do
            pokeElemOff arr i x
            loop (i + 1)
{-# INLINE _AMset #-}

_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a
_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] $ x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f acc ai
{-# INLINE _AMfoldl' #-}

_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a
_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] $ x0
  where
    step k i = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f ai acc
{-# INLINE _AMfoldr' #-}

_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a
_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] $ x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        f acc ai >>= k
{-# INLINE _AMfoldl'M #-}

_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMtraverse_ #-}

_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMfor_ = flip _AMtraverse_
{-# INLINE _AMfor_ #-}

_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMrtraverse_ #-}

_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMrfor_ = flip _AMrtraverse_
{-# INLINE _AMrfor_ #-}

_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()
_AMitraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f i ai >> k
{-# INLINE _AMitraverse_ #-}

_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()
_AMifor_ = flip _AMitraverse_
{-# INLINE _AMifor_ #-}

instance (Storable a) => Storable (a, a) where
    sizeOf _ = 2 * sizeOf (undefined :: a)
    {-# INLINE sizeOf #-}
    alignment _ = alignment (undefined :: a)
    {-# INLINE alignment #-}
    peek p  = do
        let pa = castPtr p
        !a <- peek pa
        !b <- peekElemOff pa 1
        return (a, b)
    {-# INLINE peek #-}
    poke p (a, b) = do
        let pa = castPtr p
        poke pa a
        pokeElemOff pa 1 b
    {-# INLINE poke #-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe         #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import           Data.Bits
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8     as B
import           Data.Char
import qualified Data.Foldable             as F
import           Data.Int
import qualified Data.List                 as L
import           Data.Monoid
import qualified Data.Traversable          as T
import           Data.Word
import           System.IO
--
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    [n, t] <- map read.words <$> getLine
    xs <- L.unfoldr (runStateT parseInt) <$> B.getLine
    lrs <- L.unfoldr (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents
    res <- solve n t xs lrs
    builder <- F.foldrM (\i b -> do
        r <- peekElemOff res i
        return $! int64Dec r <> char7 '\n' <> b
      ) mempty [0..t-1]
    hPutBuilder stdout builder
    free res

nothing :: Int64
nothing = -1

limit :: Int
limit = 1000000

solve :: Int -> Int -> [Int] -> [(Int, Int)] -> IO (Ptr Int64)
solve n t xs lrs = do
    arr <- mallocArray n
    result <- mallocArray t
    freq <- mallocArray (limit + 1)
    pokeArray arr xs
    pokeArray result $ replicate t nothing
    pokeArray freq $ replicate (limit + 1) 0
    let ctx = MoCtx arr result freq
    pokeElemOff freq (head xs) 1
    sorted <- moSort t lrs
    void $ foldlM (step ctx) (MoS 0 0 (fromIntegral $ head xs)) sorted
    free arr >> free freq
    return result

moSort :: Int -> [(Int, Int)] -> IO [MoQuery]
moSort m lrs = do
    left <- mallocArray m :: IO (Ptr Int)
    right <- mallocArray m :: IO (Ptr Int)
    encoded <- mallocArray m :: IO (Ptr Word64)
    let step :: (Ptr Word64, Ptr Word64) -> Int -> IO (Ptr Word64, Ptr Word64)
        step (arr, buf) k = do
          pokeArray buf $ replicate m 0
          freq <- mallocArray 0x10000 :: IO (Ptr Int)
          pokeArray freq $ replicate 0x10000 0
          flip traverse_ [0..m-1] $ \i -> do
              masked <- fromIntegral . (.&. 0xffff).(`unsafeShiftR` k) <$> peekElemOff arr i
              peekElemOff freq masked >>= pokeElemOff freq masked . (+1)
          flip traverse_ [1..0xffff] $ \i -> do
              f <- peekElemOff freq (i - 1)
              peekElemOff freq i >>= pokeElemOff freq i . (+f)
          flip traverse_ [1-m..0] . (.negate) $ \i -> do
              ai <- peekElemOff arr i
              let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff
              j <- subtract 1 <$> peekElemOff freq masked
              pokeElemOff freq masked j
              pokeElemOff buf j ai
          return (buf, arr)

    F.for_ (zipWith mkMoQuery lrs [0..]) $ \q@(MoQ l r qi) -> do
        pokeElemOff left qi l
        pokeElemOff right qi r
        pokeElemOff encoded qi $ moEncode q

    buf <- mallocArray m :: IO (Ptr Word64)
    (sorted, used) <- foldlM step (encoded, buf) [16, 32, 48]
    free used

    res <- T.forM [0..m-1] $ \i -> do
        qi <- moDecode <$> peekElemOff sorted i
        li <- peekElemOff left qi
        ri <- peekElemOff right qi
        return $! MoQ li ri qi
    free left
    free right
    free sorted
    return res

moBlockSize :: Int
moBlockSize = 450
{-# INLINE moBlockSize #-}

data MoQuery = MoQ
    { getL          :: {-# UNPACK #-} !Int
    , getR          :: {-# UNPACK #-} !Int
    , getQueryIndex :: {-# UNPACK #-} !Int
    } deriving Eq

instance Ord MoQuery where
    compare (MoQ lx rx _) (MoQ ly ry _) =
        case compare ql (quot ly moBlockSize) of
            EQ | testBit ql 0 -> compare ry rx
               | otherwise -> compare rx ry
            res -> res
      where
        !ql = quot lx moBlockSize

moEncode :: MoQuery -> Word64
moEncode (MoQ l r qi) = unsafeShiftL l' 36 .|. unsafeShiftL r' 18 .|. fromIntegral qi
  where
    l' = fromIntegral $ quot l moBlockSize
    r' | testBit l' 0 = unsafeShiftL 1 18 - fromIntegral r
       | otherwise = fromIntegral r

moDecode :: Word64 -> Int
moDecode bits = fromIntegral $ bits .&. (unsafeShiftL 1 18 - 1)

data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

mkMoQuery :: (Int, Int) -> Int -> MoQuery
mkMoQuery (l, r) i = MoQ l r i

data MoContext = MoCtx
    { getArray  :: !(Ptr Int)
    , getResult :: !(Ptr Int64)
    , getFreq   :: !(Ptr Int)
    }

step :: MoContext -> MoState -> MoQuery -> IO MoState
-- step ctx  = \st q -> return st
step (MoCtx arr result freq) = \(MoS l0 r0 acc) (MoQ l r qi) -> do
    let add = \i -> do
            x <- peekElemOff arr i
            f <- peekElemOff freq x
            pokeElemOff freq x (f + 1)
            acc <- peekElemOff result qi
            pokeElemOff result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x
        {-# INLINE add #-}
    let remove = \i -> do
            x <- peekElemOff arr i
            f <- peekElemOff freq x
            pokeElemOff freq x (f - 1)
            acc <- peekElemOff result qi
            pokeElemOff result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x
        {-# INLINE remove #-}
    pokeElemOff result qi acc
    traverse_ add [r0+1..r]
    traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]
    traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]
    traverse_ remove [l0..l-1]
    res <- peekElemOff result qi
    return $! MoS l r res
{-# INLINE step #-}

intSqrt :: Int -> Int
intSqrt x = floor.sqrt $ fromIntegral x

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

traverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()
traverse_ f = foldr((>>).f)(return())
{-# INLINE traverse_ #-}
foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

{-# OPTIONS_GHC -Odph -msse4.2 -optc-O3 #-}
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE FlexibleInstances   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Trans.State
import           Data.Bits
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8     as B
import           Data.Char
import qualified Data.Foldable             as F
import           Data.Function
import           Data.Int
import qualified Data.List                 as L
import           Data.Monoid
import qualified Data.Traversable          as T
import           Data.Word
import           System.IO
--
import           Foreign.ForeignPtr.Safe
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    [n, t] <- map read.words <$> getLine
    xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine
    lrs <- _AMunfoldrN t (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents
    res <- solve n t xs lrs
    builder <- _AMfoldr' (\x b -> int64Dec x <> char7 '\n' <> b) mempty res
    hPutBuilder stdout builder
    hFlush stdout

limit :: Int
limit = 1000000

solve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)
solve _ t arr lrs = do
    result <- _AMunsafeNew t
    freq <- _AMreplicate (limit + 1) 0
    let ctx = MoCtx arr lrs result freq
    h <- _AMunsafeRead arr 0
    _AMunsafeWrite freq h 1
    sorted <- moSort t lrs
    void $ _AMfoldl'M (\mos encoded ->
        step ctx mos $ moDecode encoded
      )(MoS 0 0 (fromIntegral h)) sorted
    return result

moSort :: Int -> CMArray (Int, Int) -> IO (CMArray Word64)
moSort m lrs = do
    encoded <- _AMunsafeNew m

    _AMifor_ lrs $ \i (l, r) ->
        _AMunsafeWrite encoded i $ moEncode l r i

    radixSort64 encoded
    return encoded

radixSort64 :: CMArray Word64 -> IO ()
radixSort64 arr0@(CMA o n _) = assert (o == 0) $ do
    buf <- _AMunsafeNew n
    freq <- _AMunsafeNew 0x10000
    void $ foldlM step (arr0, buf, freq) [0, 16, 32, 48]
  where
    step (arr, buf, freq) k = do
        _AMset buf 0
        _AMset freq 0
        _AMfor_ arr $ \x -> do
            let masked = fromIntegral $ unsafeShiftR x k .&. 0xffff
            _AMunsafeModify freq masked (+1)
        for_ [1..0xffff] $ \i -> do
            f <- _AMunsafeRead freq (i - 1)
            _AMunsafeModify freq i (+f)
        _AMrfor_ arr $ \ai -> do
            let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff
            j <- subtract 1 <$> _AMunsafeRead freq masked
            _AMunsafeWrite freq masked j
            _AMunsafeWrite buf j ai
        return (buf, arr, freq)

moBlockSize :: Int
moBlockSize = 450
{-# INLINE moBlockSize #-}

moEncode :: Int -> Int -> Int -> Word64
moEncode l r qi = unsafeShiftL l' 40 .|. unsafeShiftL r' 20 .|. fromIntegral qi
  where
    l' = fromIntegral $ quot l moBlockSize
    r' | testBit l' 0 = 0xfffff - fromIntegral r
       | otherwise = fromIntegral r
{-# INLINE moEncode #-}

moDecode :: Word64 -> Int
moDecode bits = fromIntegral $ bits .&. 0xfffff
{-# INLINE moDecode #-}

data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

data MoContext = MoCtx
    { getArray  :: !(CMArray Int)
    , getQuery  :: !(CMArray (Int, Int))
    , getResult :: !(CMArray Int64)
    , getFreq   :: !(CMArray Int)
    }

step :: MoContext -> MoState -> Int -> IO MoState
step (MoCtx arr query result freq) (MoS l0 r0 acc) qi = do
    let add i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f + 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x
    let remove i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f - 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x
    _AMunsafeWrite result qi acc
    (l, r) <- _AMunsafeRead query qi
    traverse_ add [r0+1..r]
    traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]
    traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]
    traverse_ remove [l0..l-1]
    res <- _AMunsafeRead result qi
    return $! MoS l r res

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

traverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()
traverse_ f = foldr((>>).f)(return())
{-# INLINE traverse_ #-}

for_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()
for_ = flip traverse_
{-# INLINE for_ #-}

foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

data CMArray a = CMA
    {-# UNPACK #-} !Int            -- ^ offset
    {-# UNPACK #-} !Int            -- ^ length
    {-# UNPACK #-} !(ForeignPtr a) -- ^ array
    deriving (Eq, Show)

_AMlength :: CMArray a -> Int
_AMlength (CMA _ l _) = l

_AMunsafeTail :: CMArray a -> CMArray a
_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc
{-# INLINE _AMunsafeTail #-}

_AMunsafeTake :: Int -> CMArray a -> CMArray a
_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc
{-# INLINE _AMunsafeTake #-}

_AMunsafeDrop :: Int -> CMArray a -> CMArray a
_AMunsafeDrop n (CMA o l acc) = CMA (o + min l n) (max 0 $ l - n) acc
{-# INLINE _AMunsafeDrop #-}

_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)
_AMunsafeNew n = do
        arr <-  mallocForeignPtrArray n
        return $! CMA 0 n arr
{-# INLINE _AMunsafeNew #-}

_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)
_AMreplicate n x = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr -> do
        flip fix 0 $ \loop !i ->
            when (i < n) $ do
                pokeElemOff arr i x
                loop $ i + 1
        return $ CMA 0 n ptr
{-# INLINE _AMreplicate #-}

_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)
_AMunfoldrN n f x0 = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr ->
        fix `flip` 0 `flip` x0 $ \loop !i !x ->
            case f x of
                Just (y, x') -> do
                    pokeElemOff arr i y
                    loop (i + 1) x'
                Nothing -> return $ CMA 0 n ptr
{-# INLINE _AMunfoldrN #-}

_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a
_AMunsafeRead (CMA _ l ptr) i = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr i
{-# INLINE _AMunsafeRead #-}

_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMunsafeWrite (CMA _ l ptr) i x = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        pokeElemOff arr i x
{-# INLINE _AMunsafeWrite #-}

_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMunsafeModify (CMA _ l ptr) i f = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr i >>= pokeElemOff arr i . f
{-# INLINE _AMunsafeModify #-}

_AMreadArray :: (Storable a) => CMArray a -> Int -> IO a
_AMreadArray (CMA o l ptr) i = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o)
{-# INLINE _AMreadArray #-}

_AMwriteArray :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMwriteArray (CMA o l ptr) i x = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        pokeElemOff arr (i + o) x
{-# INLINE _AMwriteArray #-}

_AMmodifyArray :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMmodifyArray (CMA o l ptr) i f = assert (0 <= i && i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f
{-# INLINE _AMmodifyArray #-}

_AMset :: (Storable a) => CMArray a -> a -> IO ()
_AMset (CMA o l ptr) x = withForeignPtr ptr $ \arr -> do
    let end = o + l
    flip fix o $ \loop !i ->
        when (i < end) $ do
            pokeElemOff arr i x
            loop (i + 1)
{-# INLINE _AMset #-}

_AMfoldl' :: (Storable b) => (a -> b -> a) -> a -> CMArray b -> IO a
_AMfoldl' f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f acc ai
{-# INLINE _AMfoldl' #-}

_AMfoldr' :: (Storable b) => (b -> a -> a) -> a -> CMArray b -> IO a
_AMfoldr' f x0 arr@(CMA o l _) = foldl step return [o..o+l-1] x0
  where
    step k i = \ !acc -> do
        ai <- _AMunsafeRead arr i
        k $ f ai acc
{-# INLINE _AMfoldr' #-}

_AMfoldl'M :: (Storable b) => (a -> b -> IO a) -> a -> CMArray b -> IO a
_AMfoldl'M f x0 arr@(CMA o l _) = foldr step return [o..o+l-1] x0
  where
    step i k = \ !acc -> do
        ai <- _AMunsafeRead arr i
        f acc ai >>= k
{-# INLINE _AMfoldl'M #-}

_AMtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMtraverse_ f arr@(CMA o l _) = foldr step (return()) [o..o+l-1]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMtraverse_ #-}

_AMfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMfor_ = flip _AMtraverse_
{-# INLINE _AMfor_ #-}

_AMrtraverse_ :: (Storable a) => (a -> IO ()) -> CMArray a -> IO ()
_AMrtraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f ai >> k
{-# INLINE _AMrtraverse_ #-}

_AMrfor_ :: (Storable a) => CMArray a -> (a -> IO ()) -> IO ()
_AMrfor_ = flip _AMrtraverse_
{-# INLINE _AMrfor_ #-}

_AMitraverse_ :: (Storable a) => (Int -> a -> IO ()) -> CMArray a -> IO ()
_AMitraverse_ f arr@(CMA o l _) = foldr (step.negate) (return()) [1-o-l.. -o]
  where
    step i k = do
        ai  <- _AMunsafeRead arr i
        f i ai >> k
{-# INLINE _AMitraverse_ #-}

_AMifor_ :: (Storable a) => CMArray a -> (Int -> a -> IO ()) -> IO ()
_AMifor_ = flip _AMitraverse_
{-# INLINE _AMifor_ #-}

instance (Storable a) => Storable (a, a) where
    sizeOf _ = 2 * sizeOf (undefined :: a)
    {-# INLINE sizeOf #-}
    alignment _ = alignment (undefined :: a)
    {-# INLINE alignment #-}
    peek p  = do
        let pa = castPtr p
        !a <- peek pa
        !b <- peekElemOff pa 1
        return (a, b)
    {-# INLINE peek #-}
    poke p (a, b) = do
        let pa = castPtr p
        poke pa a
        pokeElemOff pa 1 b
    {-# INLINE poke #-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE FlexibleInstances   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Trans.State
import           Data.Bits
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8     as B
import           Data.Char
import           Data.Complex
import qualified Data.Foldable             as F
import           Data.Function
import           Data.Int
import qualified Data.List                 as L
import           Data.Monoid
import qualified Data.Traversable          as T
import           Data.Word
import           System.IO
--
import           Foreign.ForeignPtr.Safe
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    [n, t] <- map read.words <$> getLine
    xs <- _AMunfoldrN n (runStateT parseInt) =<< B.getLine
    lrs <- _AMunfoldrN t (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) =<< B.getContents
    res <- solve n t xs lrs
    builder <- F.foldrM (\i b -> do
        r <- _AMunsafeRead res i
        return $! int64Dec r <> char7 '\n' <> b
      ) mempty [0..t-1]
    hPutBuilder stdout builder
    hFlush stdout

nothing :: Int64
nothing = -1

limit :: Int
limit = 1000000

solve :: Int -> Int -> CMArray Int -> CMArray (Int, Int) -> IO (CMArray Int64)
solve n t arr lrs = do
    result <- _AMunsafeNew t
    freq <- _AMreplicate (limit + 1) 0
    let ctx = MoCtx arr lrs result freq
    h <- _AMunsafeRead arr 0
    _AMunsafeWrite freq h 1
    sorted <- moSort t lrs
    void $ foldlM (\mos i -> do
        qi <- _AMunsafeRead sorted i
        step ctx mos qi
      ) (MoS 0 0 (fromIntegral h)) [0..t-1]
    return result

moSort :: Int -> CMArray (Int, Int) -> IO (CMArray Int)
moSort m lrs = do
    encoded <- _AMunsafeNew m

    for_ [0..m-1] $ \i -> do
        (l, r) <- _AMunsafeRead lrs i
        _AMunsafeWrite encoded i $ moEncode l r i

    radixSort64 encoded
    res <- _AMunsafeNew m
    for_ [0..m-1] $ \i -> do
        qi <- moDecode <$> _AMunsafeRead encoded i
        _AMunsafeWrite res i qi
    return res

radixSort64 :: CMArray Word64 -> IO ()
radixSort64 arr0 = do
    buf <- _AMunsafeNew n
    void $ foldlM step (arr0, buf) [0, 16, 32, 48]
  where
    !n = _AMlength arr0
    step :: (CMArray Word64, CMArray Word64) -> Int -> IO (CMArray Word64, CMArray Word64)
    step (arr, buf) k = do
        _AMset buf 0
        freq <- _AMreplicate 0x10000 (0 :: Int)
        for_ [0..n-1] $ \i -> do
            masked <- fromIntegral . (.&. 0xffff).(`unsafeShiftR` k) <$> _AMunsafeRead arr i
            _AMunsafeModify freq masked (+1)
        for_ [1..0xffff] $ \i -> do
            f <- _AMunsafeRead freq (i - 1)
            _AMunsafeModify freq i (+f)
        for_ [1-n..0] . (.negate) $ \i -> do
            ai <- _AMunsafeRead arr i
            let masked = fromIntegral $ (ai `unsafeShiftR` k) .&. 0xffff
            j <- subtract 1 <$> _AMunsafeRead freq masked
            _AMunsafeWrite freq masked j
            _AMunsafeWrite buf j ai
        return (buf, arr)

moBlockSize :: Int
moBlockSize = 450
{-# INLINE moBlockSize #-}

data MoQuery = MoQ
    { getL          :: {-# UNPACK #-} !Int
    , getR          :: {-# UNPACK #-} !Int
    , getQueryIndex :: {-# UNPACK #-} !Int
    } deriving Eq

instance Ord MoQuery where
    compare (MoQ lx rx _) (MoQ ly ry _) =
        case compare ql (quot ly moBlockSize) of
            EQ | testBit ql 0 -> compare ry rx
               | otherwise -> compare rx ry
            res -> res
      where
        !ql = quot lx moBlockSize

moEncode :: Int -> Int -> Int -> Word64
moEncode l r qi = unsafeShiftL l' 36 .|. unsafeShiftL r' 18 .|. fromIntegral qi
  where
    l' = fromIntegral $ quot l moBlockSize
    r' | testBit l' 0 = unsafeShiftL 1 18 - fromIntegral r
       | otherwise = fromIntegral r

moDecode :: Word64 -> Int
moDecode bits = fromIntegral $ bits .&. (unsafeShiftL 1 18 - 1)

data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

mkMoQuery :: (Int, Int) -> Int -> MoQuery
mkMoQuery (l, r) i = MoQ l r i

data MoContext = MoCtx
    { getArray  :: !(CMArray Int)
    , getQuery  :: !(CMArray (Int, Int))
    , getResult :: !(CMArray Int64)
    , getFreq   :: !(CMArray Int)
    }

step :: MoContext -> MoState -> Int -> IO MoState
step (MoCtx arr query result freq) = \(MoS l0 r0 acc) qi -> do
    let add i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f + 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc + fromIntegral (f + f + 1) * fromIntegral x
    let remove i = do
            x <- _AMunsafeRead arr i
            f <- _AMunsafeRead freq x
            _AMunsafeWrite freq x (f - 1)
            acc <- _AMunsafeRead result qi
            _AMunsafeWrite result qi $! acc - fromIntegral (f + f - 1) * fromIntegral x
    _AMunsafeWrite result qi acc
    (l, r) <- _AMunsafeRead query qi
    traverse_ add [r0+1..r]
    traverse_ (remove.negate) [-r0.. -(r+1)] -- [r0, r0-1..r+1]
    traverse_ (add.negate)[1-l0..(-l)] -- [l0-1, l0-2..l]
    traverse_ remove [l0..l-1]
    res <- _AMunsafeRead result qi
    return $! MoS l r res
{-# INLINE step #-}

intSqrt :: Int -> Int
intSqrt x = floor.sqrt $ fromIntegral x

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

traverse_ :: (Monad m) => (Int -> m ()) -> [Int] -> m ()
traverse_ f = foldr((>>).f)(return())
{-# INLINE traverse_ #-}

for_ :: (Monad m) => [Int] -> (Int -> m ()) -> m ()
for_ = flip traverse_
{-# INLINE for_ #-}

foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

data CMArray a = CMA
    {-# UNPACK #-} !Int     -- ^ offset
    {-# UNPACK #-} !Int     -- ^ length
    {-# UNPACK #-} !(ForeignPtr a) -- ^ array
    deriving (Eq, Show)

_AMlength :: CMArray a -> Int
_AMlength (CMA _ l _) = l

_AMunsafeTail :: CMArray a -> CMArray a
_AMunsafeTail (CMA o l acc) = CMA (o + 1) (l - 1) acc
{-# INLINE _AMunsafeTail #-}

_AMunsafeTake :: Int -> CMArray a -> CMArray a
_AMunsafeTake n (CMA o l acc) = CMA o (min n l) acc
{-# INLINE _AMunsafeTake #-}

_AMunsafeDrop :: Int -> CMArray a -> CMArray a
_AMunsafeDrop n (CMA o l acc) = CMA (o + n) (max 0 $ l - n) acc
{-# INLINE _AMunsafeDrop #-}

_AMunsafeNew :: (Storable a) => Int -> IO (CMArray a)
_AMunsafeNew n = do
        arr <-  mallocForeignPtrArray n
        return $! CMA 0 n arr
{-# INLINE _AMunsafeNew #-}

_AMreplicate :: (Storable a) => Int -> a -> IO (CMArray a)
_AMreplicate n x = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr -> do
        flip fix 0 $ \loop !i ->
            when (i < n) $ do
                pokeElemOff arr i x
                loop $ i + 1
        return $ CMA 0 n ptr
{-# INLINE _AMreplicate #-}

_AMunfoldrN :: (Storable a) => Int -> (b -> Maybe (a, b)) -> b -> IO (CMArray a)
_AMunfoldrN n f x0 = do
    ptr <- mallocForeignPtrArray n
    withForeignPtr ptr $ \arr ->
        fix `flip` 0 `flip` x0 $ \loop !i !x ->
            case f x of
                Just (y, x') -> do
                    pokeElemOff arr i y
                    loop (i + 1) x'
                Nothing -> return $ CMA 0 n ptr
{-# INLINE _AMunfoldrN #-}

_AMunsafeRead :: (Storable a) => CMArray a -> Int -> IO a
_AMunsafeRead (CMA o l ptr) i = assert (i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o)
{-# INLINE _AMunsafeRead #-}

_AMunsafeWrite :: (Storable a) => CMArray a -> Int -> a -> IO ()
_AMunsafeWrite (CMA o l ptr) i x = assert (i < l)
    . withForeignPtr ptr $ \arr ->
        pokeElemOff arr (i + o) x
{-# INLINE _AMunsafeWrite #-}

_AMunsafeModify :: (Storable a) => CMArray a -> Int -> (a -> a) -> IO ()
_AMunsafeModify (CMA o l ptr) i f = assert (i < l)
    . withForeignPtr ptr $ \arr ->
        peekElemOff arr (i + o) >>= pokeElemOff arr (i + o) . f
{-# INLINE _AMunsafeModify #-}

_AMset :: (Storable a) => CMArray a -> a -> IO ()
_AMset (CMA o l ptr) x = withForeignPtr ptr $ \arr ->
    flip fix 0 $ \loop !i ->
        when (i < l) $ do
            pokeElemOff arr (i + o) x
            loop (i + 1)
{-# INLINE _AMset #-}

instance (Storable a) => Storable (a, a) where
    sizeOf _ = 2 * sizeOf (undefined :: a)
    {-# INLINE sizeOf #-}
    alignment _ = alignment (undefined :: a)
    {-# INLINE alignment #-}
    peek p  = do
        let pa = castPtr p
        !a <- peek pa
        !b <- peekElemOff pa 1
        return (a, b)
    {-# INLINE peek #-}
    poke p (a, b) = do
        let pa = castPtr p
        poke pa a
        pokeElemOff pa 1 b
    {-# INLINE poke #-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe         #-}

import           Control.Applicative
import           Control.DeepSeq
import           Control.Monad
import           Control.Monad.ST.Safe
import           Control.Monad.Trans.Class
import           Control.Monad.Trans.Reader
import           Control.Monad.Trans.State
import           Data.Array.ST.Safe
import           Data.Array.Unboxed
import           Data.Bits
import           Data.Bool
import           Data.ByteString.Builder
import qualified Data.ByteString.Char8      as B
import           Data.Char
import qualified Data.Foldable              as F
import           Data.Int
import           Data.Ix
import qualified Data.List                  as L
import           Data.Monoid
import           Data.Ord
import qualified Data.Traversable           as T
import           System.IO
--
import           Data.Time.Clock
import           Foreign.Marshal.Alloc
import           Foreign.Marshal.Array
import           Foreign.Ptr
import           Foreign.Storable

main :: IO ()
main = do
    hSetBinaryMode stdin True
    hSetBinaryMode stdout True
    !start <- getCurrentTime
    [n, t] <- map read.words <$> getLine
    xs <- L.unfoldr (runStateT parseInt) <$> B.getLine
    lrs <- L.unfoldr (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents
    !res <- solve n t xs lrs
    !end <- getCurrentTime
    when (n == 200000) $ do
        print $ diffUTCTime end start
    hPutBuilder stdout $ foldr(\x l -> (int64Dec x <> char7 '\n') <> l) mempty res

nothing :: Int64
nothing = -1

limit :: Int
limit = 1000000

solve :: Int -> Int -> [Int] -> [(Int, Int)] -> IO [Int64]
solve n t xs lrs = do
    result <- mallocArray t
    pokeArray result $ replicate t nothing
    freq <- mallocArray (limit + 1)
    pokeArray freq $ replicate (limit + 1) 0
    flip runReaderT (MoCtx arr result freq) $ do
        lift $ pokeElemOff freq (arr ! UI 0) 1
        void $ foldlM step (MoS 0 0 (fromIntegral $ arr ! UI 0)) sorted
    T.mapM (peekElemOff result) [0..t-1]

  where
    !blockSize = intSqrt n
    arr :: UArray UnsafeIx Int
    !arr = listArray (UI 0, UI (n - 1)) xs
    sorted :: [MoQuery]
    sorted = L.sortBy (comparing $ moCmp blockSize) $ zipWith mkMoQuery lrs [0..]

data MoQuery = MoQ
    { getL          :: {-# UNPACK #-} !Int
    , getR          :: {-# UNPACK #-} !Int
    , getQueryIndex :: {-# UNPACK #-} !Int
    } deriving (Eq, Ord)
data MoState = MoS
    { moL :: {-# UNPACK #-} !Int
    , moR :: {-# UNPACK #-} !Int
    , moA :: {-# UNPACK #-} !Int64
    } deriving (Eq, Ord)

moCmp :: Int -> MoQuery -> (Int, Int)
moCmp blockSize (MoQ l r _)
    | testBit q 0 = (q, -r)
    | otherwise = (q, r)
  where
    !q = l `quot` blockSize

mkMoQuery :: (Int, Int) -> Int -> MoQuery
mkMoQuery (l, r) i = MoQ l r i

data MoContext = MoCtx
    { getArray  :: UArray UnsafeIx Int
    , getResult :: !(Ptr Int64)
    , getFreq   :: !(Ptr Int)
    }

type MoReader a = ReaderT MoContext IO a

add :: Int64 -> Int -> MoReader Int64
add !acc i = ReaderT $ \(MoCtx arr _ freq) -> do
        let !x = arr ! UI i
        f <- peekElemOff freq x
        pokeElemOff freq x $! (f + 1)
        return $! acc + fromIntegral (2 * f + 1) * fromIntegral x
{-# INLINE add #-}

remove :: Int64 -> Int -> MoReader Int64
remove !acc i = ReaderT $ \(MoCtx arr _ freq) -> do
        let !x = arr ! UI i
        f <- peekElemOff freq x
        pokeElemOff freq x $! (f - 1)
        return $! acc - fromIntegral (2 * f - 1) * fromIntegral x
{-# INLINE remove #-}

step :: MoState -> MoQuery -> MoReader MoState
step (MoS l0 r0 acc) (MoQ l r qi) = do
    addR <- foldlM add acc [r0+1..r]
    removeR <- foldlM remove addR [r0, r0-1..r+1]
    addL <- foldlM add removeR [l0-1, l0-2..l]
    removeL <- foldlM remove addL [l0..l-1]
    result <- asks getResult
    lift $ pokeElemOff result qi removeL
    return $ MoS l r removeL
-- {-# INLINE step #-}

intSqrt :: Int -> Int
intSqrt x = floor.sqrt $ fromIntegral x

newtype UnsafeIx = UI{unUI:: Int} deriving (Eq, Ord)

instance Ix UnsafeIx where
    range (_, UI r) = map UI [0..r]
    {-# INLINE range #-}
    index _ (UI i) = i
    {-# INLINE index #-}
    inRange _ _ = True
    {-# INLINE inRange #-}

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace
{-# INLINE parseInt #-}

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt
{-# INLINE parseInt2 #-}

foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe         #-}

import           Control.Applicative
import           Control.DeepSeq
import           Control.Monad
import           Control.Monad.ST.Safe
import           Control.Monad.Trans.Class
import           Control.Monad.Trans.Reader
import           Control.Monad.Trans.State
import           Data.Array.ST.Safe
import           Data.Array.Unboxed
import           Data.Bool
import qualified Data.ByteString.Char8      as B
import           Data.Char
import qualified Data.Foldable              as F
import           Data.Int
import           Data.Ix
import qualified Data.List                  as L
import           Data.Ord

main :: IO ()
main = do
    [n, t] <- map read.words <$> getLine
    xs <- L.unfoldr (runStateT parseInt) <$> B.getLine
    lrs <- L.unfoldr (runStateT $ (\(x,y)->(x-1,y-1)) <$> parseInt2) <$> B.getContents
    putStr.unlines.map show $ solve n t xs lrs

nothing :: Int64
nothing = -1

limit :: Int
limit = 1000000

solve :: Int -> Int -> [Int] -> [(Int, Int)] -> [Int64]
solve n t xs lrs = elems results
  where
    !blockSize = intSqrt n
    arr :: UArray UnsafeIx Int
    !arr = listArray (UI 0, UI (n - 1)) xs
    sorted :: [MoQuery]
    sorted = L.sortBy (comparing $ \q -> (getL q `quot` blockSize, getR q)) $ zipWith mkMoQuery lrs [0..]
    results :: UArray UnsafeIx Int64
    !results = runSTUArray $ do
        result <- newArray (UI 0, UI (t - 1)) nothing :: ST s (STUArray s UnsafeIx Int64)
        freq <- newArray (UI 0, UI limit) 0 :: ST s (STUArray s UnsafeIx Int64)
        flip runReaderT (Mo arr result freq) $ do
            lift $ writeArray freq (UI $ arr! UI 0) 1
            void $ foldlM step ((0, 0), fromIntegral $ arr ! UI 0) sorted
            asks getResult

data MoQuery = MoQ
    { getL          :: {-# UNPACK #-} !Int
    , getR          :: {-# UNPACK #-} !Int
    , getQueryIndex :: {-# UNPACK #-} !Int
    }
mkMoQuery :: (Int, Int) -> Int -> MoQuery
mkMoQuery (l, r) i = MoQ l r i

data MoContext s = Mo
    { getArray  :: UArray UnsafeIx Int
    , getResult :: STUArray s UnsafeIx Int64
    , getFreq   :: STUArray s UnsafeIx Int64
    }

type MoReader s a = ReaderT (MoContext s) (ST s) a

add :: Int64 -> Int -> MoReader s Int64
add acc i = do
    x <- asks $ UI . (! (UI i)) . getArray
    freq <- asks getFreq
    lift $ do
        f <- readArray freq x
        writeArray freq x (f + 1)
        return $! acc + (2 * f + 1) * fromIntegral (unUI x)

remove :: Int64 -> Int -> MoReader s Int64
remove acc i = do
    x <- asks $ UI . (! (UI i)) . getArray
    freq <- asks getFreq
    lift $ do
        f <- readArray freq x
        writeArray freq x (f + 1)
        return $! acc - (2 * f - 1) * fromIntegral (unUI x)

step :: ((Int, Int), Int64) -> MoQuery -> MoReader s ((Int, Int), Int64)
step ((l0, r0), acc) (MoQ l r qi) = do
    addR <- foldlM add acc [r0+1..r]
    removeR <- foldlM remove addR [r0, r0-1..r+1]
    addL <- foldlM add removeR [l0-1, l0-2..l]
    removeL <- foldlM remove addL [l0..l-1]
    result <- asks getResult
    lift $ writeArray result (UI qi) removeL
    return ((l, r), removeL)

intSqrt :: Int -> Int
intSqrt x = floor.sqrt $ fromIntegral x

newtype UnsafeIx = UI{unUI:: Int} deriving (Eq, Ord)

instance Ix UnsafeIx where
    range (UI l, UI r) = map UI [l..r]
    {-# INLINE range #-}
    index _ (UI i) = i
    {-# INLINE index #-}
    inRange _ _ = True
    {-# INLINE inRange #-}

type Parser a = StateT B.ByteString Maybe a

parseInt :: Parser Int
parseInt = StateT $ B.readInt . B.dropWhile isSpace

parseInt2 :: Parser (Int, Int)
parseInt2 = (,) <$> parseInt <*> parseInt

foldlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldlM f a xs=foldr((>=>).flip f)return xs$a
{-# INLINE foldlM #-}


There are $$$n$$$ candies in a row, they are numbered from left to right from $$$1$$$ to $$$n$$$. The size of the $$$i$$$-th candy is $$$a_i$$$.Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.The process consists of moves. During a move, the player eats one or more sweets from her/his side (Alice eats from the left, Bob — from the right).Alice makes the first move. During the first move, she will eat $$$1$$$ candy (its size is $$$a_1$$$). Then, each successive move the players alternate — that is, Bob makes the second move, then Alice, then again Bob and so on.On each move, a player counts the total size of candies eaten during the current move. Once this number becomes strictly greater than the total size of candies eaten by the other player on their previous move, the current player stops eating and the move ends. In other words, on a move, a player eats the smallest possible number of candies such that the sum of the sizes of candies eaten on this move is strictly greater than the sum of the sizes of candies that the other player ate on the previous move. If there are not enough candies to make a move this way, then the player eats up all the remaining candies and the game ends.For example, if $$$n=11$$$ and $$$a=[3,1,4,1,5,9,2,6,5,3,5]$$$, then:  move 1: Alice eats one candy of size $$$3$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3,5]$$$.  move 2: Alice ate $$$3$$$ on the previous move, which means Bob must eat $$$4$$$ or more. Bob eats one candy of size $$$5$$$ and the sequence of candies becomes $$$[1,4,1,5,9,2,6,5,3]$$$.  move 3: Bob ate $$$5$$$ on the previous move, which means Alice must eat $$$6$$$ or more. Alice eats three candies with the total size of $$$1+4+1=6$$$ and the sequence of candies becomes $$$[5,9,2,6,5,3]$$$.  move 4: Alice ate $$$6$$$ on the previous move, which means Bob must eat $$$7$$$ or more. Bob eats two candies with the total size of $$$3+5=8$$$ and the sequence of candies becomes $$$[5,9,2,6]$$$.  move 5: Bob ate $$$8$$$ on the previous move, which means Alice must eat $$$9$$$ or more. Alice eats two candies with the total size of $$$5+9=14$$$ and the sequence of candies becomes $$$[2,6]$$$.  move 6 (the last): Alice ate $$$14$$$ on the previous move, which means Bob must eat $$$15$$$ or more. It is impossible, so Bob eats the two remaining candies and the game ends. Print the number of moves in the game and two numbers:  $$$a$$$ — the total size of all sweets eaten by Alice during the game;  $$$b$$$ — the total size of all sweets eaten by Bob during the game.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases in the input. The following are descriptions of the $$$t$$$ test cases. Each test case consists of two lines. The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of candies. The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$) — the sizes of candies in the order they are arranged from left to right. It is guaranteed that the sum of the values of $$$n$$$ for all sets of input data in a test does not exceed $$$2\cdot10^5$$$.

For each set of input data print three integers — the number of moves in the game and the required values $$$a$$$ and $$$b$$$.

import Data.Sequence

solve :: Bool -> Int -> Int -> Seq Int -> (Int, Int, Int)
solve _ 0 _ Empty = (0,0,0)
solve True cur pre Empty = (1, cur, 0)
solve True cur pre (c:<|cs)
    | cur > pre     = (turns+1, cur+ta,tb)
    | otherwise     = solve True (cur+c) pre cs
    where
        (turns,ta,tb) = solve False 0 cur (c:<|cs)
solve False cur pre Empty = (1, 0, cur)
solve False cur pre (cs:|>c)
    | cur > pre     = (turns+1, ta,cur+tb)
    | otherwise     = solve False (cur+c) pre cs
    where
        (turns,ta,tb) = solve True 0 cur (cs:|>c)

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- getLine
    cs <- readNums
    let (turns,a,b) = solve True 0 0 $ fromList cs
    putStrLn $ unwords $ map show [turns,a,b]
    testCases (t-1)

test :: (Int,Int,Int)
test = solve True 0 0 $ fromList [3,1,4,1,5,9,2,6,5,3,5]

main :: IO ()
main = do
    (t:_) <- readNums
    testCases t

readNums :: (Read n) => IO [n]
readNums = map read . words <$> getLine

main :: IO ()
main = do
  getLine
  ans <- map (solve . map read . words) <$> joiner <$> lines <$> getContents
  mapM_ (putStrLn . f) ans

solve :: [Int] -> [Int]
solve xs =
  let len = head xs
      list = tail xs
      revlist = reverse list
   in function len list revlist 0 0 0 0 (0,0)

-- length list revlist totalEaten turns aliceEaten bobEaten turn(alice/bob)
function :: Int -> [Int] -> [Int] -> Int -> Int -> Int -> Int -> (Int,Int) -> [Int]
function 0 _ _ turns alice bob _ (x,y) = [turns, x, y]

function length list revlist i alice bob 0 (x,y) =
  let remaining = take length list
      (count, size) = eat remaining bob (0, 0)
      list' = drop count list
      alice' = size
      length' = length - count
   in function length' list' revlist (i+1) alice' bob 1 (x+alice',y)

function length list revlist i alice bob 1 (x,y) =
  let remaining = take length revlist
      (count, size) = eat remaining alice (0, 0)
      revlist' = drop count revlist
      bob' = size
      length' = length - count
   in function length' list revlist' (i+1) alice bob' 0 (x, y + bob')

eat :: [Int] -> Int -> (Int, Int) -> (Int, Int)
eat [] _ (count, size) = (count, size)
eat (x : xs) y (count, size)
  | y < 0 = (count, size)
  | otherwise = eat xs (y - x) (count + 1, size + x)

f :: [Int] -> String
f xs = unwords . map show $ xs

joiner :: [String] -> [String]
joiner [] = []
joiner (x : y : xs) = (x ++ " " ++ y) : joiner xs


Mr. Chanek gives you a sequence $$$a$$$ indexed from $$$1$$$ to $$$n$$$. Define $$$f(a)$$$ as the number of indices where $$$a_i = i$$$. You can pick an element from the current sequence and remove it, then concatenate the remaining elements together. For example, if you remove the $$$3$$$-rd element from the sequence $$$[4, 2, 3, 1]$$$, the resulting sequence will be $$$[4, 2, 1]$$$. You want to remove some elements from $$$a$$$ in order to maximize $$$f(a)$$$, using zero or more operations. Find the largest possible $$$f(a)$$$.

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the initial length of the sequence. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2 \cdot 10^5$$$) — the initial sequence $$$a$$$.

Output an integer denoting the largest $$$f(a)$$$ that can be obtained by doing zero or more operations.

NoteIn the first example, $$$f(A) = 3$$$ by doing the following operations.$$$[2,1,\textbf{4},2,5,3,7] \rightarrow [\textbf{2},1,2,5,3,7] \rightarrow [1,2,5,3,\textbf{7}] \rightarrow [1,2,\textbf{5},3] \rightarrow [1,2,3]$$$In the second example, $$$f(A) = 2$$$ and no additional operation is needed.

{-# LANGUAGE ScopedTypeVariables #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
--import Control.Monad
import Data.List
import Data.Array.Unboxed
import qualified Data.IntSet as Set

longestIncreasingSubsequence :: [Int] -> Int
longestIncreasingSubsequence = let
  step :: Set.IntSet -> Int -> Set.IntSet
  step s v = case  Set.lookupGE v s  of
    Nothing -> Set.insert v s
    Just v2 -> Set.insert v $ Set.delete v2 s
  in  Set.size . foldl' step (Set.empty)

stableBucketSortOn :: forall t. (t -> Int) -> (Int, Int) -> [t] -> [t]
stableBucketSortOn fun bnds li = let
  buckets :: Array Int ([t] -> [t])
  buckets = accumArray (\p q -> p . (q :)) id bnds [(fun v, v) | v <- li]
  in  foldr ($) [] buckets

mainFun :: SO
mainFun = do
  ~[n] <- getInts 1
  aLi <- getInts n
  let
    a :: UArray Int Int
    a = listArray (1, n) aLi

    validIxs = [i | (i, ai) <- assocs a, i >= ai]
    opts = stableBucketSortOn (\i -> i - a ! i) (0, n) validIxs
    ans = longestIncreasingSubsequence $ map (a !) opts
  pure $ putInts [ans]

type SP = State [P.ByteString]
type SO = SP Builder

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp


Valera takes part in the Berland Marathon. The marathon race starts at the stadium that can be represented on the plane as a square whose lower left corner is located at point with coordinates (0, 0) and the length of the side equals a meters. The sides of the square are parallel to coordinate axes.As the length of the marathon race is very long, Valera needs to have extra drink during the race. The coach gives Valera a bottle of drink each d meters of the path. We know that Valera starts at the point with coordinates (0, 0) and runs counter-clockwise. That is, when Valera covers a meters, he reaches the point with coordinates (a, 0). We also know that the length of the marathon race equals nd + 0.5 meters. Help Valera's coach determine where he should be located to help Valera. Specifically, determine the coordinates of Valera's positions when he covers d, 2·d, ..., n·d meters.

The first line contains two space-separated real numbers a and d (1 ≤ a, d ≤ 105), given with precision till 4 decimal digits after the decimal point. Number a denotes the length of the square's side that describes the stadium. Number d shows that after each d meters Valera gets an extra drink. The second line contains integer n (1 ≤ n ≤ 105) showing that Valera needs an extra drink n times.

Print n lines, each line should contain two real numbers xi and yi, separated by a space. Numbers xi and yi in the i-th line mean that Valera is at point with coordinates (xi, yi) after he covers i·d meters. Your solution will be considered correct if the absolute or relative error doesn't exceed 10 - 4. Note, that this problem have huge amount of output data. Please, do not use cout stream for output in this problem.

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface #-}

-- Codeforces 404B

import Foreign
import Foreign.C.String
import Foreign.C.Types
import Data.Fixed (mod') -- important !!
import Control.Applicative

main :: IO ()
main = do
    [a, d] <- fmap (map read . words) getLine
    n <- fmap read getLine
    newCString "%.8lf %.8lf\n" >>= solve a d n

foreign import ccall "stdio.h printf"
    c_printf :: CString -> Double -> Double -> IO CInt

solve :: Double -> Double -> Int -> CString -> IO ()
solve a d n format = mapM_ (ps . handle . (*) d . fromIntegral) [1..n] where
    handle p = case p `mod'` (4*a) of
        q | q < a -> (q, 0)
        q | q < 2 * a -> (a, q-a)
        q | q < 3 * a -> (3*a-q, a)
        q | otherwise -> (0, 4*a-q)
    ps (a, b) = c_printf format a b where

{-# LANGUAGE ForeignFunctionInterface #-}

import Foreign
import Foreign.C.String
import Foreign.C.Types
import Data.Fixed
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B8
import Control.Applicative
import System.IO
import Control.DeepSeq
import Text.Printf

main = do
    inp <- words <$> getContents
    solve inp

foreign import ccall "stdio.h printf"
    c_printf :: CString -> Double -> Double -> IO CInt

solve [sa, sd, sn] = do
    format <- newCString "%.6lf %.6lf\n"
    let a = read sa :: Double
        d = read sd :: Double
        n = read sn :: Int
        ps :: (Double, Double) -> IO ()
        ps (a, b) = do
            c_printf format a b
            return ()

        dtoc p = case mod' p (4 * a) of
            q | q < a     -> (q, 0)
            q | q < 2 * a -> (a, q - a)
            q | q < 3 * a -> (3 * a - q, a)
            q | otherwise -> (0, 4 * a - q)
    mapM_ (ps . dtoc . (*)d . fromIntegral) [1 .. n]

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Foreign.C.Types
import Foreign.C.String

main = do
  [a,d,n] <- map read.words <$> getContents
  solve (round n) a d

foreign import ccall unsafe "stdio.h printf"
  c_printf :: CString -> Double -> Double -> IO ()

putAnswer :: Double -> Double -> IO ()
putAnswer x y = B.useAsCString "%f %f\n" $ \fmt-> do
  c_printf fmt x y

solve :: Int -> Double -> Double -> IO ()
solve n a d = go 1
   where
     go i = do
       when (i<=n) $ do
         let q = fromIntegral.floor $ (fromIntegral i*d) / (4*a)
             x = fromIntegral i*d - q*4*a
         if x <= 1*a then  putAnswer x 0
         else if x <= 2*a then putAnswer a (x-a)
         else if x <= 3*a then putAnswer (a-(x-2*a)) a
         else putAnswer 0 (a-(x-3*a))
         go (i+1)

-- Codeforces 404B

import Data.List (intercalate)

main :: IO ()
main = do
    [a, d] <- fmap (map read . words) getLine
    n <- fmap read getLine
    putStrLn $ intercalate "\n" $ solve a d n

solve :: Double -> Double -> Int -> [String]
solve a d n = map path [1..n] where
    path :: Int -> String
    path i = case k `mod` 4 of {
        0 -> str h 0;
        1 -> str a h;
        2 -> str (a-h) a;
        3 -> str 0 (a-h);
    } where
        l = (fromIntegral i) * d
        k = floor (l / a) :: Int
        h = l - (fromIntegral k) * a
        str :: Double -> Double -> String
        str x y = (show x) ++ " " ++ (show y)


The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively.Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separated by dots. For example, the record 0.255.1.123 shows a correct IP address and records 0.256.1.123 and 0.255.1.01 do not. In this problem an arbitrary group of four 8-bit numbers is a correct IP address.Having worked as an administrator for some time, Polycarpus learned that if you know the IP address, you can use the subnet mask to get the address of the network that has this IP addess.The subnet mask is an IP address that has the following property: if we write this IP address as a 32 bit string, that it is representable as "11...11000..000". In other words, the subnet mask first has one or more one bits, and then one or more zero bits (overall there are 32 bits). For example, the IP address 2.0.0.0 is not a correct subnet mask as its 32-bit record looks as 00000010000000000000000000000000.To get the network address of the IP address, you need to perform the operation of the bitwise "and" of the IP address and the subnet mask. For example, if the subnet mask is 255.192.0.0, and the IP address is 192.168.1.2, then the network address equals 192.128.0.0. In the bitwise "and" the result has a bit that equals 1 if and only if both operands have corresponding bits equal to one.Now Polycarpus wants to find all networks to which his IP addresses belong. Unfortunately, Polycarpus lost subnet mask. Fortunately, Polycarpus remembers that his IP addresses belonged to exactly k distinct networks. Help Polycarpus find the subnet mask, such that his IP addresses will belong to exactly k distinct networks. If there are several such subnet masks, find the one whose bit record contains the least number of ones. If such subnet mask do not exist, say so.

The first line contains two integers, n and k (1 ≤ k ≤ n ≤ 105) — the number of IP addresses and networks. The next n lines contain the IP addresses. It is guaranteed that all IP addresses are distinct.

In a single line print the IP address of the subnet mask in the format that is described in the statement, if the required subnet mask exists. Otherwise, print -1.

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Data.Bits
import Data.List
import Data.Maybe
import Data.Word
import qualified Data.ByteString.Char8 as C

newtype IP = IP Word32
  deriving (Eq, Ord, Num, Bits)

instance Show IP where
  show (IP ip) = intercalate "." $ map show $
    reverse $ map (`mod`256) $ take 4 $ iterate (`div`256) $ ip

readInt :: C.ByteString -> Int
readInt = fst . fromJust . C.readInt

parse :: C.ByteString -> IP
parse s = IP $ foldl1 (\i j -> (i * 256 + j)) $ map (fromIntegral . readInt) $ C.split '.' s

clz :: (Num a, Bits a) => a -> Int
clz x
  | x == 0    = n
  | otherwise = m - until (testBit x) pred m
  where
    n = bitSize x
    m = n - 1

main :: IO ()
main = do
  (sn:sm:s) <- fmap C.words C.getContents
  let _ = readInt sn
      m = readInt sm
      a = sort $ map parse s
      b = [i | i <- masks, let j = map (.&. i) a, length (group j) == m]
  if null b
    then putStrLn "-1"
    else putStrLn $ show $ head b
  where
    masks = scanl1 (.|.) $ map (IP . bit) $ [31, 30 .. 0]

import Data.ByteString.Char8 as BS (getLine, readInt, split, words)
import Data.Bits ((.&.), shiftL)
import Data.Maybe (fromJust)
import Data.List (intersperse)
import Data.Set as Set (fromList, size)

main = do
    [n, k] <- fmap (map readInt' . BS.words) BS.getLine
    ips <- fmap (map fromIP) $ sequence $ replicate n BS.getLine
    let subnets = scanl1 (+) $ map (1 `shiftL`) [31,30..0]
    case filter (check k ips) subnets of
        []       -> print (-1)
        subnet:_ -> putStrLn $ toIP subnet

check k ips subnet = (==k) $ Set.size $ Set.fromList $ map (subnet .&.) ips

readInt' = fst . fromJust . BS.readInt

fromIP s = sum $ zipWith (*) (map (256^) [3,2,1,0]) $ map readInt' $ BS.split '.' s

toIP x = concat $ intersperse "." $ reverse $ map (show . (`mod` 256)) $ scanl div x $ replicate 3 256

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map(foldl(\a c->a*10+fromEnum c-fromEnum '0')0).ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr m=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
bsearch f a b | a + 1 == b = a
 | f c = bsearch f a c
 | otherwise = bsearch f c b where
   c = (a + b)`div`2
s k l
  | k == g r = pr r
  | otherwise = "-1"
  where
  r = min 31 $ bsearch f 0 32 + 1
  g i = length(group$map(take i)l)
  f i = g i >= k
solve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl
main=interact$solve.lines

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map read.ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr[]="-1"
pr(m:_)=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
s k l=pr$filter(\i->k==length(nub$map(take i)l))[0..32] where
solve(hl:rl)=s((!!1).map read.words$hl).map(tobits.pip)$rl
main=interact$solve.lines

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map(foldl(\a c->a*10+fromEnum c-fromEnum '0')0).ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr m=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
bsearch f a b | a + 1 == b = a
 | f c = bsearch f a c
 | otherwise = bsearch f c b where
   c = (a + b)`div`2
s k l
  | k == g r = pr r
  | otherwise = "-1"
  where
  r = bsearch f 1 32
  g i = length(group$map(take i)l)
  f i = k >= g i
solve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl
main=interact$solve.lines

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map read.ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr[]="-1"
pr(m:_)=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
s k l=pr$filter(\i->k==length(nub$map(take k)l))[0..32]
solve(hl:rl)=s((!!1).map read.words$hl).map(tobits.pip)$rl
main=interact$solve.lines

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map(foldl(\a c->a*10+fromEnum c-fromEnum '0')0).ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr m=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
bsearch f a b | a + 1 == b = a
 | f c = bsearch f a c
 | otherwise = bsearch f c b where
   c = (a + b)`div`2
s k l
  | k == g r = pr r
  | otherwise = "-1"
  where
  r = min 31 $ bsearch f 1 32 + 1
  g i = length(group$map(take i)l)
  f i = g i >= k
solve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl
main=interact$solve.lines


Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:You are given an array $$$a$$$ of $$$n$$$ integers. You are also given an integer $$$k$$$. Lord Omkar wants you to do $$$k$$$ operations with this array.Define one operation as the following:   Set $$$d$$$ to be the maximum value of your array.  For every $$$i$$$ from $$$1$$$ to $$$n$$$, replace $$$a_{i}$$$ with $$$d-a_{i}$$$. The goal is to predict the contents in the array after $$$k$$$ operations. Please help Ray determine what the final sequence will look like!

Each test contains multiple test cases. The first line contains the number of cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5, 1 \leq k \leq 10^{18}$$$) – the length of your array and the number of operations to perform. The second line of each test case contains $$$n$$$ integers $$$a_{1},a_{2},...,a_{n}$$$ $$$(-10^9 \leq a_{i} \leq 10^9)$$$ – the initial contents of your array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each case, print the final version of array $$$a$$$ after $$$k$$$ operations described above.

NoteIn the first test case the array changes as follows:Initially, the array is $$$[-199, 192]$$$. $$$d = 192$$$.After the operation, the array becomes $$$[d-(-199), d-192] = [391, 0]$$$.

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Control.Monad

main = getLine >>= flip replicateM_ test . read

test = do
  [n, k] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  if odd k
    then putStrLn $ unwords $ map show $ apply as
    else putStrLn $ unwords $ map show $ apply $ apply as

apply as = (maximum as -) <$> as

{-# LANGUAGE OverloadedStrings #-}

import Prelude
import Control.Monad
import Data.Functor
import Data.List
import Data.Maybe
import Data.Int
import Data.Char
import qualified Data.ByteString.Char8 as B8
import Text.Printf

readIntB8 :: B8.ByteString -> Int
readIntB8 = fst . fromJust . B8.readInt

readInt64B8 :: B8.ByteString -> Int64
readInt64B8 = fromInteger . fst . fromJust . B8.readInteger

step :: [Int] -> [Int]
step as = map (\x -> maxA - x) as
    where
        maxA = foldr1 max as

solve :: Int64 -> Int64 -> [Int] -> [Int]
solve n k as =
        if ((k - 1) `mod` 2) == 0
            then firstStepped
            else secondStepped
    where
        firstStepped = step as
        secondStepped = step firstStepped

main :: IO ()
main = do
    t <- readIntB8 <$> B8.getLine
    forM_ [1..t] $ \_ -> do
        [n, k] <- map readInt64B8 <$> B8.words <$> B8.getLine
        as <- map readIntB8 <$> B8.words <$> B8.getLine
        let answer = solve n k as
        forM_ answer $ printf "%d "
        printf "\n"

import Control.Monad (replicateM_)
import Data.Int (Int64)

step :: Int64 -> [Int] -> [Int]
step k li = let
  p = minimum li
  q = maximum li
  in  if  even k  then  map (subtract p) li  else  map (q-) li

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [_n, k] <- map read . words <$> getLine
    a <- map read . words <$> getLine
    putStrLn . unwords $ map show (step k a)