object Main extends App {
  val n: Int = io.StdIn.readInt()
  val d: Array[Int] = Array.ofDim(n)
  val f: Array[Int] = Array.ofDim(n)
  val adjacencyMatrix: Seq[Array[Int]] =
    for (_ <- (0 until n).toVector)
      yield io.StdIn.readLine().split(" ").drop(2).map(_.toInt - 1)
  loop(0, 1)
  for (i <- 0 until n) println(s"${i+1} ${d(i)} ${f(i)}")

  def loop(current: Int, time: Int): Int = {
    var t: Int = time
    d(current) = time
    for(x <- adjacencyMatrix(current)) {
      if (d(x) == 0) t = loop(x, t+1)
    }
    t += 1
    f(current) = t
    t
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Depth First Search

Depth-first search (DFS) follows the strategy to search ”deeper” in the graph whenever possible. In DFS, edges are recursively explored out of the most recently discovered vertex $v$ that still has unexplored edges leaving it. When all of $v$'s edges have been explored, the search ”backtracks” to explore edges leaving the vertex from which $v$ was discovered.

This process continues until all the vertices that are reachable from the original source vertex have been discovered. If any undiscovered vertices remain, then one of them is selected as a new source and the search is repeated from that source.

DFS timestamps each vertex as follows:

$d[v]$ records when $v$ is first discovered.

$f[v]$ records when the search finishes examining $v$’s adjacency list.

Write a program which reads a directed graph $G = (V, E)$ and demonstrates DFS on the graph based on the following rules:

$G$ is given in an adjacency-list. Vertices are identified by IDs $1, 2,... n$ respectively.

IDs in the adjacency list are arranged in ascending order.

The program should report the discover time and the finish time for each vertex.

When there are several candidates to visit during DFS, the algorithm should select the vertex with the smallest ID.

The timestamp starts with 1.

Input

In the first line, an integer $n$ denoting the number of vertices of $G$ is given. In the next $n$ lines, adjacency lists of $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree. $v_i$ are IDs of vertices adjacent to $u$.

Output

For each vertex, print $id$, $d$ and $f$ separated by a space character in a line. $id$ is ID of the vertex, $d$ and $f$ is the discover time and the finish time respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 100$

Sample Input 1

4
1 1 2
2 1 4
3 0
4 1 3

Sample Output 1

1 1 8
2 2 7
3 4 5
4 3 6

Sample Input 2

6
1 2 2 3
2 2 3 4
3 1 5
4 1 6
5 1 6
6 0

Sample Output 2

1 1 12
2 2 11
3 3 8
4 9 10
5 4 7
6 5 6

This is example for Sample Input 2 (discover/finish)

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


object Main extends App {
    val in = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
    val n = in.next.head
    val tree = in.map(_.drop(2).map(_ - 1)).toList
    val res = List.fill(n)(Array.fill(3)(0))
    solve(1, 0, tree(0))
    def solve(d: Int, id: Int, ids: Array[Int]): Int = {
        if (res(id)(2) == 1) {
            d - 1
        } else {
            res(id)(0) = d
            res(id)(2) = 1
            val f_chld = ids.foldLeft(d)((_d, _id) => solve(_d + 1, _id, tree(_id)))
            res(id)(1) = f_chld + 1
            f_chld + 1
        }
    }
    res.zipWithIndex.foreach{case (x, i) => println(i + 1 + " " + x.init.mkString(" "))}
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


object Main extends App {
    val in = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
    val n = in.next.head
    val tree = in.map(_.drop(2).map(_ - 1)).toList
    val res = List.fill(n)(Array.fill(2)(0))
    def solve(d: Int, id: Int, ids: Array[Int]): Int =
        if (res(id)(0) != 0) {
            d - 1
        } else {
            res(id)(0) = d
            val f_chld = ids.foldLeft(d)((_d, _id) => solve(_d + 1, _id, tree(_id)))
            res(id)(1) = f_chld + 1
            f_chld + 1
        }

    solve(1, 0, tree(0))
    res.zipWithIndex.foreach{case (x, i) => println(i + 1 + " " + x.mkString(" "))}
}


import scala.io.StdIn.{readInt,readLine}

object Main {
  def main(args:Array[String]) = {
    val n = readInt
    val d = (1 to n).map(_ => -1).toArray

    val g = {
      for(i<-0 until n) yield {
        val v = readLine.split(" ").map(_.toInt)
        (for(j<-2 until 2+v(1)) yield v(j) ).toArray
      }
    }.toArray

    var list = Array(1)
    var cnt = 0
    while(list.length>0) {
      println("list="+list.mkString(" "))
      for(e <- list) {
        if(d(e-1) == -1) { d(e-1) = cnt }
        list = g(e-1)
      }
      cnt += 1
    }

    for(i<-0 until n) println((i+1) + " " + d(i))
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Breadth First Search

Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.

Input

In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:

$u$ $k$ $v_1$ $v_2$ ... $v_k$

$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.

Constraints

$1 \leq n \leq 100$

Output

For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.

Sample Input 1

4
1 2 2 4
2 1 4
3 0
4 1 3

Sample Output 1

1 0
2 1
3 2
4 1

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main extends App {

  val Array(n, m) = StdIn.readLine().split(' ').map(_.toInt)
  val groupIndex = Array.fill[Int](n)(-1)
  val friends = Array.ofDim[ArrayBuffer[Int]](n)

  (0 until m).foreach { _ =>
    val a = StdIn.readLine().split(' ').map(_.toInt)
    friends(a(0)) = if(friends(a(0)) == null) ArrayBuffer.empty[Int] else friends(a(0))
    friends(a(0)) += a(1)
    friends(a(1)) = if(friends(a(1)) == null) ArrayBuffer.empty[Int] else friends(a(1))
    friends(a(1)) += a(0)
  }

  def dps(r: Int, groupIdx: Int): Unit = {
    var buff = ArrayBuffer.empty[Int]
    buff += r
    groupIndex(r) = groupIdx
    while(buff.nonEmpty){
      val u = buff.head
      buff = buff.tail
      friends(u).foreach{ v =>
        if(groupIndex(v) == -1){
          groupIndex(v) = groupIdx
          buff += v
        }
      }
    }
  }

  var idx = 1
  (0 until n).foreach { v =>
    if(groupIndex(v) == -1){
      dps(v, idx + 1)
      idx += 1
    }
  }

  val q = StdIn.readLine().toInt
  val sbbuff = new StringBuilder
  //println(s"q: $q")
  (0 until q).foreach { _ =>
    val ql = StdIn.readLine().split(' ').map(_.toInt)
    sbbuff.append(if(groupIndex(ql(0)) == groupIndex(ql(1))){
      f"yes%n"
    } else {
      f"no%n"
    })
  }

  println(sbbuff.toString())

}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Connected Components

Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.

Input

In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$.

In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other).

In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character.

Output

For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise.

Constraints

$2 \leq n \leq 100,000$

$0 \leq m \leq 100,000$

$1 \leq q \leq 10,000$

Sample Input

10 9
0 1
0 2
3 4
5 7
5 6
6 7
6 8
7 8
8 9
3
0 1
5 9
1 3

Sample Output

yes
yes
no


import scala.collection.mutable.ArraySeq;
import scala.reflect.ClassTag;
import scala.io.StdIn.{readInt, readLine};

object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val ig = new IntGraph(n);
        (0 until n).foreach { i =>
            readLine.trim.split(" ").map(_.toInt).zipWithIndex.filter( e => e._1 != -1).foreach { e => ig.add(i, e._2, e._1)}
        }
        val ret = ig.mst;
        println(ret._1.sum);
    }
}
class IntGraph(n: Int) {
    case class Node(value: Int, cost: Int);
    val matrix: Array[List[Node]] = new Array[List[Node]](n).map( e => Nil);

    override def toString(): String = {
        matrix.zipWithIndex.foldLeft[List[String]](Nil) { (list, e) =>
            val nodes = e._1.map( n => n.value.toString + "(" + n.cost.toString + ")");
            e._2.toString + " -> " + nodes.mkString(", ") :: list;
        }.reverse.mkString("\n");
    }

    def add(src: Int, dst: Int, cost: Int): Unit = matrix(src) = Node(dst, cost) :: matrix(src);

    def mst(): (Array[Int], Array[Int]) = {
        val colors = new Array[Int](n); // 0 : 未探索, 1 : 追加候補, 2 : 追加済み
        val parents = new Array[Int](n);
        val distances = new Array[Int](n).map( e => Int.MaxValue);
        val pq = new PriorityQueue[Node](n * n)(Ordering.by((e: Node) => e.cost).reverse);
        var cnt = 0;
        def _mst(): Unit = {
            pq.dequeue match {
                case None => ();
                case Some(Node(minValue, minCost)) if (colors(minValue) == 2)  => _mst;
                case Some(Node(minValue, minCost)) => {
                    colors(minValue) = 2;
                    cnt += 1;
                    if (cnt < n) {
                        matrix(minValue).foreach { e =>
                            if (e.cost < distances(e.value) && colors(e.value) != 2) {
                                colors(e.value) = 1;
                                parents(e.value) = minValue;
                                distances(e.value) = e.cost;
                                pq.enqueue(e);
                            }
                        }
                        _mst;
                    }
                }
            }
        }
        parents(0) = -1;
        distances(0) = 0;
        pq.enqueue(Node(0, distances(0)));
        _mst;
        (distances, parents);
    }
}

class PriorityQueue[A](len: Int)(implicit ord: Ordering[A]) {
    import ord._;
    private val heap = new ArraySeq[A](len);
    var size = 0;

    def isEmpty: Boolean = size == 0;

    def isFull: Boolean = size == len;

    def enqueue(e: A): Unit = {
        def _enqueue(curr: Int): Unit = {
            // if (curr % 2 == 0) right else left
            val parent = if (curr % 2 == 0) (curr - 2) / 2 else (curr - 1) / 2;
            if (parent >= 0 && heap(curr) > heap(parent)) {
                swap(curr, parent);
                _enqueue(parent);
            }
        }
        if (!isFull) {
            heap(size) = e;
            _enqueue(size);
            size += 1;
        }
    }

    def dequeue(): Option[A] = {
        if (isEmpty) {
            None;
        } else {
            val top = heap(0);
            size -= 1;
            heap(0) = heap(size);
            heapify(0);
            Some(top);
        }
    }

    private def heapify(curr: Int): Unit = {
        if (curr < size) {
            val left = curr * 2 + 1;
            val right = curr * 2 + 2;
            if (right < size) {
                val maxIdx = max(curr, left, right);
                if (curr < maxIdx) {
                    swap(curr, maxIdx);
                    heapify(maxIdx);
                }
            } else if (left < size && heap(left) > heap(curr)) {
                swap(curr, left);
            }
        }
    }

    private def max(curr: Int, left: Int, right: Int): Int = {
        if (heap(curr) > heap(left)) {
            if (heap(right) > heap(curr)) right else curr;
        } else {
            if (heap(right) > heap(left)) right else left;
        }
    }

    private def swap(a: Int, b: Int): Unit = {
        val tmp = heap(a);
        heap(a) = heap(b);
        heap(b) = tmp;
    }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Minimum Spanning Tree

For a given weighted graph $G = (V, E)$, find the minimum spanning tree (MST) of $G$ and print total weight of edges belong to the MST.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, a $n \times n$ adjacency matrix $A$ which represents $G$ is given.
$a_{ij}$ denotes the weight of edge connecting vertex $i$ and vertex $j$. If there is no edge between $i$ and $j$, $a_{ij}$ is given by -1.

Output

Print the total weight of the minimum spanning tree of $G$.

Constraints

$1 \leq n \leq 100$

$0 \leq a_{ij} \leq 2,000$ (if $a_{ij} \neq -1$)

$a_{ij} = a_{ji}$

$G$ is a connected graph

Sample Input 1

5
-1 2 3 1 -1
2 -1 -1 4 -1
3 -1 -1 1 1
1 4 1 -1 3
-1 -1 1 3 -1

Sample Output 1

5

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import scala.io.StdIn.readLine
import scala.collection.mutable.ArrayBuffer

object Main {
  def main(args:Array[String]) = {
    val hw = readLine.split(" ").map(_.toInt)
    val fld = (for(i<-0 until hw(0)) yield {
      readLine.trim.map(_.asDigit)
    }).toArray
    val rc = readLine.split(" ").map(_.toInt)
    val pattern = (for(i<-0 until rc(0)) yield {
      readLine.trim.map(_.asDigit)
    }).toArray
    val b = new ArrayBuffer[Array[Int]]

    for(i<-0 to (hw(0)-rc(0))) {
      for(j<-0 to (hw(1)-rc(1))) {
        var m = true
        var k = 0
        var l = 0
        while(m && k<rc(0)) {
          if(fld(i+k)(j+l) != pattern(k)(l)) m = false
          if(l==rc(1)-1) { k+=1;l=0 }
          else l += 1
        }
        if(m) b+= Array(i,j)
      }
    }
    println{
      b.sortWith((x,y)=>if(x(0)<y(0)) true else if(x(0)==y(0) && x(1)<y(1)) true else false)
        .map(_.mkString(" ")).mkString("\n")
    }
  }
}

Pattern Search

Find places where a R × C pattern is found within a H × W region. Print top-left coordinates (i, j) of sub-regions where the pattern found. The top-left and bottom-right coordinates of the region is (0, 0) and (H-1, W-1) respectively.

Input

In the first line, two integers H and W are given. In the following H lines, i-th lines of the region are given.

In the next line, two integers R and C are given. In the following R lines, i-th lines of the pattern are given.

output

For each sub-region found, print a coordinate i and j separated by a space character in a line. Print the coordinates in ascending order of the row numbers (i), or the column numbers (j) in case of a tie.

Constraints

1 ≤ H, W ≤ 1000

1 ≤ R, C ≤ 1000

The input consists of alphabetical characters and digits

Sample Input 1

4 5
00010
00101
00010
00100
3 2
10
01
10

Sample Output 1

0 3
1 2


object Main {
  def main(args: Array[String]): Unit = {
    val input = new java.util.Scanner(System.in)
    val n = input.nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = input.nextInt
    }

    for(i <- 1 until n) {
      val v = a(i)
      var j = i - 1
      while(j >= 0 && a(j) > v){
        a(j+1) = a(j)
        j = j - 1
      }
      a(j+1) = v
      println(a.mkString(" "))
    }

    println(a.mkString(" "))

  }
}

Insertion Sort

Write a program of the Insertion Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

for i = 1 to A.length-1
key = A[i]
/* insert A[i] into the sorted sequence A[0,...,j-1] */
j = i - 1
while j >= 0 and A[j] > key
A[j+1] = A[j]
j--
A[j+1] = key

Note that, indices for array elements are based on 0-origin.

To illustrate the algorithms, your program should trace intermediate result for each step.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by a single space.

Output

The output consists of N lines. Please output the intermediate sequence in a line for each step. Elements of the sequence should be separated by single space.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 2 4 6 1 3

Sample Output 1

5 2 4 6 1 3
2 5 4 6 1 3
2 4 5 6 1 3
2 4 5 6 1 3
1 2 4 5 6 3
1 2 3 4 5 6

Sample Input 2

3
1 2 3

Sample Output 2

1 2 3
1 2 3
1 2 3

Hint

Template in C


import scala.io.StdIn

object Main {
  def main(args: Array[String]){
    val input = StdIn.readLine().split(" ").map(_.toInt)
    println(gcd(input(0),input(1)))
  }

  def gcd(x: Int, y: Int):Int = {
    return if(1 < y && y < x) { gcd(y, x % y) } else { x }
  }
}

Greatest Common Divisor

Write a program which finds the greatest common divisor of two natural numbers a and b

Input

a and b are given in a line sparated by a single space.

Output

Output the greatest common divisor of a and b.

Constrants

1 ≤ a, b ≤ 109

Hint

You can use the following observation:

For integers x and y, if x ≥ y, then gcd(x, y) = gcd(y, x%y)

Sample Input 1

54 20

Sample Output 1

2

Sample Input 2

147 105

Sample Output 2

21


import scala.io.StdIn

object Main extends App {

  val n = StdIn.readLine().trim.toInt

  def isPrime(x: Int): Boolean = {
    if (x == 2) {
      true
    }
    else if (x < 2 || x % 2 == 0) {
      false
    } else {
      !(3 to scala.math.sqrt(x).toInt by 2).exists(i => x % i == 0)
    }
  }

  println((0 until n).foldLeft(0){ (acc, _) =>
    val x = StdIn.readLine().trim.toInt
    acc + (if(isPrime(x)) 1 else 0)
  })

}

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4


import scala.io.Source

object Main{
  def main(args: Array[String]){
    val lines = for{
      in <- Source.stdin.getLines.toList
    }yield in.toInt

    println(rec(lines.tail).max)
  }

  def rec(list: List[Int]): List[Int] =
    if(list.length == 1) Nil
    else list.last - list.init.min :: rec(list.init)
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


import scala.io.Source
import scala.annotation.tailrec

object Main{
  def main(args: Array[String]){
    val lines = for{
      in <- Source.stdin.getLines.toList
    }yield in.toInt

    println(rec(lines.tail, Int.MinValue))
  }

  @tailrec
  def rec(list: List[Int], max: Int): Int ={
    if(list.length == 1) max
    else rec(list.init, Math.max(list.last - list.init.min, max))
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val inputString = io.StdIn.readLine()
    val intArray = inputString.split("\n").map(_.toInt)
    val sz = intArray(0)
    var ret = Int.MinValue
/*
    for(i <- 1 to sz) {
      for(j <- i+1 to sz) {
        val temp = intArray(j) - intArray(i)
        if(temp>ret) ret = temp
      }
    }
*/
    println(ret)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val inputString = io.StdIn.readLine()
    val intArray = inputString.split("\n").map(_.toInt)
    val sz = intArray(0)
    var ret = Int.MinValue
    for(i <- 1 to sz) {
      for(j <- i+1 to sz) {
/*
        val temp = intArray(j) - intArray(i)
        if(temp>ret) ret = temp
*/
      }
    }
    println(ret)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val sz = sc.nextInt
    val list = List.fill(sz)(sc.nextInt)

    val max = list.max
    val maxi = list.indexOf(max)
    val min = list.min
    val mini = list.indexOf(min)
    if(mini <= maxi) {
        println(max-min)
        return
    }

    var ret = Int.MinValue
    for (i <- 0 until list.length-1) {
        var maxv = Int.MinValue
        (i+1 to list.length-1).foreach( index => if(list(index)>maxv)maxv=list(index))
        val t = maxv - list(i)
        if(t>ret) ret = t
    }

    println(ret)
  }
}


import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    val n = readLine.toInt
    val input = (1 to n map { _ => readLine.toInt }).toList
    // println(input)
    println(calMaxProf(input))
  }

  @tailrec def calMaxProf(input: List[Int], maxProf: Int = Int.MinValue): Int = input match {
    case head :: Nil =>
      maxProf
    case head :: tail =>
      val prof = tail.map(_ - head).max
      if (prof > maxProf) {
        calMaxProf(tail, prof)
      } else {
        calMaxProf(tail, maxProf)
      }
    case Nil =>
      maxProf
  }
}


import scala.annotation.tailrec

object Main {
  def main(args: Array[String]): Unit = {
    val n = readLine.toInt
    val _input = new Array[Int](n)
    1 to n foreach { i =>
      _input(i-1) = readLine.toInt
    }
    val input = _input.toList
    println(input)

    println(calMaxProf(input))
  }

