{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

type Range = (Int, Int)
type CombineFunc a = a -> a -> a
type Instruction = Int
type Program = (Int, Int, Int)

defaultProgram :: (Int, Int, Int)
defaultProgram = (0, 0, 0)

combinePrograms :: Program -> Program -> Program
(aDeltaI, aDeltaL, aDeltaR) `combinePrograms` (bDeltaI, bDeltaL, bDeltaR) = (aDeltaI + bDeltaI, fst resultRange, snd resultRange)
    where
        aRange = (aDeltaL, aDeltaR)
        bRange = (bDeltaL + aDeltaI, bDeltaR + aDeltaI)
        resultRange = ((min `on` fst) aRange bRange, (max `on` snd) aRange bRange)

type ProgramArray = UA.Array Int Program
presolve :: Int -> String -> (ProgramArray, ProgramArray)
presolve n instructionsStr = (prefixes, suffixes)
        -- `debug` ("presolve \n\t" ++ show n ++ "\n\t" ++ show instructions ++ "\n\t" ++ show prefixes ++ "\n\t" ++ show suffixes)
    where
        instructions = map (\c -> if c == '+' then 1 else -1) instructionsStr
        programs = map (\i -> (i, min 0 i, max 0 i)) instructions
        prefixes = UA.listArray (0, n) (scanl combinePrograms defaultProgram programs)
        suffixes = UA.listArray (0, n) (scanr combinePrograms defaultProgram programs)

solve :: (ProgramArray, ProgramArray) -> Range -> Int
solve (prefixes, suffixes) (l, r) = resultR - resultL + 1
    where
        lProgram = prefixes UA.! (l - 1)
        rProgram = suffixes UA.! r
        rangeProgram@(_, resultL, resultR) = lProgram `combinePrograms` rProgram

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, q] <- B8.getLine <&> map readIntB8 . B8.words
        s <- B8.getLine <&> head . B8.words <&> B8.unpack
        let preAnswer = presolve n s

        replicateM_ q $ do
            [l, r] <- B8.getLine <&> map readIntB8 . B8.words
            let answer = solve preAnswer (l, r)
            printf "%d\n" answer

{-# LANGUAGE BangPatterns #-}

import           Control.Monad
import qualified Data.Array      as A
import qualified Data.List       as L
import qualified Data.Map.Strict as M
import qualified Data.Set        as S
import System.IO (hSetBuffering, stdin, stdout, BufferMode (..))

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = parseInt <$> C8.getLine

getInts :: IO [Int]
getInts = parseInts <$> C8.getLine

parseInt :: C8.ByteString -> Int
parseInt = fst . fromJust . C8.readInt

parseInts :: C8.ByteString -> [Int]
parseInts = fmap parseInt . C8.words

getInteger :: IO Integer
getInteger = read <$> getLine

getIntegers :: IO [Integer]
getIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine

--
-- MAIN
--

main :: IO ()
main = do
    hSetBuffering stdin NoBuffering
    hSetBuffering stdout NoBuffering
    t:input <- C8.lines <$> C8.getContents
    forM_ (prepareInput input) $ \(prog, ixs) -> do
        let !arrays = buildArrays prog
        let results =  (\(l, r) -> solve arrays l r) <$> ixs
        C8.putStr . C8.unlines $ C8.pack . show <$> results

prepareInput :: [C8.ByteString] -> [(C8.ByteString, [(Int, Int)])]
prepareInput [] = []
prepareInput (nums:prog:lst) = (prog, (\[x, y] -> (x, y)) . parseInts <$> ixs) : prepareInput rest
  where
    [n, m] = parseInts nums
    (ixs, rest) = L.splitAt m lst

buildArrays :: C8.ByteString -> (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int))
buildArrays str = (left2right, right2left)
  where
    nums = fmap c2n $ C8.unpack str

    c2n :: Char -> Int
    c2n c | c == '+' = 1
          | c == '-' = -1
          | otherwise = 0

    left2right :: A.Array Int (Int, Int, Int)
    left2right = A.listArray (0, length nums) $ L.scanl' minMaxFinal (0, 0, 0) nums
    right2left :: A.Array Int (Int, Int, Int)
    right2left = A.listArray (0, length nums) $ reverse $ L.scanl' minMaxFinal (0, 0, 0) $ reverse $ negate <$> nums

