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 Scala (judge verdict: Accepted)

import scala.annotation.tailrec
import net.pushl.io.MyConsole

package net.pushl.datastructure {
  import scala.reflect.ClassTag
  abstract class ASegmentTree[T: ClassTag](_n: Int) {
    protected val init: T
    protected def calc(left: T, right: T): T
    private val n = smallest2Powered(_n)
    private val data = {
      val d = implicitly[ClassTag[T]].newArray(2*n-1)
      (0 until n).foreach(d(_) = init)
      d
    }
    def update(i: Int, v: T) : Unit = {
      val k = i+n-1
      data(k) = v
      @tailrec
      def updateAux(k: Int) : Unit =
        if(k > 0) {
          val p   = parent(k)
          data(p) = calc(data(getLeft(p)),data(getRight(p)))
          updateAux(p)
        }
      updateAux(k)
    }
    // get data of [a,b)
    def get(a: Int, b: Int) : T = get(a,b,0,0,n)

    // l,r is segment of node k.
    protected def get(a: Int, b: Int, k: Int, l: Int, r: Int) : T = {
      if(r <= a || b <= l) init
      else if(a <= l && r <= b) data(k)
      else calc(get(a,b,getLeft(k) ,l,(l+r)/2),
                get(a,b,getRight(k),(l+r)/2,r))
    }

    final private def getLeft (i: Int) = 2*i+1
    final private def getRight(i: Int) = 2*i+2
    final private def parent  (i: Int) = (i-1)/2
    final private def smallest2Powered(n: Int) = {
      @tailrec
      def smallest2PoweredAux(k: Int) : Int = {
        if(k >= n) k
        else smallest2PoweredAux(k*2)
      }
      smallest2PoweredAux(1)
    }
    override def toString() = data.foldLeft("[")(_ + "," + _) + "]"
  }
  class RangeSumQueryTree[T: ClassTag](n: Int)(implicit num: Numeric[T])
                                               extends ASegmentTree[T](n) {
    override val init = num.zero
    override def calc(left: T, right: T) = num.plus(left,right)
  }
  // Numeric does not have INF.
  class RangeMinimumQueryTree(n: Int) extends ASegmentTree[Long](n) {
    override val init = 1l << 30
    override def calc(left: Long, right: Long) = left min right
  }
}

// Document: http://www.scala-lang.org/api/current/#package
// -----------------------------------------------------------------------------
import net.pushl.datastructure.RangeSumQueryTree
class Solver(val stdio: MyConsole){
  import stdio._ // shadow Console.~
  def main() : Unit = {
    val n,q = nextInt
    val rsq = new RangeSumQueryTree[Int](n)
    for(i <- 1 to q){
      val com,_x,_y = nextInt
      if(com == 0){
        val (x,y) = (_x-1,_y)
        rsq(x) = rsq.get(x,x+1) + y
      } else {
        val (x,y) = (_x-1,_y-1)
        println(rsq.get(x,y+1))
      }
    }
  }
}









// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
object Main {
  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
}
package net.pushl.io {
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

    def readIntVector()    : Vector[Int]    = parseLineToVector(() => nextInt)
    def readLongVector()   : Vector[Long]   = parseLineToVector(() => nextLong)
    def readStringVector() : Vector[String] = parseLineToVector(() => nextString)
    def nextInt()          : Int            = nextLong().toInt
    def nextBigInt()       : BigInt         = BigInt(nextString())
    def nextBigDecimal(  ) : BigDecimal     = BigDecimal(nextString())
    def nextDouble()       : Double         = nextString().toDouble
    def nextLong() : Long = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading long failed")
      val sgn = if(peek == '-') -1l else 1
      if(sgn == -1l) ignore(read())
      if(peek < '0' || '9' < peek)
        throw new NumberFormatException(s"readLong found only '-' or no number")
      @tailrec
      def readLong(next: Int, cur: Long) : Long =
        if('0' <= next && next <= '9'){
          ignore(read()) // is equal to next
          readLong(peek, cur*10 + next-'0')
        }
        else if(isEnd(next) || isSpaceOrControl(next))
          sgn*cur
        else
          throw new NumberFormatException(s"readLong found strange byte $next")
      val res = readLong(peek,0)
      skipTrailingSpaces()
      res
    }
    def nextString() : String = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading String failed")
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isSpaceOrControl(next)){
          builder.toString
        }else{
          builder.append(read().toChar) // here we skip.
          appendCode(peek)
        }
      }
      val res = appendCode(peek)
      skipTrailingSpaces()
      res
    }
    // TODO: refactoring to marge nextString
    def readLine() : String = {
      if(isEnd(peek))
        throw new NoSuchElementException("Reading Line failed")
      skipNewline()
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isNewLine(next)){
          builder.toString
        }else{
          builder.append(next.toChar)
          appendCode(read())
        }
      }
      appendCode(read())
    }
    // helpers
    private def ignore[T](x: => T) : Unit = { x; () }
    private[this] var peeked: Option[Int] = None
    private[this] var is_first = true
    protected def read() = {
      val res = peeked match {
        case None    => in.read()
        case Some(a) => { peeked = None; a }
      }
      is_first = false
      res
    }
    private def peek() =
      peeked match {
        case None    => {
          val res = in.read()
          peeked  = Some(res)
          res
        }
        case Some(a) => a
      }
    private def isEnd(c: Int)     = c == -1
    private def isCR(c: Int)      = c == 13
    private def isLF(c: Int)      = c == 10
    private def isNewLine(c: Int) = isLF(c) || isCR(c)
    private def isThereReadable() = !isEnd(peek)
    private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127
    @tailrec
    final private def goNextNotSpaceNorControl() : Unit =
      if(isSpaceOrControl(peek)){
        ignore(read())
        goNextNotSpaceNorControl()
      }
    final private def skipTrailingSpaces() : Unit = {
      @tailrec
      def skipTrailingSpacesAux() : Unit = {
        if(!isNewLine(peek) && isSpaceOrControl(peek)){
          ignore(read())
          skipTrailingSpacesAux()
        }
      }
      skipTrailingSpacesAux()
    }
    final private def skipNewline() : Unit =
      if(!is_first){
        if(isCR(peek))
          ignore(read())
        if(isLF(peek))
          ignore(read())
      }
    private def goNextValuable() : Boolean = {
      goNextNotSpaceNorControl()
      isThereReadable()
    }

    private def parseLineToVector[X](parser: () => X) : Vector[X] = {
      import scala.collection.immutable.VectorBuilder
      val vb = new VectorBuilder[X]()
      skipNewline()
      @tailrec
      def parseLineToVectorAux() : Vector[X] =
        if(isNewLine(peek) || isEnd(peek)) {
          vb.result
        }else{
          vb += parser()
          parseLineToVectorAux()
        }
      parseLineToVectorAux()
    }
  }
}