  @tailrec def calMaxProf(input: List[Int], maxProf: Int = Int.MinValue): Int = input match {
    case head :: Nil =>
      maxProf
    case head :: tail =>
      val prof = tail.map(_ - head).max
      if (prof > maxProf) {
        calMaxProf(tail, prof)
      } else {
        calMaxProf(tail, maxProf)
      }
    case Nil =>
      maxProf
  }
}


import scala.io.Source

object Main {
  def calcMaxProfit(numbers: Seq[Int]): Int = {
    if (numbers.size == 2) {
      numbers(1) - numbers(0)
    } else {
      val maxProfit: Int = (1 to numbers.size-2)
        .map{i =>
          val as = numbers.take(i)
          val bs = numbers.drop(i)
          bs.max - as.last
        }
        .max
      maxProfit
    }
  }

  def main(args: Array[String]): Unit = {
    // Get interator of stdin
    val stdinIterator = Source.stdin.getLines()

    // Skip the first line
    stdinIterator.next()

    // Get input
    val numbers: Seq[Int] = stdinIterator.toSeq.map(_.toInt)

    // Calc max profit
    val maxProfit = calcMaxProfit(numbers)

    // Print max profit
    println(maxProfit)
  }
}


import java.util.Scanner

object Main extends App {

  def read(): Array[Int] = {
    val sc: Scanner = new Scanner(System.in)
    val n = sc.nextInt
    val arr = Array.fill(n)(sc.nextInt)
    sc.close()
    arr
  }