minMaxFinal :: (Int, Int, Int) -> Int -> (Int, Int, Int)
minMaxFinal (oldmin, oldmax, oldfin) n =
    let newfin = oldfin + n
    in (min oldmin newfin, max oldmax newfin, newfin)

solve :: (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) -> Int -> Int -> Int
solve (left2right, right2left) l r = ansmax - ansmin + 1
  where
    (lmin, lmax, lfin) = left2right A.! (l - 1)
    (rmin, rmax, rfin) = right2left A.! r

    diff = lfin - rfin
    ansmin = min lmin (rmin + diff)
    ansmax = max lmax (rmax + diff)

{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE OverloadedStrings #-}

import           Control.Monad
import qualified Data.Array      as A
import qualified Data.List       as L
import qualified Data.Map.Strict as M
import qualified Data.Set        as S
import           System.IO       (BufferMode (..), hSetBuffering, stdin, stdout)

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = parseInt <$> C8.getLine

getInts :: IO [Int]
getInts = parseInts <$> C8.getLine

parseInt :: C8.ByteString -> Int
parseInt = fst . fromJust . C8.readInt

parseInts :: C8.ByteString -> [Int]
parseInts = fmap parseInt . C8.words

getInteger :: IO Integer
getInteger = read <$> getLine

getIntegers :: IO [Integer]
getIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine

--
-- MAIN
--

main :: IO ()
main = do
    hSetBuffering stdin NoBuffering
    hSetBuffering stdout NoBuffering
    input <- C8.getContents
    output <- solveProblem input
    C8.putStrLn output

solveProblem :: C8.ByteString -> IO (C8.ByteString)
solveProblem str = pure $ C8.unlines $ getAns <$> preparedInput
  where
    (_:input) = C8.lines str
    preparedInput = prepareInput input

    getAns :: (C8.ByteString, [(Int, Int)]) -> C8.ByteString
    getAns (prog, ixs) = C8.intercalate "\n" $ C8.pack . show <$> results
      where
        !arrays = buildArrays prog
        !results = (\(l, r) -> solve arrays l r) <$> ixs

prepareInput :: [C8.ByteString] -> [(C8.ByteString, [(Int, Int)])]
prepareInput [] = []
prepareInput (nums:prog:lst) = (prog, (\[x, y] -> (x, y)) . parseInts <$> ixs) : prepareInput rest
  where
    [n, m] = parseInts nums
    (ixs, rest) = L.splitAt m lst

buildArrays :: C8.ByteString -> (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int))
buildArrays str = (left2right, right2left)
  where
    nums = fmap c2n $ C8.unpack str

    c2n :: Char -> Int
    c2n c | c == '+' = 1
          | c == '-' = -1
          | otherwise = 0

    left2right :: A.Array Int (Int, Int, Int)
    left2right = A.listArray (0, length nums) $ L.scanl' minMaxFinal (0, 0, 0) nums
    right2left :: A.Array Int (Int, Int, Int)
    right2left = A.listArray (0, length nums) $ reverse $ L.scanl' minMaxFinal (0, 0, 0) $ reverse $ negate <$> nums

minMaxFinal :: (Int, Int, Int) -> Int -> (Int, Int, Int)
minMaxFinal (oldmin, oldmax, oldfin) n =
    let newfin = oldfin + n
    in (min oldmin newfin, max oldmax newfin, newfin)

solve :: (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) -> Int -> Int -> Int
solve (left2right, right2left) l r = ansmax - ansmin + 1
  where
    (lmin, lmax, lfin) = left2right A.! (l - 1)
    (rmin, rmax, rfin) = right2left A.! r

    diff = lfin - rfin
    ansmin = min lmin (rmin + diff)
    ansmax = max lmax (rmax + diff)

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)

import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

type PII = (Int, Int)
type Input = (String, [PII])
type Output = [Int]

input :: Scanner Input
input = do
  n <- int
  m <- int
  s <- str
  qs <- m >< pair int int
  return (s, qs)

