Problem:
Range Sum Query

Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:

add(i, x): add x to ai.

getSum(s, t): print the sum of as, as+1,...,at.

Note that the initial values of ai (i = 1, 2, . . . , n) are 0.

Input

n q
com1 x1 y1
com2 x2 y2
...
comq xq yq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes add(xi, yi) and '1' denotes getSum(xi, yi).

Output

For each getSum operation, print the sum in a line.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 1 ≤ xi ≤ n, 0 ≤ yi ≤ 1000.

If comi is 1, then 1 ≤ xi ≤ n, 1 ≤ yi ≤ n.

Sample Input 1

3 5
0 1 1
0 2 2
0 3 3
1 1 2
1 2 2

Sample Output 1

3
2

Solution in Haskell (judge verdict: Accepted)

import Control.Applicative
import Control.Monad.State

data SegTree a = Leaf a | Seg Int (SegTree a) a (SegTree a) deriving (Show)
type Query = StateT (SegTree Int) IO ()

main = do
    [n,q] <- map read.words<$>getLine
    let initTree = fromList $ replicate n 0
    evalStateT (rsq q) initTree

rsq :: Int -> Query
rsq 0 = return ()
rsq q = do
    getQuery
    rsq (q-1)

getQuery :: Query
getQuery = do
    [c,x,y] <- liftIO $ map read.words<$>getLine
    case c of
      0 -> add x y
      1 -> getSum x y
      2 -> (get >>= \seg -> lift $ print seg)

add :: Int -> Int -> Query
add i x = modify $ addSeg i x

getSum :: Int -> Int -> Query
getSum s t = get >>= (\seg -> lift . print . getSumSeg (s,t) $ seg)

val :: SegTree a -> a
val (Leaf x) = x
val (Seg _ _ x _) = x

size :: SegTree a -> Int
size (Leaf x) = 1
size (Seg s _ _ _) = s

fromList :: Num a => [a] -> SegTree a
fromList xs = fl n xs
    where n = length xs

fl :: Num a => Int -> [a] -> SegTree a
fl _ [x] = Leaf x
fl n xs = Seg s l v r
    where
        n' = n `div` 2
        (xsL, xsR) = splitAt n' xs
        l = fl n' xsL
        r = fl (n-n') xsR
        v = val l + val r
        s = size l + size r

addSeg :: Num a => Int -> a -> SegTree a -> SegTree a
addSeg _ x (Leaf v) = Leaf (v+x)
addSeg i x (Seg n l v r)
  | i <= n' = Seg n left (val left + val r) r
  | otherwise = Seg n l (val l + val right) right
  where
      n' = n `div` 2
      left = addSeg i x l
      right = addSeg (i - n') x r

getSumSeg :: Num a => (Int, Int) -> SegTree a -> a
getSumSeg _ (Leaf x) = x
getSumSeg (s,t) (Seg n l v r)
  | s == 1 && t == n = v
  | t <= n' = getSumSeg (s,t) l
  | s > n' = getSumSeg (s - n', t - n') r
  | s <= n' && t > n' = lsum + rsum
  where n' = n `div` 2
        lsum = getSumSeg (s,n') l
        rsum = getSumSeg (1,t - n') r