  def solve()  = {
    val arr = read()
    var max = Long.MinValue
    var min = arr.head
    for(i <- 1 until arr.length) {
      max = Math.max(max, arr(i)-min)
      min = Math.min(min, arr(i))
    }
    max
  }
  println(solve)

}


object Main {
  def SelectionSort(A: Array[Int]):(Int,Array[Int]) = {
    var count = 0
    def swap(i: Int, j: Int){
      if(i != j){
        count += 1
      }
      val tmp = A(i)
      A(i) = A(j)
      A(j) = tmp
    }

    for(i <- 0 to A.length - 1){
      var mini = i
      for(j <- i + 1 to A.length - 1){
        if (A(j) < A(mini)){
          mini = j
        }
      }
      swap(i,mini)
    }
    (count,A)
  }

  def main(args: Array[String]){
    val N = readLine().map(_.toInt)
    val input = readLine().split(" ").map(_.toInt).toArray
    val result = SelectionSort(input)
    println(result._2.mkString(" "))
    println(result._1)
  }
}

Selection Sort

Write a program of the Selection Sort algorithm which sorts a sequence A in ascending order. The algorithm should be based on the following pseudocode:

SelectionSort(A)
1 for i = 0 to A.length-1
2 mini = i
3 for j = i to A.length-1
4 if A[j] < A[mini]
5 mini = j
6 swap A[i] and A[mini]

Note that, indices for array elements are based on 0-origin.

Your program should also print the number of swap operations defined in line 6 of the pseudocode in the case where i ≠ mini.

Input

The first line of the input includes an integer N, the number of elements in the sequence.

In the second line, N elements of the sequence are given separated by space characters.

Output

The output consists of 2 lines.

In the first line, please print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

In the second line, please print the number of swap operations.

Constraints

1 ≤ N ≤ 100

Sample Input 1

6
5 6 4 2 1 3

Sample Output 1

1 2 3 4 5 6
4

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
3


import scala.io.StdIn
import scala.annotation.tailrec

object Main{
  def main(args: Array[String]){
    StdIn.readLine()
    val line = StdIn.readLine().split(" ").toList.map(_.toInt)

    println(line.sorted.mkString(" "))
    println(sSort(List(), line, 0))
  }

  @tailrec
  def sSort(sorted: List[Int], unsorted: List[Int], n: Int): Int={
    if(unsorted.length == 0) n
    else if(unsorted.sorted == unsorted) n
    else sSort(sorted :+ unsorted.min, deleteOneList(unsorted, unsorted.min), n+1)
  }

  def deleteOneList(list: List[Int], target: Int): List[Int] =
    list.filter(_ != target) ::: List.fill(list.filter(_ == target).length - 1)(target)
}


import scala.io.StdIn
import scala.annotation.tailrec

object Main{
  def main(args: Array[String]){
    StdIn.readLine()
    val line = StdIn.readLine().split(" ").toList.map(_.toInt)

    sSort(List(), line, 0)
  }

  @tailrec
  def sSort(sorted: List[Int], unsorted: List[Int], n: Int){
    if((sorted ::: unsorted).length == 1)
      println(unsorted.mkString(" ") + "\n" + (n+1))
    else if(unsorted.length == 1)
      println((sorted ::: unsorted).mkString(" ") + "\n" + n)
    else if(unsorted.sorted == unsorted)
      println((sorted ::: unsorted).mkString(" ") + "\n" + n)
    else if(unsorted.indexWhere(_ == unsorted.min) == 0)
      sSort(sorted :+ unsorted.head, unsorted.tail, n)
    else {
      val pos = unsorted.indexWhere(_ == unsorted.min)
      // pos??¨head???????´????swap?????????
      val swapped = unsorted.updated(0, unsorted(pos)).updated(pos, unsorted.head)

      sSort(sorted :+ unsorted.min, swapped.tail, n+1)
    }
  }
}


import scala.io.StdIn
import scala.annotation.tailrec

object Main{
  def main(args: Array[String]){
    StdIn.readLine()
    val line = StdIn.readLine().split(" ").toList.map(_.toInt)

    sSort(List(), line, 0)
  }

  @tailrec
  def sSort(sorted: List[Int], unsorted: List[Int], n: Int){
    if((sorted ::: unsorted).length == 1)
      println(unsorted.mkString(" ") + "\n" + n)
    else if(unsorted.sorted == unsorted)
      println((sorted ::: unsorted).mkString(" ") + "\n" + n)
    else if(unsorted.indexWhere(_ == unsorted.min) == 0)
      sSort(sorted :+ unsorted.head, unsorted.tail, n)
    else {
      val pos = unsorted.indexWhere(_ == unsorted.min)
      // pos??¨head???????´????swap?????????
      val swapped = unsorted.updated(0, unsorted(pos)).updated(pos, unsorted.head)

      sSort(sorted :+ unsorted.min, swapped.tail, n+1)
    }
  }
}


import scala.io.StdIn
import scala.annotation.tailrec
import scala.collection.immutable.{Queue => EmQueue}

case class Process(name: String, time: Int){
  override def toString(): String = s"$name $time"
}

object Main extends App {
  val Array(_, quantum) = StdIn.readLine().split(" ").map(_.toInt)

  val queue = Iterator.continually(StdIn.readLine()).takeWhile(_ != null).foldLeft(Queue.empty) {
    (queue, line) => {
      line.split(" ") match {
        case Array(name: String,time: String) => queue.enqueue(Process(name, time.toInt))
      }
    }
  }

  @tailrec
  def loop(queue: Queue, out: EmQueue[Process] = EmQueue(), curTime: Int = 0): EmQueue[Process] = {
    if(queue.isEmpty) out
    else {
      val(process, nextQueue) = queue.dequeue
      if(process.time > quantum){
        loop(nextQueue.enqueue(process.copy(time = process.time - quantum)), out, curTime + quantum)
      }else{
        loop(
          nextQueue,
          out :+ process.copy(time = curTime + process.time),
          curTime + process.time
        )
      }
    }
  }

  println(loop(queue).mkString("\n"))
}

class Queue private(val in: List[Process], val out: List[Process]){
  def enqueue(elem: Process) = new Queue(elem :: in, out)

  def dequeue: (Process, Queue) = out match {
    case Nil if !in.isEmpty => val rev = in.reverse ; (rev.head, new Queue(Nil, rev.tail))
    case x :: xs            => (x, new Queue(in, xs))
    case _                  => throw new NoSuchElementException("dequeue on empty queue")
  }

  def isEmpty: Boolean = in.isEmpty && out.isEmpty

  override def toString() = in.toString
}

object Queue {
  def empty: Queue = new Queue(Nil, Nil)
  def apply(xs: Process*): Queue = new Queue(Nil, xs.toList)
}

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C


import scala.io.StdIn.readLine
case class Queue[T](in: List[T], out: List[T]) {
    def isEmpty(): Boolean = if (in.isEmpty && out.isEmpty) true else false
    def head(): T = out match {
        case x :: xs => x
        case _ => throw new RuntimeException("error...")
    }
    def enque(e: T): Queue[T] = {
        val newIn = e :: in
        new Queue[T](newIn, newIn.reverse)
    }
    def deque(): Queue[T] = out match {
        case x :: xs => new Queue[T](xs.reverse, xs)
        case _ => throw new RuntimeException("error...")
    }
}
object Queue {
    def apply[T](): Queue[T] = new Queue[T](Nil, Nil)
}
case class Proc(name: String, time: Int) {
    def exec(t: Int): (Proc, Int) = {
        if (time - t < 0) (new Proc(name, 0), time)
        else (new Proc(name, time - t), t)
    }
    def finished(): Boolean = if (time == 0) true else false
}
object Main {
    def main(args: Array[String]): Unit = {
        val line = readLine.split(" ").map(_.toInt)
        val procNum = line(0)
        val quantum = line(1)
        val que: Queue[Proc] = (1 to procNum).foldLeft(Queue[Proc]()) { (que, a) =>
            val p = readLine.split(" ")
            que.enque(new Proc(p(0), p(1).toInt))
        }
        println(process(que, quantum).mkString("\n"))
    }