output :: Output -> C.ByteString
output = C.unlines . map showB

solve :: Input -> Output
solve (s, qs) = map query qs
  where
    query (l, r) = max mxl mxr - min mnl mnr + 1
      where
        mxl = preMax ! (l - 1)
        mnl = preMin ! (l - 1)
        delta = (preSum ! (l - 1)) - (preSum ! r)
        mxr = (sufMax ! (r + 1)) + delta
        mnr = (sufMin ! (r + 1)) + delta

    psum = scanl (+) 0 . map conv $ s

    inf = 10^9
    preSum, preMin, sufMin, preMax, sufMax :: UArray Int Int
    preSum = listArray (0, length s) psum
    preMin = listArray (0, length s) $ scanl min inf psum
    preMax = listArray (0, length s) $ scanl max (-inf) psum
    sufMin = listArray (1, length s + 1) $ scanr min inf psum
    sufMax = listArray (1, length s + 1) $ scanr max (-inf) psum

    conv :: Char -> Int
    conv '+' = 1
    conv '-' = -1

-------------------------- Template ------------------------------------------
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = read . C.unpack <$> bstr

double :: Scanner Double
double = read . C.unpack <$> bstr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show


import Data.List
import Control.Monad

sums :: [[Int]] -> [Int]
sums = map sum

solve :: [[Int]] -> Int
solve l =
    let rows = sums l
        cols = sums $ transpose l
    in
      sum [if x < y then 1 else 0 | x <- rows, y <- cols]

main = do
  n <- getLine >>= (return . (read::String->Int))
  rows <- forM [1..n] (\_ -> getLine >>= (return . map (read::String->Int) . words))
  print $ solve rows

import Data.List ( transpose )

main = do
    input <- getContents
    let process = putStrLn . show . winningSquares
    mapM_ process $ readLines $ lines input

readLines :: [String] -> [[[Int]]]
readLines [] = []
readLines input = (cases $ take numLines rest):(readLines $ drop numLines rest)
    where
        numLines = (read $ head input)::Int
        rest = tail input

cases :: [String] -> [[Int]]
cases [] = []
cases (x:xs) = list:cases xs
    where
        list = (map read $ words x)::[Int]

winningSquares :: [[Int]] -> Int
winningSquares board = countSquares board 0 0
    where
        lines = map sum board
        columns = map sum (transpose board)

        countSquares :: [[Int]] -> Int -> Int -> Int
        countSquares [] _ _ = 0
        countSquares ([]:ys) i j = countSquares ys (i+1) 0
        countSquares ((x:xs):ys) i j
            | columnSum > lineSum = 1 + rec
            | otherwise           = rec
            where
                columnSum = columns !! j
                lineSum = lines !! i
                rec = countSquares (xs:ys) i (j+1)

import List
m=map sum
s t=length[0|a<-m t,b<-m$transpose t,b>a]
main=interact$show.s.map(map read.words).tail.lines

import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

main :: IO ()
main = do
	nn <- getLine
	inp <- getContents
	let
		n = read nn :: Int
		arr1 = map (\x -> map(\x -> read x :: Int). words $ x). lines $ inp
		arr2 = transpose arr1
		s = sum [if sum (arr1 !! i) < sum (arr2 !! j) then 1 else 0 | i <- [0..n-1], j <- [0..n-1]]
	print s

import Data.List
main = do
    s <- getLine
    let n = read s
    c <- getContents
    let ns = take n $ map (\x -> map read $ words x) $ lines c
    print $ sum.map (\z -> f z (n-1) ns (transpose ns) 0) $ [0..(n-1)]