    def process(que: Queue[Proc], quantum: Int): List[String] = {
        def go(que: Queue[Proc], total: Int, result: List[String]): List[String] = que match {
            case que if que.isEmpty => result
            case que => que.head.exec(quantum) match {
                case (pProc, time) if pProc.finished => go(que.deque, total + time, s"${pProc.name} ${total + time}" :: result)
                case (pProc, time) => go(que.deque.enque(pProc), total + time, result)
            }
        }
        go(que, 0, Nil).reverse
    }
}


import scala.io.StdIn._
import scala.annotation.tailrec

object Main {

  //f(x) => (-1,0,1)
  @tailrec
  def binarySearch(f: Int => Int,l: Int, r: Int): Int = {
    if(r-l<=1)f(l)
    else if(f((l+r)/2) < 1)binarySearch(f,(l+r)/2,r)
    else binarySearch(f,l,(l+r)/2)
  }

  def main(args: Array[String]): Unit = {
    val n = readInt
    val list = readLine.split(" ").map(_.toInt).toList

    val f = (ar: List[Int]) => (a: Int) => (x: Int) => ar(x)-a

    val q = readInt
    val qlist = readLine.split(" ").map(_.toInt)

    val res = for(e <- qlist)yield(0 == binarySearch(f(list)(e),0,n))
    println(res.toList.map(if(_) 1 else 0).sum)
  }
}

Search II

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


import scala.io.StdIn._
import scala.annotation.tailrec

object Main {

  val f = (ar: List[Int]) => (a: Int) => (x: Int) => ar(x)-a

  //f(x) => (-1,0,1)
  @tailrec
  def binarySearch(f: Int => Int,l: Int, r: Int): Int = {
    if(r-l<=1)f(l)
    else if(f((l+r)/2) < 1)binarySearch(f,(l+r)/2,r)
    else binarySearch(f,l,(l+r)/2)
  }

  def loop(n: Int,in: Int, q: Int, cnt:Int,f: Int => Int => Int):Int = {
    if(q==0)cnt
    else loop(n,readInt,q-1,cnt+(if(0==binarySearch(f(in),0,n)) 1 else 0),f )
  }

  def main(args: Array[String]): Unit = {
    val n = readInt
    val list = readLine.split(" ").map(_.toInt).toList

    val q = readInt
    val qlist = readLine.split(" ").map(_.toInt)
    var res:Int = 0
    for(e <- qlist)res=res+(if(0 == binarySearch(f(list)(e),0,n)) 1 else 0)
    println(res)
    //val res = for(e <- qlist)yield(0 == binarySearch(f(list)(e),0,n))
    //println(res.toList.map(if(_) 1 else 0).sum)
    //println(loop(n,readInt,q,0,f(list)))
  }
}


import scala.io.StdIn.readLine

object Main {
  def search(a:Array[Int],len:Int,value:Int) = {
    def scan(l:Int,r:Int):Boolean = {
      val mid = (l+r)/2
      if(a(mid) == value) true
      else if(l>=r) false
      else if(a(mid)<value) scan(mid+1,r)
      else scan(l,mid-1)
    }
    scan(0,len)
  }

  def main(args:Array[String]) = {
    readLine
    val s = readLine.split(" ").map(_.toInt)
    readLine
    val t = readLine.split(" ").map(_.toInt)
    val len = s.length-1
    println(t.count(i=> search(s,len,i) ))
  }
}


import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine.toInt
    val S = StdIn.readLine.split(' ').map(_.toInt)
    val q = StdIn.readLine.toInt
    val T = StdIn.readLine.split(' ').map(_.toInt)
    val C = new Array[Int](100000)
    var len = 0

    val res = T filter { m => binSearch(S, n, m) }
    println(res.mkString(" "))
  }

  def binSearch(S: Array[Int], len: Int, i: Int): Boolean = {
    var l = 0
    var r = len
    while (l < r) {
      val indice = (r + l) / 2
      if (S(indice) < i) {
        r = indice
      } else if (S(indice) > i) {
        l = indice + 1
      } else {
        return true
      }
    }
    false
  }
}


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val a = List.fill(n)(sc.nextInt)
  val q = sc.nextInt
  val m = List.fill(q)(sc.nextInt)

  def solve(i: Int, m: Int): Boolean = if(m == 0) true
    else if(i >= n) false
    else solve(i+1, m) || solve(i+1, m - a(i))

  val result = m.map(p => if(solve(0, p)) "yes" else "no")

  print(result.mkString(f"%n"))

}

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


object Main extends App {

  val sc = new java.util.Scanner(System.in)
  val n = sc.nextInt
  val a = List.fill(n)(sc.nextInt)
  val q = sc.nextInt
  val m = List.fill(q)(sc.nextInt)

  def solve(i: Int, m: Int): Boolean = if(m == 0) true
    else if(i >= n) false
    else solve(i+1, m) || solve(i+1, m - a(i))

  val result = m.map(p => if(solve(0, p)) "yes" else "no")

  print(result.mkString(f"%n") + f"%n")

}


import scala.io.StdIn.{readLine,readInt}
import scala.language.postfixOps

object Main {
  var cnt = 0
  val l = new Array[Int](250001)
  val r = new Array[Int](250001)

  def merge(a:Array[Int],left:Int,mid:Int,right:Int) = {
    val n1 = mid-left
    val n2 = right-mid
    Array.copy(a,left,l,0,n1)
    l(n1) = Int.MaxValue
    Array.copy(a,mid,r,0,n2)
    r(n2) = Int.MaxValue
    var i=0
    var j=0
    for(k<-left until right) {
      if(l(i)<=r(j)){
        a(k) = l(i)
        i += 1
      } else  {
        a(k)=r(j)
        j += 1
      }
      cnt += 1
    }
  }

  def getSortIndex(n:Int):Iterator[IndexedSeq[(Int,Int)]] = {
    var w = n
    var h = 0
    while(w>1) {
      h += 1
      w /= 2
    }

    def scan(h:Int,l:List[IndexedSeq[(Int,Int)]]):List[IndexedSeq[(Int,Int)]] = {
      if(h==0) l
      else
        scan(h-1,(for(i<-l.head;j<-List((i._1,(i._2+i._1)/2),((i._2+i._1)/2,i._2))) yield j)::l)
    }
    scan(h-1,List(IndexedSeq((0,n/2),(n/2,n)))).to[Iterator]
  }

  def main(args:Array[String]) = {
    val n = readInt
    val l = getSortIndex(n)
    val a = readLine.split(" ").map(_.toInt)

    for(e2<-l) {
      for(e<-e2) {
        val mid = (e._2+e._1)/2
        if(e._2-e._1>1)
          merge(a,e._1,mid,e._2)
      }
    }
    merge(a,0,n/2,n)
    println(a.mkString(" "))
    println(cnt)
  }
}

Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


import scala.io.StdIn.{readLine,readInt}
import scala.language.postfixOps

object Main {
  var cnt = 0
  val l = new Array[Int](250001)
  val r = new Array[Int](250001)
  var a:Array[Int] = null

  def merge(left:Int,mid:Int,right:Int) = {
    val n1 = mid-left
    val n2 = right-mid
    Array.copy(a,left,l,0,n1)
    l(n1) = Int.MaxValue
    Array.copy(a,mid,r,0,n2)
    r(n2) = Int.MaxValue
    var i=0
    var j=0
    for(k<-left until right) {
      if(l(i)<=r(j)){
        a(k) = l(i)
        i += 1
      } else  {
        a(k)=r(j)
        j += 1
      }
      cnt += 1
    }
  }

  def getSortIndex(n:Int):Iterator[IndexedSeq[(Int,Int)]] = {
    var w = n
    var h = 0
    while(w>1) {
      h += 1
      w /= 2
    }

    def scan(h:Int,l:List[IndexedSeq[(Int,Int)]]):List[IndexedSeq[(Int,Int)]] = {
      if(h==0) l
      else
        scan(h-1,(for(i<-l.head;j<-List((i._1,(i._2+i._1)/2),((i._2+i._1)/2,i._2))) yield j)::l)
    }
    scan(h-1,List(IndexedSeq((0,n/2),(n/2,n)))).to[Iterator]
  }

  def main(args:Array[String]) = {
    val n = readInt
    a = readLine.split(" ").map(_.toInt)
    val l = getSortIndex(n)
    for(e2<-l) {
      for(e<-e2) {
        val mid = (e._2+e._1)/2
        if(e._2-e._1>1)
          merge(e._1,mid,e._2)
      }
    }
    merge(0,n/2,n)
    println(a.mkString(" "))
    println(cnt)
  }
}


import scala.math.BigDecimal
import scala.math.BigDecimal.RoundingMode
import scala.io.StdIn.readInt
object Main {
    def main(args: Array[String]): Unit = {
        koch(new Point(0.0, 0.0), 0, 100, readInt)
    }
    def koch(point: Point, angle: Int, len: Double, count: Int): Point = {
        if (count == 0) {
            val p = point.add(len * cos(angle), len * sin(angle))
            println(p)
            p
        } else {
            val nextLen = len / 3.0
            List(0, 60, 300, 360).foldLeft(point) { (p, a) =>
                koch(p, angle + a, nextLen, count - 1)
            }
        }
    }
    def cos(angle: Int) = Math.cos(Math.toRadians(angle % 360))
    def sin(angle: Int) = Math.sin(Math.toRadians(angle % 360))
}
case class Point(x: Double, y: Double) {
    override def toString(): String = {
        val a = "%.8f".format(BigDecimal(x).setScale(8, RoundingMode.HALF_UP))
        val b = "%.8f".format(BigDecimal(y).setScale(8, RoundingMode.HALF_UP))
        a + " " + b
    }
    def add(xx: Double, yy: Double): Point = new Point(x + xx, y + yy)
}

Koch Curve

Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n.

The Koch curve is well known as a kind of fractals.

You can draw a Koch curve in the following algorithm:

Divide a given segment (p1, p2) into three equal segments.

Replace the middle segment by the two sides of an equilateral triangle (s, u, t) of the same length as the segment.

Repeat this procedure recursively for new segments (p1, s), (s, u), (u, t), (t, p2).

You should start (0, 0), (100, 0) as the first segment.

Input

An integer n is given.

Output

Print each point (x, y) of the Koch curve. Print a point in a line. You should start the point(0, 0), which is the endpoint of the first segment and end with the point (100, 0), the other endpoint so that you can draw the Koch curve as an unbroken line. Each solution should be given as a decimal with an arbitrary number of fractional digits, and with an absolute error of at most 10-4.

Constraints

0 ≤ n ≤ 6

Sample Input 1

1

Sample Output 1

0.00000000 0.00000000
33.33333333 0.00000000
50.00000000 28.86751346
66.66666667 0.00000000
100.00000000 0.00000000

Sample Input 2

2

Sample Output 2

0.00000000 0.00000000
11.11111111 0.00000000
16.66666667 9.62250449
22.22222222 0.00000000
33.33333333 0.00000000
38.88888889 9.62250449
33.33333333 19.24500897
44.44444444 19.24500897
50.00000000 28.86751346
55.55555556 19.24500897
66.66666667 19.24500897
61.11111111 9.62250449
66.66666667 0.00000000
77.77777778 0.00000000
83.33333333 9.62250449
88.88888889 0.00000000
100.00000000 0.00000000

Notes


import scala.io.StdIn
import scala.collection.mutable.ArrayBuffer

/*
 ret
 http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=2232735#1
 */
object Main {
  class Point(val x: Double, val y: Double){
    override def toString: String = {
      f"$x%.8f $y%.8f"
    }
  }

  final val start = new Point(0, 0)
  final val end   = new Point(100, 0)
  final val th = scala.math.Pi * 60.0 / 180.0
  final val cos = math.cos(th)
  final val sin = math.sin(th)

  @inline def calcuPoint(p1: Point, p2: Point, a: Double, b: Double) = new Point((a*p1.x+b*p2.x)/3.0, (a*p1.y+b*p2.y)/3.0)

  def koch(d: Double, p1: Point, p2: Point, ret: ArrayBuffer[Point]): Unit = {
    if(d != 0){
      val s = calcuPoint(p1, p2, 2.0, 1.0)
      val t = calcuPoint(p1, p2, 1.0, 2.0)
      val tsx = t.x - s.x
      val tsy = t.y - s.y
      val u = new Point(tsx*cos - tsy*sin + s.x,
                        tsx*sin + tsy*cos + s.y)

      koch(d-1, p1, s, ret)
      // println(s)
      ret += s

      koch(d-1, s, u, ret)
      //println(u)
      ret += u

      koch(d-1, u, t, ret)
      // println(t)
      ret += t

      koch(d-1, t, p2, ret)

    }
  }

  def main(args:Array[String]) = {
    var result = ArrayBuffer.empty[Point]
    val n = StdIn.readLine().trim.toInt

    //println(start)
    result += start
    koch(n, start, end, result)
    result += end

    //result.foreach(println)
    println(result.mkString(f"%n"))

  }

}


import scala.io.StdIn.{readLine,readInt}
import scala.language.postfixOps

object Main {
  var cnt = 0
  val l = new Array[Int](100002)
  val r = new Array[Int](100002)

  def merge(a:Array[Int],left:Int,mid:Int,right:Int) = {
    val n1 = mid-left
    val n2 = right-mid
    Array.copy(a,left,l,0,n1)
    l(n1) = Int.MaxValue
    Array.copy(a,mid,r,0,n2)
    r(n2) = Int.MaxValue
    var i=0
    var j=0
    for(k<-left until right) {
      if(l(i)<=r(j)){
        a(k) = l(i)
        i += 1
      } else  {
        a(k)=r(j)
        cnt = cnt+n1-i
        j += 1
      }
    }
  }

  def scan(h:Int,l:List[IndexedSeq[(Int,Int)]]):List[IndexedSeq[(Int,Int)]] =
    if(h==0) l
    else scan(h-1,(for(i<-l.head;j<-List((i._1,(i._2+i._1)/2),((i._2+i._1)/2,i._2))) yield j)::l)

  def getSortIndex(n:Int):Iterator[IndexedSeq[(Int,Int)]] = {
    var w = n
    var h = 0
    while(w>1) {
      h += 1; w /= 2
    }
    scan(h-1,List(IndexedSeq((0,n/2),(n/2,n)))).to[Iterator]
  }