f z (-1) ns ns' acc = acc
f z n ns ns' acc
    |((sum $ (ns')!!z) > (sum $ ns!!n)) = f z (n-1) ns ns' (acc+1)
    | True = f z (n-1) ns ns' acc

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

-- getInts = fmap (map read . words) getLine
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  n <- readLn
  a <- replicateM n getInts

  let
    ss1 = map sum a
    ss2 = map sum $ transpose a

  print $ length [(s1, s2) | s1 <- ss1, s2 <- ss2, s1 < s2]

import Data.List (transpose, sum)

main = interact $ show . solve . lines where

solve (ns:ss) = cnt where
    n = read ns
    xs = map (map read . take n . words) (take n ss)
    ys = transpose xs
    sx = map sum xs
    sy = map sum ys
    cnt = length [(x, y) | x <- sx, y <- sy, x < y]

--    ghc --make -O Main.hs
import Data.List (transpose)

parse_input :: String -> [[Int]]
parse_input str =
  let strs = lines str
      n = (read::String->Int) $ head $ words $ head strs       -- read n from first line
  in map (map (read::String->Int).words) (take n $ tail strs ) -- read [[Int]] from n next lines

solve :: String -> String
solve in_str =
  let l = parse_input in_str        -- [[Int]] of size n x n
      rSum = map sum l              -- sum by rows
      cSum = map sum $ transpose l  -- sum by columns
  in show $ length $ [True | r <- rSum, c <- cSum, c > r]
  -- show [ (r, c) | r <- rSum, c <- cSum, c > r]

main :: IO ()
main = do interact $ solve

import Array

test :: Array (Int, Int) Int
test = array ((0, 0), (n, n)) ([((0, j), 100) | j <- [0..n]] ++ [((i, j), 1) | i <- [1..n], j <- [0..n]])
  where
    n = 29

readWords :: IO [String]
readWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = readWords >>= return . (map read)

readArray :: Read e => (Int, Int) -> IO (Array (Int, Int) e)
readArray (n, m) = do
    xss <- sequence (replicate n Main.reads)
    return (array ((0, 0), (n-1, m-1))
        [((i, j), xss !! i !! j) | i <- [0..n-1], j <- [0..m-1]])

solve :: Array (Int, Int) Int -> Int
solve a  =  length [(c, r) | c <- sumInCols, r <- sumInRows, c > r]
  where
    ((i0, j0), (i1, j1)) = bounds a
    sumInRows  =  map (\i -> sum (map (\j -> a ! (i, j)) [j0..j1])) [i0..i1]
    sumInCols  =  map (\j -> sum (map (\i -> a ! (i, j)) [i0..i1])) [j0..j1]

main :: IO ()
main  =  do
    n <- readLn
    a <- readArray (n, n)
    print $ solve a

module Main where
main :: IO ()
main = do
    n <- readLn :: IO Int
    let readSquares :: [Int] -> [Int] -> IO ([Int],[Int])
        readSquares rowSums colSums =
            if length rowSums == n
            then do return (rowSums,colSums)
            else do l <- getLine
                    let squares = map (read :: String -> Int) (words l)
                        s = sum squares
                        colSums' = zipWith (+) squares colSums
                    readSquares (s:rowSums) colSums'
    (rowSums, colSums) <- readSquares [] (repeat 0)
    putStrLn (show (sum [1 | rSum <- rowSums, cSum <- colSums, cSum > rSum]))

import Data.Array (listArray, (!))

solve :: [[Int]] -> Int
solve x =
  length $ filter (\[a, b] -> b > a) $ sequence [rowSums, colSums]
  where
    n = length x
    x' = listArray ((1,1), (n, n)) $ concat x
    rowSums = [sum [x' ! (i, j) | j <- [1..n]] | i <- [1..n]] :: [Int]
    colSums = [sum [x' ! (i, j) | i <- [1..n]] | j <- [1..n]] :: [Int]

main = do
  putStrLn . show . solve . map (map read . words) . tail . lines =<< getContents

import Data.List
import Data.Char
import Control.Monad
main = do
  n <- readLn
  g <- replicateM n $ fmap (map read . words) getLine
  let a = map sum g
      b = map sum $ transpose g
      k = [1 | a1 <- a, b1 <- b, a1 < b1]
      in print $ length k

import Data.List
import Control.Monad
main = do
  n <- readLn
  g <- replicateM n $ fmap (map read . words) getLine
  let rs = map sum g
      cs = foldr1 (zipWith (+)) g
  print $ length [ () | r <- rs, c <- cs, c > r ]

import Control.Applicative
import Data.List

main = do
    n <- read <$> getLine
    table <- mapM (\_ -> map read . words <$> getLine) [1..n]
    print $ winnerCount table

winnerCount :: [[Int]] -> Int
winnerCount tbl = length $ filter (isWinner tbl) possibleCoords
    where possibleCoords = [(x, y) | x <- [0..length tbl-1], y <- [0..length tbl-1]]

isWinner :: [[Int]] -> (Int, Int) -> Bool
isWinner tbl (x, y) = sumVertical > sumHorizontal
    where sumVertical = sum $ (transpose tbl) !! x
          sumHorizontal = sum $ tbl !! y

import Data.List
import Control.Applicative

main = getLine >> do
  ss <- map (map read . words) . lines <$> getContents
  print $ solve ss

solve :: [[Int]] -> Int
solve ss = length [(x,y) | x<-xs, y<-ys, x<y]
   where xs = map sum ss
         ys = map sum $ transpose ss

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

-- getInts = fmap (map read . words) getLine
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  n <- readLn
  a <- replicateM n getInts

  let
    ss1 = map sum a
    ss2 = map sum $ transpose a

  print $ length [(s1, s2) | s1 <- ss1, s2 <- ss2, s1 > s2]

import Data.List (transpose)

parse_input :: String -> [[Int]]
parse_input str = tail $ map (map (read::String->Int).words) (lines str)

solve :: String -> String
solve in_str =
  let l = parse_input in_str
      r = map sum l              -- sum by rows
      c = map sum $ transpose l  -- sum by columns
      in show $ length $ [1::Int | rSum <- r, cSum <- c, rSum > cSum]

main :: IO ()
main = do interact $ solve

import Array

readWords :: IO [String]
readWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = readWords >>= return . (map read)

readArray :: Read e => (Int, Int) -> IO (Array (Int, Int) e)
readArray (n, m) = do
    xss <- sequence (replicate n Main.reads)
    return (array ((0, 0), (n-1, m-1))
        [((i, j), xss !! i !! j) | i <- [0..n-1], j <- [0..m-1]])

solve :: Array (Int, Int) Int -> Int
solve a  =  length [(c, r) | c <- sumInCols, r <- sumInRows, c > r]
  where
    ((i0, j0), (i1, j1)) = bounds a
    sumInCols  =  map (\i -> sum (map (\j -> a ! (i, j)) [j0..j1])) [j0..j1]
    sumInRows  =  map (\j -> sum (map (\i -> a ! (i, j)) [i0..i1])) [j0..j1]

main :: IO ()
main  =  do
    n <- readLn
    a <- readArray (n, n)
    print $ solve a

import Data.List
import Data.Char
import Control.Monad
main = do
  n <- readLn
  g <- replicateM n $ fmap (map read . words) getLine
  let a = map sum g
      b = map sum $ transpose g
      k = [1 | a1 <- a, b1 <- b, a1 > b1]
      in print $ length k

import Data.List
import Control.Applicative

main = getLine >> do
  ss <- map (map read . words) . lines <$> getContents
  print $ solve ss

solve :: [[Int]] -> Int
solve ss = length [(x,y) | x<-xs, y<-ys, x<y]
   where ys = map sum ss
         xs = map sum $ transpose ss

import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

main :: IO ()
main = do
	nn <- getLine
	inp <- getContents
	let
		n = read nn :: Int
		arr1 = map (\x -> map(\x -> read x :: Int). words $ x). lines $ inp
		arr2 = transpose arr1
		s = sum [if sum (arr1 !! i) > sum (arr2 !! j) then 1 else 0 | i <- [0..n-1], j <- [0..n-1]]
	print s

import Data.List
import Control.Monad

sums :: [[Int]] -> [Int]
sums = map sum

solve :: [[Int]] -> Int
solve l =
    let rows = sums l
        cols = sums $ transpose l
    in
      sum [if x > y then 1 else 0 | x <- rows, y <- cols]

main = do
  n <- getLine >>= (return . (read::String->Int))
  rows <- forM [1..n] (\_ -> getLine >>= (return . map (read::String->Int) . words))
  print $ solve rows


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


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