  def main(args:Array[String]) = {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val l = getSortIndex(n)
    for(e2<-l) {
      for(e<-e2) {
        val mid = (e._2+e._1)/2
        if(e._2-e._1>1)
          merge(a,e._1,mid,e._2)
      }
    }
    merge(a,0,n/2,n)
    println(cnt)
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

The Number of Inversions

For a given sequence $A = \{a_0, a_1, ... a_{n-1}\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program:

bubbleSort(A)
cnt = 0 // the number of inversions
for i = 0 to A.length-1
for j = A.length-1 downto i+1
if A[j] < A[j-1]
swap(A[j], A[j-1])
cnt++

return cnt

For the given sequence $A$, print the number of inversions of $A$. Note that you should not use the above program, which brings Time Limit Exceeded.

Input

In the first line, an integer $n$, the number of elements in $A$, is given. In the second line, the elements $a_i$ ($i = 0, 1, .. n-1$) are given separated by space characters.

output

Print the number of inversions in a line.

Constraints

$ 1 \leq n \leq 200,000$

$ 0 \leq a_i \leq 10^9$

$a_i$ are all different

Sample Input 1

5
3 5 2 1 4

Sample Output 1

6

Sample Input 2

3
3 1 2

Sample Output 2

2


import scala.io.StdIn.readLine

object Main {
  def sort(a:Array[Int],k:Int) = {
    val count = new Array[Int](k+1)
    val buf = new Array[Int](a.length)
    a.map( x=> count(x) += 1 )
    for(i<-1 to k) count(i) += count(i-1)
    for(i<-0 until a.length) {
      val j = a.length-1-i
      buf(count(a(j))-1) = a(j)
      count(a(j)) = count(a(j))-1
    }
    buf
  }

  def main(args:Array[String]) = {
    readLine
    val a = readLine.split(" ").map(_.toInt)
    val result = sort(a,10000)
    println(result.mkString(" "))
  }
}

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input

The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


import scala.io.StdIn.{readInt, readLine};
import scala.reflect.ClassTag;

object Main {

    def main(args: Array[String]): Unit = {
        implicit val ord = Ordering.by((e: (String, Long)) => e._2);
        val n = readInt;
        val arr1 = new Array[(String, Long)](n);
        val arr2 = new Array[(String, Long)](n);
        (0 until n).foreach { i =>
            val input = readLine.split(" ");
            val elem = (input(0), input(1).toLong);
            arr1(i) = elem;
            arr2(i) = elem;
        }

        quickSort[(String, Long)](arr1, n);
        mergeSort[(String, Long)](arr2, n);

        if ((0 until n).exists( i => arr1(i) != arr2(i))) println("Not stable") else println("Stable");
        println(arr1.map(e => e._1 + " " + e._2).mkString("\n"));
    }

    def quickSort[A](arr: Array[A], n: Int)(implicit ord: Ordering[A]): Unit = {
        def _quickSort(first: Int, last: Int): Unit = {
            if (first < last){
                val pivot = partition(arr, first, last);
                _quickSort(first, pivot - 1);
                _quickSort(pivot + 1, last);
            }
        }
        _quickSort(0, n - 1);
    }

    def partition[A](arr: Array[A], first: Int, last: Int)(implicit ord: Ordering[A]): Int = {
        import ord._;
        val pivot = arr(last);
        def _partition(ptr: Int, laterPtr: Int): Int = {
            if (ptr > last) {
                laterPtr;
            } else {
                if (arr(ptr) > pivot) {
                    _partition(ptr + 1,  laterPtr);
                } else {
                    swap(arr, ptr, laterPtr + 1);
                    _partition(ptr + 1, laterPtr + 1);
                }
            }
        }
        _partition(0, -1);
    }

    private def swap[A](arr: Array[A], a: Int, b: Int): Unit = {
        val tmp = arr(a);
        arr(a) = arr(b);
        arr(b) = tmp;
    }

    def mergeSort[A](arr: Array[A], n: Int)(implicit ord: Ordering[A], m: ClassTag[A]): Int = {
        import ord._;
        def _mergeSort(first: Int, last: Int): Int = {
            if (last - first > 0) {
                val pivot = (first + last) / 2;
                val cnt1 = _mergeSort(first, pivot);
                val cnt2 = _mergeSort(pivot + 1, last);
                merge(arr, first, last, pivot);
                cnt1 + cnt2 + (last - first + 1);
            } else {
                0;
            }
        }
        _mergeSort(0, n - 1);
    }

    def merge[A](arr: Array[A], first: Int, last: Int, pivot: Int)(implicit ord: Ordering[A], m: ClassTag[A]): Unit = {
        import ord._;
        val tmpArr = (first to pivot).map(arr(_)).toArray;
        var ptr1 = 0;
        var ptr2 = pivot + 1;
        for (i <- (first to last)) {
            if (ptr1 >= tmpArr.length) {
                arr(i) = arr(ptr2);
                ptr2 += 1;
            } else if (ptr2 > last) {
                arr(i) = tmpArr(ptr1);
                ptr1 += 1;
            } else {
                if (arr(ptr2) < tmpArr(ptr1)) {
                    arr(i) = arr(ptr2);
                    ptr2 += 1;
                } else {
                    arr(i) = tmpArr(ptr1);
                    ptr1 += 1;
                }
            }
        }
    }
}

Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


import scala.io.StdIn.{readInt, readLine}
case class Node[T](value: T, parent: Node[T], var children: List[Node[T]], depth: Int) {
    override def toString(): String = {
        val p = if (parent == null) -1 else parent.value
        val t = if (parent == null) "root" else if (children == Nil) "leaf" else "internal node"
        val c = children.map(_.value).mkString(",")
        s"node ${value}: parent = ${p}, depth = ${depth}, ${t}, [${c}]"
    }
}
class IntTree() {
    var node: Node[Int] = null

    def add(target: Int, c: List[Int]): Unit = {
        if (node == null) {
            node = new Node[Int](target, null,  Nil, 0)
            node.children = c.map(new Node[Int](_, node, Nil, 1))
        } else search(target) match {
            case n => n.children = c.map(new Node[Int](_, n, Nil, n.depth + 1))
        }
    }

    def search(target: Int): Node[Int] = {
        def go(nodes: List[Node[Int]]): Node[Int] = nodes match {
            case Nil => null
            case x :: xs if x.value == target => x
            case x :: xs => go(x.children) match {
                case null => go(xs)
                case ret => ret
            }
        }
        if (node.value == target) node else go(node.children)
    }
}
object Main {
    def main(args: Array[String]): Unit = {
        val len = readInt
        val t = new IntTree()
        val l = (0 until len).foldLeft(Nil: List[Int]) { (list, i) =>
            val line = readLine.split(" ").map(_.toInt)
            val c = line.slice(2, line.length).toList
            val p = line.head
            t.add(p, c)
            if (i == 0) (p :: c) ::: list
            else c ::: list
        }
        println(l.sorted.map(t.search(_)).mkString("\n"))
    }
}

Rooted Trees

A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).

Fig. 1

A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."

Your task is to write a program which reports the following information for each node u of a given rooted tree T:

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.

A node with no children is an external node or leaf. A nonleaf node is an internal node

The number of children of a node x in a rooted tree T is called the degree of x.

The length of the path from the root r to a node x is the depth of x in T.

Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.

Fig. 2

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node u is given in the following format:

id k c1 c2 ... ck

where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.

Output

Print the information of each node in the following format ordered by IDs:

node id: parent = p, depth = d, type, [c1...ck]

p is ID of its parent. If the node does not have a parent, print -1.

d is depth of the node.

type is a type of nodes represented by a string (root, internal node or leaf). If the root can be considered as a leaf or an internal node, print root.

c1...ck is the list of children as a ordered tree.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0

Sample Output 1

node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Sample Input 2

4
1 3 3 2 0
0 0
3 0
2 0

Sample Output 2

node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []

Note

You can use a left-child, right-sibling representation to implement a tree which has the following data:

the parent of u

the leftmost child of u

the immediate right sibling of u

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import scala.collection.mutable
import scala.io.StdIn.{readInt, readLine}

case class Node(id: Int, parent: Int, depth: Int, children: List[Int])

object Main extends App {
  import Solver.solve

  val n     = readInt()
  val lines = Iterator.fill(n)(readLine())

  val xs = solve(lines, n)

  xs.foreach {
    case Node(id, parent, depth, children) =>
      val typeName =
        if (parent == -1) "root"
        else if (children.isEmpty) "leaf"
        else "internal node"

      val cs = children.mkString("[", ", ", "]")
      println(s"node $id: parent = $parent, depth = $depth, $typeName, $cs")
  }
}

object Solver {
  def solve(lines: Iterator[String], n: Int): Array[Node] = {

    val (childrenMap, rootId) = {
      val childrenMap = mutable.Map.empty[Int, List[Int]]
      val allChildren = mutable.Set(0 until n: _*)
      for {
        line               <- lines
        id :: _ :: children = line.split(' ').map { _.toInt }.toList
      } {
        childrenMap(id) = children
        allChildren --= children
      }

      val rootId = allChildren.head
      (childrenMap, rootId)
    }

    val xs = new Array[Node](n)
    def setDepth(id: Int, parent: Int, depth: Int): Unit = {
      val children = childrenMap(id)
      xs(id) = Node(id, parent, depth, children)

      val d = depth + 1
      for (childNodeId <- children) {
        setDepth(childNodeId, id, d)
      }
    }

    setDepth(rootId, -1, 0)

    xs
  }
}


import java.io._
import scala.io.StdIn.{readInt, readLine}

object Main {
  val out:BufferedWriter =
    new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512)
  var count = 0
  class Node(var key:Int, var left:Node = null, var right:Node = null) { }

  def insert(tree:Node, key:Node) = {
    val keyNode = key
    def getNodeToInsert(node:Node):Node =
      if(node.key > keyNode.key) {
        if(node.left == null) node
        else getNodeToInsert(node.left)
      } else {
        if(node.right == null) node
        else getNodeToInsert(node.right)
      }

    val target = getNodeToInsert(tree)

    if(keyNode.key < target.key) target.left = keyNode
    else target.right = keyNode
  }

  def inOrder(tree:Node):Unit =
    if(tree == null) return
    else {
      inOrder(tree.left)
      out.write(" ")
      out.write(tree.key.toString)
      if(count<100) count += 1
      else {
        out.flush
        count = 0
      }
      inOrder(tree.right)
    }

  def preOrder(tree:Node):Unit =
    if(tree == null) return
    else {
      out.write(" ")
      out.write(tree.key.toString)
      if(count<100) count += 1
      else {
        out.flush
        count = 0
      }
      preOrder(tree.left)
      preOrder(tree.right)
    }

  def main(args:Array[String]) = {
    val n = readInt
    val tree = new Node(-1)

    for(i<-0 until n) {
      val s = readLine.split(" ")
      s(0) match {
        case "insert" =>
          if(tree.key == -1) tree.key = s(1).toInt
          else insert(tree, new Node(s(1).toInt))
        case _ => {
          inOrder(tree)
          out.write("\n")
          out.flush()
          preOrder(tree)
          out.write("\n")
          out.flush()
        }
      }
    }
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


import scala.io.StdIn.{readLine,readInt}
import scala.collection.mutable.ArrayBuffer

object Main {
  var size = 0

  def swap(a:Array[Long],i:Int,j:Int) =  {
    val temp = a(i)
    a(i) = a(j)
    a(j) = temp
  }

  def maxHeapify(a:Array[Long], i:Int):Unit = {
    var largest = i
    if(i*2 <= size) {
      if(a(i*2-1) > a(i-1)) largest = i*2
      if(i*2+1<=size && a(i*2) > a(largest-1)) largest = i*2+1
      if(largest != i) {
        swap(a,i-1,largest-1)
        maxHeapify(a,largest)
      }
    }
  }

  def extract(a:Array[Long]):Long = {
    val max = a(0)
    if(size>0) {
      a(0) = a(size-1)
      size -= 1
      for(i<-size/2 to 1 by -1) {
        maxHeapify(a,i)
      }
    }
    max
  }

  def insert(a:Array[Long], n:Long) = {
    a(size) = n
    size += 1
    def upHeap(i:Int):Unit =
      if(i/2>0) {
        if(a(i/2-1) < a(i-1)) {
          swap(a,i/2-1,i-1)
          upHeap(i/2)
        }
      }
    upHeap(size)
  }

  def main(args:Array[String]) = {
    val a = new Array[Long](2100000)
    Iterator.continually(readLine).takeWhile(_.trim!="end").foreach { s=>
      val op = s.split(" ")
      if(op(0) == "insert") {
        insert(a, op(1).toLong)
      } else if(op(0) == "extract") {
        println(extract(a))
      }
    }
  }
}

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2


import scala.io.StdIn.{readLine,readInt}
import scala.collection.mutable.ArrayBuffer

object Main {
  var size = 0

  def swap(a:Array[Long],i:Int,j:Int) =  {
    val temp = a(i)
    a(i) = a(j)
    a(j) = temp
  }

  def maxHeapify(a:Array[Long], i:Int):Unit = {
    var largest = i
    if(i*2 <= size) {
      if(a(i*2-1) > a(i-1)) largest = i*2
      if(i*2+1<=size && a(i*2) > a(largest-1)) largest = i*2+1
      if(largest != i) {
        swap(a,i-1,largest-1)
        maxHeapify(a,largest)
      }
    }
  }

  def extract(a:Array[Long]):String = {
    val max = a(0)
    if(size>0) {
      a(0) = a(size-1)
      size -= 1
      for(i<-size/2 to 1 by -1) {
        maxHeapify(a,i)
      }
    }
    max.toString
  }

  def insert(a:Array[Long], n:Long) = {
    a(size) = n
    size += 1
    def upHeap(i:Int):Unit =
      if(i/2>0) {
        if(a(i/2-1) < a(i-1)) {
          swap(a,i/2-1,i-1)
          upHeap(i/2)
        }
      }
    upHeap(size)
  }

  def main(args:Array[String]) = {
    val a = new Array[Long](3100000)
    val b = new ArrayBuffer[String]
    Iterator.continually(readLine).takeWhile(s=>s!=null && s.trim!="end").foreach { s=>
      val op = s.split(" ")
      if(op(0) == "insert") {
        insert(a, op(1).toLong)
      } else if(op(0) == "extract") {
        b+=extract(a)
      }
    }
     println(b.mkString("\n"))
  }
}


import java.io._
import scala.io.Source

object Main {
  var size = 0
  var size2 = 0
  var count = 0
  val out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(FileDescriptor.out), "ASCII"), 512)

  def swap(a:Array[Int],i:Int,j:Int,ai:Int,aj:Int) =  {
    a(i) = aj
    a(j) = ai
  }

  def up(a:Array[Int], i:Int):Unit = {
    val j = i/2
    if(j>0 && a(j-1) < a(i-1)) { swap(a,j-1,i-1,a(j-1),a(i-1)); up(a,j) }
  }

  def down(a:Array[Int], i:Int, temp:Int):Unit = {
    var largest = i
    val j = (i+1)*2
    if(j>size) a(i) = temp
    else {
       val max = if(j==size) j-1 else if(a(j-1) >= a(j)) j-1 else j
       if(a(max)>temp) { a(i) = a(max); down(a,max,temp) }
       else a(i) = temp
    }
  }

  def extract(a:Array[Int]):Int = {
    val max = a(0)
    if(size>0) {
      a(0) = a(size-1)
      size -= 1
      down(a,0,a(0))
      a(size) = 0
    }
    max
  }

  def insert(a:Array[Int], n:Int) = {
    a(size) = n
    size += 1
    up(a,size)
  }

  def main(args:Array[String]) = {
    val a = new Array[Int](2000000)
    var s = ""
    Source.stdin.getLines.takeWhile(_!="end").foreach { s =>
      val op = s.split(" ")
      if(op(0) == "insert") {
        insert(a, op(1).toInt)
      } else if(op(0) == "extract") {
        val x = extract(a).toString
        out.write(x)
        out.write("\n")
        if(count<100) count += 1
        else {
         out.flush
         count = 0
        }
      }
    }
    out.flush
  }
}


import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Main {

  case class Point(x: Double = 0, y: Double = 0) {

    def +(p: Point): Point = Point(this.x + p.x, this.y + p.y)

    def -(p: Point): Point = Point(this.x - p.x, this.y - p.y)

    def *(a: Double): Point = Point(this.x * a, this.y * a)

    def /(a: Double): Point = {
      assert(a != 0)
      Point(this.x / a, this.y / a)
    }

    def norm(): Double = this.x * this.x + this.y * this.y

    def abs(): Double = scala.math.sqrt(norm())

    def <(p: Point): Boolean = this.x < p.x && this.y < p.y

    def ==(p: Point): Boolean = scala.math.abs(this.x - p.x) < Cgl0A.EPS &&
      scala.math.abs(this.y - p.y) < Cgl0A.EPS

  }

  case class Circle(center: Point, r: Int)

  case class Segment(p1: Point, p2: Point)

  case class Line(p1: Point, p2: Point)

  type GeoVector = Point

  object Cgl0A {
    val EPS: Double = scala.math.pow(10, -10)

    // 内積
    def dot(a: Point, b: Point): Double = a.x * b.x + a.y * b.y

    def isOrthogonal(a: GeoVector, b: GeoVector): Boolean = dot(a, b) == 0.0

    def isOrthogonal(a1: Point, a2: Point, b1: Point, b2: Point): Boolean = {
      isOrthogonal(a1 - a2, b1 - b2)
    }

    def isOrthogonal(s1: Segment, s2: Segment): Boolean = {
      dot(s1.p2 - s1.p1, s2.p2 - s2.p1) == 0.0
    }

    // 外積
    def cross(a: Point, b: Point): Double = a.x * b.y - a.y * b.x

    def isParallel(a: GeoVector, b: GeoVector): Boolean = cross(a, b) == 0.0

    def isParallel(a1: Point, a2: Point, b1: Point, b2: Point): Boolean = {
      isParallel(a1 - a2, b1 - b2)
    }

    def isParallel(s1: Segment, s2: Segment): Boolean = {
      cross(s1.p2 - s1.p1, s2.p2 - s2.p1) == 0.0
    }

    def project(s: Segment, p: Point): Point = {
      val base: GeoVector = s.p2 - s.p1
      val r: Double = Cgl0A.dot(p - s.p1, base) / base.norm()
      s.p1 + base * r
    }

    def reflect(s: Segment, p: Point): Point = {
      p + (project(s, p) - p) * 2.0
    }

    def getDistance(a: Point, b: Point): Double = (a - b).abs()

    def getDistanceLP(l: Line, a: Point): Double = {
      scala.math.abs(cross(l.p2 - l.p1, a - l.p1) / (l.p2 - l.p1).abs())
    }

    def getDistanceSP(s: Segment, a: Point): Double = {
      if (dot(s.p2 - s.p1, a - s.p1) < 0.0) (a - s.p1).abs()
      else if (dot(s.p1 - s.p2, a - s.p2) < 0.0) (a - s.p2).abs()
      else getDistanceLP(Line(s.p1, s.p2), a)
    }

    def getDistance(s1: Segment, s2: Segment): Double = {
      if (intersect(s1, s2)) {
        0.0
      }
      else {
        math.min(math.min(getDistanceSP(s1, s2.p1), getDistanceSP(s1, s2.p2)),
          math.min(getDistanceSP(s2, s1.p1), getDistanceSP(s2, s1.p2)))
      }
    }

    val COUNTER_CLOCKWISE: Int = 1
    val CLOCKWISE: Int = -1
    val ONLINE_BACK: Int = 2
    val ONLINE_FRONT: Int = -2
    val ON_SEGMENT: Int = 0

    def ccw(p0: Point, p1: Point, p2: Point): Int = {
      val a: GeoVector = p1 - p0
      val b: GeoVector = p2 - p0

      if (cross(a, b) > EPS) COUNTER_CLOCKWISE
      else if (cross(a, b) < -1 * EPS) CLOCKWISE
      else if (dot(a, b) < -1 * EPS) ONLINE_BACK
      else if (a.norm() < b.norm()) ONLINE_FRONT
      else ON_SEGMENT

    }

    def intersect(p1: Point, p2: Point, p3: Point, p4: Point): Boolean = {
      Cgl0A.ccw(p1, p2, p3) * Cgl0A.ccw(p1, p2, p4) <= 0 &&
        Cgl0A.ccw(p3, p4, p1) * Cgl0A.ccw(p3, p4, p2) <= 0
    }

    def intersect(s1: Segment, s2: Segment): Boolean = {
      Cgl0A.intersect(s1.p1, s1.p2, s2.p1, s2.p2)
    }

    def getCrossPoint(s1: Segment, s2: Segment): Point = {
      val base: GeoVector = s2.p2 - s2.p1
      val d1 = scala.math.abs(cross(base, s1.p1 - s2.p2))
      val d2 = scala.math.abs(cross(base, s1.p2 - s2.p1))
      val t = d1 / (d1 + d2)
      s1.p1 + (s1.p2 - s1.p1) * t
    }

    def getCrossPoint(c: Circle, l: Line): Array[Point] = {
      val pr: GeoVector = project(Segment(l.p1, l.p2), c.center)
      val e: GeoVector = (l.p2 - l.p1) / (l.p2 - l.p1).abs()
      val base: Double = scala.math.sqrt(c.r * c.r - (pr - c.center).norm())
      Array(pr + e * base, pr - e * base).sortBy(p => (p.x, p.y))
    }

    // arq tangent
    def arg(p: GeoVector): Double = scala.math.atan2(p.y, p.x)

    //
    def polar(a: Double, r: Double): GeoVector = {
      // x * 角度ラジアン
      Point(scala.math.cos(r) * a, scala.math.sin(r) * a)
    }

    def getCrossPoint(c1: Circle, c2: Circle): Array[Point] = {
      val d: Double = (c1.center - c2.center).abs()
      val cos: Double = (c1.r * c1.r + d * d - c2.r * c2.r) / (2 * c1.r * d)
      val a: Double = scala.math.acos(cos) // radian

      val t: Double = arg(c2.center - c1.center) // radian
      Array(c1.center + polar(c1.r, t + a),
        c1.center + polar(c1.r, t - a)).sortBy(p => (p.x, p.y))

    }

    val IN: Int = 2
    val ON: Int = 1
    val OUT: Int = 0

    def contains(g: IndexedSeq[Point], target: Point): Int = {
      val n = g.size
      var i = 0
      var onJudge = false
      var parity = false
      while (!onJudge && i < n) {
        var a: Point = g(i) - target
        var b: Point = g((i + 1) % n) - target
        if (cross(a, b).abs < EPS && dot(a, b) < EPS) {
          onJudge = true
        } else {
          if (a.y > b.y) {
            val temp = a
            a = b
            b = temp
          }
          parity = if (a.y < EPS && EPS < b.y && cross(a, b) > EPS) !parity else parity
        }
        i += 1
      }

      if (onJudge) {
        ON
      } else {
        if (parity) IN else OUT
      }
    }

    def andrewScan(s: Array[Point]): Array[Point] = {
      val u: ArrayBuffer[Point] = ArrayBuffer.empty[Point]
      val l: ArrayBuffer[Point] = ArrayBuffer.empty[Point]

      val sSize = s.length
      if (sSize < 3) {
        s
      } else {
        val temp = s.sortBy(p => (p.x, p.y))
        u.append(temp(0))
        u.append(temp(1))

        l.append(temp(sSize - 1))
        l.append(temp(sSize - 2))

        (2 until sSize).foreach { i =>
          var n = u.size
          while (n >= 2 && ccw(u(n - 2), u(n - 1), temp(i)) == COUNTER_CLOCKWISE) {
            u.remove(n - 1)
            n -= 1
          }
          u.append(temp(i))
        }

        (sSize - 3 to 0 by -1).foreach { i =>
          var n = l.size
          while (n >= 2 && ccw(l(n - 2), l(n - 1), temp(i)) == COUNTER_CLOCKWISE) {
            l.remove(n - 1)
            n -= 1
          }
          l.append(temp(i))
        }

        //println("U: " + u.toList)
        //println("L: " + l.toList)

        val r: ArrayBuffer[Point] = l.reverse
        u.reverse.slice(1, u.size - 1).foreach( e => r.append(e))

        r.toArray
      }

    }

  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().toInt
    val polygon = (0 until n).map { _ =>
      val point = StdIn.readLine().split(' ').map(_.toInt)
      Point(point(0), point(1))
    }.toArray

    val r = Cgl0A.andrewScan(polygon)
    r.foreach { e =>
      println(f"${e.x.toInt} ${e.y.toInt}")
    }

  }

}

Convex Hull

Find the convex hull of a given set of points P. In other words, find the smallest convex polygon containing all the points of P. Here, in a convex polygon, all interior angles are less than or equal to 180 degrees.

Please note that you should find all the points of P on both corner and boundary of the convex polygon.

Input

n
x1 y1
x2 y2
:
xn yn

The first integer n is the number of points in P. The coordinate of the i-th point pi is given by two integers xi and yi.

Output

In the first line, print the number of points on the corner/boundary of the convex polygon. In the following lines, print x y coordinates of the set of points.
The coordinates should be given in the order of counter-clockwise visit of them starting from the point in P with the minimum y-coordinate, or the leftmost such point in case of a tie.

Constraints

3 ≤ n ≤ 100000

-10000 ≤ xi, yi ≤ 10000

No point in the P will occur more than once.

Sample Input 1

7
2 1
0 0
1 2
2 2
4 2
1 3
3 3

Sample Output 1

5
0 0
2 1
4 2
3 3
1 3

Sample Input 2

4
0 0
2 2
0 2
0 1

Sample Output 2

4
0 0
2 2
0 2
0 1


import java.util.Scanner

object Main extends App {
  val sc = new Scanner(System.in)
  val N, W = sc.nextInt()
  val ls = (for (i <- 1 to N) yield (sc.nextInt, sc.nextInt, sc.nextInt)).toList

  type Item = (Int,Int) // (value, Weight)

  def mkItems(t:(Int,Int,Int)):List[Item] = {
    def iter(v:Int, w:Int, m:Int, s:Int, acc:List[Item]):(Int, List[Item]) = {
      if (m > 1) {
        iter(v << 1,w << 1,m >> 1, s << 1, (v, w)::acc)
      } else (s,acc)
    }
    val (v,w,m) = t
    val (s, items) = iter(v, w, m, 1, Nil)
    val k = m - (s -1)
    if (k > 0) (v*k,w*k)::items else items
  }

  class DP(num:Int, wgt:Int, items:Array[Item]) {
    val memo = Array.fill(wgt+1)(0)
    override def toString:String = (for (e <- memo) yield f" $e%3d").foldLeft("")(_+_)
    def solver():Int = {
      for (i <- 1 to num) {
        val (v, w) = items(i-1)
        for (j <- wgt to 0 by -1) {
          if (j >= w) {
            val v0 = memo(j)
            val v1 = memo(j-w) + v
            memo(j)= v0 max v1
          }
        }
      }
      memo(wgt)
    }
  }

  val items = (for (e <- ls) yield mkItems(e)).flatten.toArray

  val dp = new DP(items.length, W, items)
  println(dp.solver())

}

Knapsack Problem with Limitations

You have N items that you want to put them into a knapsack. Item i has value vi, weight wi and limitation mi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

You can select at most mi items for ith item.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1 m1
v2 w2 m2
:
vN wN mN

The first line consists of the integers N and W. In the following N lines, the value, weight and limitation of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 100

1 ≤ vi ≤ 1,000

1 ≤ wi ≤ 1,000

1 ≤ mi ≤ 10,000

1 ≤ W ≤ 10,000

Sample Input 1

4 8
4 3 2
2 1 1
1 2 4
3 2 2

Sample Output 1

12

Sample Input 2

2 100
1 1 100
2 1 50

Sample Output 2

150


object Main extends App {
  val Seq(n,q): Seq[Int] = io.StdIn.readLine().split(" ").map(_.toInt)
  val ds = new DisjointSets(n)
  (0 until q) foreach {_ =>
    io.StdIn.readLine().split(" ").map(_.toInt) match {
      case Array(0, x, y) => ds.union(x, y)
      case Array(1, x, y) => println(if (ds.same(x,y)) 1 else 0)
    }
  }
}
class DisjointSets(size: Int) {
  val parent: Array[Int] = Array.tabulate(size)(i => i)
  val rank: Array[Int] = Array.fill(size)(0)
  def union(x: Int, y: Int): Unit = {
    val i = find(x)
    val j = find(y)
    if (rank(i) > rank(j)) parent(j) = i
    else {
      parent(i) = j
      rank(i) += (if (rank(i) == rank(j)) 1 else 0)
    }
  }
  def find(x: Int): Int = parent(x) match {
    case p if x == p => x
    case p =>
      val i = find(p)
      parent(x) = i
      rank(x) = 0
      i
  }
  def same(x: Int, y: Int):Boolean = find(x) == find(y)
}

Disjoint Set

Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}.

First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... n−1 respectively.

Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of queries for different operations:

unite(x, y): unites sets that contain x and y, say Sx and Sy, into a new set.

same(x, y): determine whether x and y are in the same set.

Input

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

In the first line, n and q are given. Then, q queries are given where com represents the type of queries. '0' denotes unite and '1' denotes same operation.

Output

For each same operation, print 1 if x and y are in the same set, otherwise 0, in a line.

Constraints

1 ≤ n ≤ 10000

1 ≤ q ≤ 100000

x ≠ y

Sample Input

5 12
0 1 4
0 2 3
1 1 2
1 3 4
1 1 4
1 3 2
0 1 3
1 2 4
1 3 0
0 0 4
1 0 2
1 3 0

Sample Output

0
0
1
1
1
0
1
1


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

package net.pushl {
  package number {
    // Prime    (Prime.scala)
    // Number   (Number.scala)
    // Combi    (Combi.scala)
    // Optimize (Optimize.scala)
  }
  package string {
    // RollingHash (RollingHash.scala)
  }
  package geometry {
    // Point   (Geometry.scala)
    // Segment (Geometry.scala)
    // Line    (Geometry.scala)
  }
  package datastructure {
    // UnionFindTree (UnionFind.scala)
  }
  package io {
  }
}

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 = calcDataSize(_n)
    private val data = {
      val d = implicitly[ClassTag[T]].newArray(2*n-1)
      (0 until n).foreach(d(_) = init)
      d
    }
    // Array.fill[implicitly[ClassTag[T]]](calcDataSize(n))(init)

    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.
    private 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 calcDataSize(n: Int) = {
      @tailrec
      def calcDataSizeAux(k: Int) : Int = {
        if(k >= n) k
        else calcDataSizeAux(k*2)
      }
      calcDataSizeAux(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)
  }
}

// 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))
      }
    }
  }
}

// ----------------------------------------------------------------------------0
// ----------------------------------------------------------------------------0
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(obj)

    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) 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')
          readLong(readWithoutCheckingPeeked(), 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(read(),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(next.toChar)
          appendCode(readWithoutCheckingPeeked())
        }
      }
      val res = appendCode(read())
      skipTrailingSpaces()
      res
    }
    // TODO: refactoring to marge nextString
    def readLine() : String = {
      if(isEnd(peek))
        throw new NoSuchElementException("Reading Line failed")
      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[this] var peeked: Option[Int] = None
    private[this] var last = -1
    private def read() = {
      val res = peeked match {
          case None    => in.read()
          case Some(a) => { peeked = None; a }
        }
      last = res
      res
    }
    @inline private def readWithoutCheckingPeeked() = {
      val res = in.read()
      last = res
      res
    }
    @inline private def peek() =
      peeked match {
        case None    => {
          val res = in.read()
          peeked  = Some(res)
          res
        }
        case Some(a) => a
      }
    @inline private def isEnd(c: Int)    = c == -1
    @inline private def isNewLine(c: Int) = c == 10 || c == 13     // LF and CR
    @inline private def isThereReadable() = !isEnd(peek)
    // XXX: this limits c is ASCII?
    @inline private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127
    @tailrec
    final private def goNextNotSpaceNorControl() : Unit =
      if(isSpaceOrControl(peek)){
        read()
        goNextNotSpaceNorControl()
      }
    final private def skipTrailingSpaces() : Unit = {
      @tailrec
      def skipTrailingSpacesAux() : Unit = {
        if(!isNewLine(last) && !isNewLine(peek) && isSpaceOrControl(peek)){
          read()
          skipTrailingSpacesAux()
        }
      }
      skipTrailingSpacesAux
      if(!isNewLine(last) && isNewLine(peek)) {
        val _ = read()
      }
    }
    @tailrec
    final private def skipTrailingSpacesAndNewline() : Unit =
      if(isNewLine(peek)){
        val _ = read() // windows causes error. maybe.
      }else if(isSpaceOrControl(peek)){
        read()
        skipTrailingSpacesAndNewline()
      }
    @inline private def goNextValuable() = {
      goNextNotSpaceNorControl()
      isThereReadable()
    }
    @inline private def parseLineToVector[X](parser: () => X) : Vector[X] = {
      import scala.collection.immutable.VectorBuilder
      val vb = new VectorBuilder[X]()
      @tailrec
      def parseLineToVectorAux(first: Boolean=false) : Vector[X] =
        if((!first && isNewLine(last)) || isNewLine(peek) || isEnd(peek)) {
          vb.result
        }else{
          vb += parser()
          parseLineToVectorAux()
        }
      parseLineToVectorAux(true)
    }
  }
}

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