object Main {
    def main(args: Array[String]) = {
        val inf = Int.MaxValue-100000
        val in = io.Source.stdin.getLines
        val v = in.next.toInt
        val g = Array.fill(v)(inf)
        val e = in.flatMap(x => {val y = x.split(" ").map(_.toInt); y.drop(2).grouped(2).map(y(0) +: _)})
        g(0) = 0
        var flag = true
        while(flag) {
            flag = false
            for (b <- e) if (g(b(0)) + b(2) < g(b(1))) {g(b(1)) = g(b(0)) + b(2); flag = true}
        }
        g.zipWithIndex.foreach(p => println(p._2 + " " + p._1))
    }
}

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

Single Source Shortest Path

For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.

Input

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

$u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$

Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$).

Output

For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 100$

$0 \leq c_i \leq 100,000$

$|E| \leq 10,000$

All vertices are reachable from vertex $0$

Sample Input 1

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

Sample Output 1

0 0
1 2
2 2
3 1
4 3

Reference

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


import scala.io.StdIn.readLine

object Main {
  def main(args:Array[String]) = {
    val s1 = readLine
    val s2 = readLine
    for(i<-0 to s1.length-s2.length)
      if(s1(i)==s2(0))
        if(s1.slice(i,i+s2.length)==s2)
          println(i)
  }
}

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

Naive String Search

Find places where a string P is found within a text T.

Print all indices of T where P found. The indices of T start with 0.

Input

In the first line, a text T is given. In the second line, a string P is given.

output

Print an index of T where P found in a line. Print the indices in ascending order.

Constraints

1 ≤ length of T ≤ 1000

1 ≤ length of P ≤ 1000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
aa

Sample Output 1

0
3
4

Sample Input 2

xyzz
yz

Sample Output 2

1

Sample Input 3

abc
xyz

Sample Output3

The ouput should be empty.

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.


import scala.io.StdIn

object Main{
  def main(args: Array[String]) = {
    def gcd(a: Int,  b: Int): Int = if (b == 0) a else gcd(b,  a % b)
    val (a :: b :: _) = StdIn.readLine().split(" ").map(_.toInt).toList
    println(gcd(a,  b))
  }
}

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


object Main {
  def gcd(a: Int, b: Int): Int = {
    if (b == 0) {
      a
    } else {
      gcd(b, a % b)
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(a, b) = io.StdIn.readLine().split(" ").map(_.toInt)
    println(gcd(a, b))
  }
}


import scala.io.StdIn

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

        println(yukuriddo(a(0), a(1)))
    }

    def yukuriddo(a: Int, b: Int): Int = {

        if(b != 0){
            yukuriddo(b, a % b)
        }else{
        a
        }

    }
}


import scala.io.StdIn.readLine;
object Main {
    def main(args: Array[String]): Unit = {
        val Array(x, y) = readLine.split(" ").map(_.toInt);
        println(gcd(x, y));
    }
    def gcd(x: Int, y: Int): Int = {
        if (x < y) {
            gcd(y, x);
        } else if (x % y == 0) {
            y;
        } else {
            gcd(y, x % y);
        }
    }
}


object Main{
  def main(args: Array[String]){
    val in = new java.util.Scanner(System.in)
    val a = in.nextInt
    var count = 0

    var arr = new Array[Int](a)
    for(i <- 0 to a-1){
      arr(i) = in.nextInt
    }

    for(i <- 0 to a-2){
      var minpos = i;
      var minval = arr(i);

      for(j <- i+1 to a-1){
        if(arr(j) < minval){
          minpos = j;
          minval = arr(j)
        }
      }

      if(minpos != i){
        var tmp = arr(minpos)
        arr(minpos) = arr(i)
        arr(i) = tmp
        count = count + 1
      }
    }

    println(arr.mkString(" "))
    println(count)
  }
}

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


object Main {
  def main(args:Array[String]) = {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val ls = List.fill(n)(sc.nextInt)
    println(ls.filter(i => is_prime(i)).size)
  }
  def is_prime2(n: Int): Boolean = {
    if (n == 2) return true
    //val count = (2 to n).filter(i => i * i <= n).filter(j => n % j == 0).size //memory limit exceeded
    val count_seq = for (i <- 2 to n if i * i <= n; if n % i == 0) yield i //memory limit exceeded
    val count = count_seq.size
    if (count == 0) true else false
  }
  def is_prime(n: Int): Boolean = {
    if (n == 2)
      return true
    var i = 2
    while (i * i <= n){
      if (n%i == 0){
        return false
      }
      i += 1
    }
    return true
  }
}


object Main {
  def is_prime(n: Int): Boolean = {
    if (n == 2)
      return true
    var i = 2
    while (i * i <= n){
      if (n%i == 0){
        return false
      }
      i += 1
    }
    return true
  }
  def main(args:Array[String]) = {
    //val primes = for (i <- 2 to 999999 if is_prime(i)) yield i
    val primes = (2 to 999999).par.filter(i => is_prime(i))
    val sc = new java.util.Scanner(System.in)
    while (sc.hasNext){
      val n = sc.nextInt
      println(primes.count(i => i <= n))
    }
  }
}


import scala.io.Source

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

    println(lines.toList.tail.filter(_ != -1).length)
  }

  def isPrime(n: Int): Boolean = (2 to Math.sqrt(n).toInt).forall(n % _ != 0)
}


import scala.io.StdIn.readInt

object Main {
  val r = Array(2,3,5,7)

  def twoPow(d:Int,s:Int):(Int,Int) = {
    if(d%2 == 1) (d,s)
    else twoPow(d>>1,s+1)
  }

  def maybePrime(i:Int,d:Int,s:Int, n:Int):Boolean = {
    if(i>3) true
    else {
      val a = r(i)
      val x = BigInt(a).modPow(d,n).toLong

      if(x==1 || x==n-1) maybePrime(i+1,d,s,n)
      else repeat(s-1,x*x%n, i, d, s, n)
    }
  }

  def repeat(j:Int, x:Long, i:Int, d:Int, s:Int, n:Int):Boolean = {
    if(j==0) false
    else if(x==1) false
    else if(x==n-1) maybePrime(i+1,d,s,n)
    else repeat(j-1,x*x%n,i,d,s,n)
  }

  def isPrime(n:Int):Boolean = {
    if(n<2000) (2 to Math.sqrt(n).toInt).forall(n%_ != 0)
    else if(n%2==0) false
    else {
      val (d,s) = twoPow(n-1,0)
      maybePrime(0,d,s,n)
    }
  }

  def main(args:Array[String]) = {
    val n = readInt
    println((0 until n).count{ _=> isPrime(readInt) })
  }
}


object Main{
  def main(args:Array[String]) = {
    val lines = for{
      in <-scala.io.Source.stdin.getLines()
    }yield if(isPrime(in.toInt)) in else -1

    println(lines.filter(_ != -1).length)
  }
  def isPrime(n : Int) : Boolean = (2 to Math.sqrt(n).toInt).forall(n % _ != 0)
}


object Main {
  def main(args: Array[String]): Unit = {
    val scanner = new java.util.Scanner(System.in)

    var a = 0
    for(_ <- 1 to scanner.nextInt) {
      val x = scanner.nextDouble
      if((2 to math.sqrt(x).toInt).find(x % _ == 0).isEmpty) a = a + 1
    }
    println(a)
  }
}


import scala.io.StdIn
import scala.math.sqrt

object Main{
    def main(args: Array[String]){
        val sc = new java.util.Scanner(System.in)
        val n = sc.nextInt // 最初の数字を読み取る
        val list = List.fill(n)(sc.nextInt) // nextIntがn回呼ばれる
        var count = 0;
        for(j <- list)if(isPrime(j)) count = count + 1

        println(count)
    }

    def isPrime(x: Int): Boolean = {
        if(x == 2){
            return true
        }

        if(x < 2 || x % 2 == 0){
            return false
        }

        var i = 3;
        while(i <= sqrt(x)){
            if(x % i == 0){
                return false
            }
            i += 2
        }
        return true
    }
}


import java.util.Scanner
import scala.annotation.tailrec

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

    println(rec(list, Int.MinValue, Int.MaxValue))
  }

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

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.StdIn.readInt
import scala.io.Source.stdin

object Main {
  def main(args: Array[String]) = {
    val list = stdin.getLines().map { _.toInt }
    val n = list.next()
    val r0 = list.next()
    val r1 = list.next()
    var max = r1 - r0
    var min = if(r0 > r1) r1 else r0
    for( m <- list ) {
      if( max < m - min) {
        max = m - min
        if( min > m )
          min = m
      }
      else if( min > m ) {
        min = m
      }
    }
    println(max)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val inputString = "6\n2\n3\n1\n3\n4\n3"
//    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 t = intArray(j) - intArray(i)
        if(t>ret) ret = t
      }
    }
    println(ret)
  }
}


import scala.io.StdIn
object Main extends App {

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

  var minv = StdIn.readLine().trim.toInt
  var maxv = (scala.math.pow(10, 9) * -1 ).toInt
  (1 until n).foreach{ j =>
    val temp = StdIn.readLine().trim.toInt
    maxv = if(maxv < temp - minv) temp - minv else maxv
    minv = if(temp < minv) temp else minv
  }

  println(maxv)

}


import scala.io.Source

object Main {
//  def calcMaxProfit(numbers: Seq[Int]): Int = {
//    val maxProfit: Int = (1 to numbers.size-1)
//      .toStream
//      .map{i =>
//        val a  = numbers(i-1)
//        val bs = numbers.toStream.drop(i)
//        bs.max - a
//      }
//      .max
//    maxProfit
//  }

  def calcMaxProfit(numbers: Seq[Int]): Int = {
    var min       = numbers(0)
    var maxProfit = numbers(1) - min
    for(i <- 1 until numbers.size) {
      maxProfit = math.max(maxProfit, numbers(i) - min)
      min       = math.min(min, numbers(i))
    }
    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).toArray

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

    // Print max profit
    println(maxProfit)
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val r = Array.fill(n)(sc.nextInt())

    var minv = r(0)
    var maxv = r(1) - r(0)

    (1 until n).foreach { j =>
      maxv = Math.max(maxv, r(j) - minv)
      minv = Math.min(minv, r(j))
    }

    println(maxv)
  }

}


import scala.io.StdIn

object Main {

  def bubbleSort(A: Array[Int]){
    def swap(i: Int, j: Int) {
      val t = A(i); A(i) = A(j); A(j) = t
      ()
    }

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

    println(A.mkString(" "))
    println(count)
  }

  def main(args: Array[String]){
    val N = StdIn.readInt()
    val input = StdIn.readLine().split(" ").map(_.toInt)
    bubbleSort(input)
  }
}

Bubble Sort

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

BubbleSort(A)
1 for i = 0 to A.length-1
2 for j = A.length-1 downto i+1
3 if A[j] < A[j-1]
4 swap A[j] and A[j-1]

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

Your program should also print the number of swap operations defined in line 4 of the pseudocode.

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

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

5
5 3 2 4 1

Sample Output 1

1 2 3 4 5
8

Sample Input 2

6
5 2 4 6 1 3

Sample Output 2

1 2 3 4 5 6
9


import scala.io.StdIn

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

    bSort(List(), line, 0)
  }

  def bSort(sorted: List[Int], unsorted: List[Int], n: Int){
    if(unsorted.length == 0) println(n)
    else bSort(sorted :+ unsorted.min, unsorted.filterNot(_ == unsorted.min), n+1)
  }
}


import scala.io.StdIn
import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

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 {
      val pos = unsorted.indexWhere(_ == unsorted.min)
      val swapped = unsorted.updated(0, unsorted(pos)).updated(pos, unsorted(0))

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

  def deleteOne(list: List[Int], index: Int): List[Int] = {
    val buf = ListBuffer(list: _*)
    buf.remove(index)
    buf.toList
  }
}

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
import scala.collection.mutable.ListBuffer

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 {
      val pos = unsorted.indexWhere(_ == unsorted.min)
      val swapped = unsorted.updated(0, unsorted(pos)).updated(pos, unsorted.head)

      if(pos == 0) sSort(sorted :+ unsorted.min, unsorted.updated(0, unsorted(pos)).updated(pos, unsorted.head).tail, n)
      else sSort(sorted :+ unsorted.min, unsorted.updated(0, unsorted(pos)).updated(pos, unsorted.head).tail, n+1)
    }
  }
}


object Main{
  def main(args: Array[String]){
    val in = new java.util.Scanner(System.in)
    val a = in.nextInt
    var count = 0;

    var arr = new Array[Int](a)
    for(i <- 0 to a-1){
      arr(i) = in.nextInt
    }

    for(i <- 0 to a-2){
      var minpos = i;
      var minval = arr(i);

      for(j <- i+1 to a-1){
        if(arr(j) < minval){
          minpos = j;
          minval = arr(j)
        }
      }

      if(minpos != i){
        var tmp = arr(minpos)
        arr(minpos) = arr(i)
        arr(i) = tmp
        count = count + 1
      }
    }

    println(arr.mkString(" "))
    println(count)
  }
}


object Main {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val a = io.StdIn.readLine().split(" ").map(_.toInt)
    val count = selectionSort(a, n)
    println(a.mkString(" "))
    println(count)
  }

  def selectionSort(a: Array[Int], n: Int): Int = {
    (0 until n).count { i =>
      val minIdx = (i until n).foldLeft(i) { case (z, j) =>
        if (a(j) < a(z)) j
        else z
      }
      if (i != minIdx) {
        val v = a(i)
        a(i) = a(minIdx)
        a(minIdx) = v
        true
      } else {
        false
      }
    }
  }
}


import scala.io.StdIn

object Main {
  def main(args: Array[String]) = {
    val n = StdIn.readInt
    val array = StdIn.readLine.split(" ").map(_.toInt)
    val t = selectionSort(n, array)
    println(t._1.mkString(" "))
    println(t._2)
  }

  def selectionSort(n: Int, array: Array[Int]) = {
    var count = 0
    for (i <- 0 to n - 1) {
      var min = i
      for (k <- i to n - 1) {
        if (array(min) > array(k)) {
          min = k
        }
      }
      if (array(min) != array(i)) {
        val tmp = array(i)
        array(i) = array(min)
        array(min) = tmp
        count = count + 1
      }
    }
    (array, count)
  }
}


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val arr: Array[String] = Array.fill(N)(sc.next())
    val arrBubble: Array[String] = arr.clone()
    val arrSelect: Array[String] = arr.clone()

    println(bubbleSort(arrBubble))
    checkStable(arr, arrBubble)
    println(selectionSort(arrSelect))
    checkStable(arr, arrSelect)
  }

  def bubbleSort(arr: Array[String]): String = {
    for(i <- 0 until arr.length) {
      for(j <- arr.length-1 until i by -1) {
        if(arr(j).last.toInt < arr(j-1).last.toInt) {
          val t = arr(j); arr(j) = arr(j-1); arr(j-1) = t  // swap
        }
      }
    }
    return arr.mkString(" ")
  }

  def selectionSort(arr: Array[String]): String = {
    for((x, i) <- arr.zipWithIndex) {
      var minj = i
      for(j <- i until arr.length) {
        if(arr(minj).last.toInt > arr(j).last.toInt) minj = j
      }
      val t = arr(i); arr(i) = arr(minj); arr(minj) = t
    }
    return arr.mkString(" ")
  }

  def checkStable(arrOrigin: Array[String], arrSorted: Array[String]): Unit = {
    for((a, i) <- arrOrigin.zipWithIndex) {
      for((b, j) <- arrOrigin.zipWithIndex if i != j && a.last.toInt == b.last.toInt) {
        for((c, k) <- arrSorted.zipWithIndex if a == c) {
          for((d, l) <- arrSorted.zipWithIndex if b == d) {
            if((i - j) * (k - l) < 0) {
              println("Not stable")
              return
            }
          }
        }
      }
    }
    println("Stable")
  }
}

Stable Sort

Let's arrange a deck of cards. There are totally 36 cards of 4 suits(S, H, C, D) and 9 values (1, 2, ... 9). For example, 'eight of heart' is represented by H8 and 'one of diamonds' is represented by D1.

Your task is to write a program which sorts a given set of cards in ascending order by their values using the Bubble Sort algorithms and the Selection Sort algorithm respectively. These algorithms should be based on the following pseudocode:

BubbleSort(C)
1 for i = 0 to C.length-1
2 for j = C.length-1 downto i+1
3 if C[j].value < C[j-1].value
4 swap C[j] and C[j-1]

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

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

For each algorithm, 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 line. Each card is represented by two characters. Two consecutive cards are separated by a space character.

Output

In the first line, print the arranged cards provided by the Bubble Sort algorithm. Two consecutive cards should be separated by a space character.

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

In the third line, print the arranged cards provided by the Selection Sort algorithm. Two consecutive cards should be separated by a space character.

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

Constraints

1 ≤ N ≤ 36

Sample Input 1

5
H4 C9 S4 D2 C3

Sample Output 1

D2 C3 H4 S4 C9
Stable
D2 C3 S4 H4 C9
Not stable

Sample Input 2

2
S1 H1

Sample Output 2

S1 H1
Stable
S1 H1
Stable


import scala.io.StdIn
object Main extends App {

  val rn = StdIn.readLine().trim.toInt
  case class Card(suit: Char, num: Int){
    override def toString: String = s"$suit$num"
  }
  val ra = StdIn.readLine().trim.split(' ').map{ p =>
    Card(p.charAt(0), p.charAt(1).toString.toInt)
  }
  val ra1 = ra.clone()
  val ra2 = ra.clone()

  def isStable(a: Array[Card], after: Array[Card], n: Int): Boolean = {
    (0 until n).foreach{ i =>
      if(a(i).suit != after(i).suit) return false
    }
    true
  }

  def bubbleSort(a: Array[Card], n: Int): Array[Card] = {
    (0 until n).foreach{ i =>
      // println(s"bubble($i):" + a.toList)
      (n-1 until i by -1).foreach{ j =>
        if(a(j).num < a(j-1).num){
          val temp = a(j)
          a(j) = a(j-1)
          a(j-1) = temp
        }
      }
    }
    a
  }

  def selectionSort(a: Array[Card], n: Int): Array[Card] = {
    (0 until n).foreach{ i =>
      // println(s"selection($i):" + a.toList)

      var minj = i
      (i until n).foreach{ j =>
        minj = if(a(j).num < a(minj).num) j else minj
      }
      val temp = a(minj)
      a(minj) = a(i)
      a(i) = temp
    }
    a
  }

  val rbubble    = bubbleSort(ra1, rn)
  val rselection = selectionSort(ra2, rn)

  //println("ra:" + ra.toList.mkString(" "))
  println(rbubble.toList.mkString(" "))
  println("Stable")

  println(rselection.toList.mkString(" "))
  println(if(isStable(rbubble, rselection, rn)) "Stable" else "Not stable")

}


import scala.io.StdIn._

object Main extends App {

  def isLeftSmall(c1: String, c2: String): Boolean = {
    if (c1.takeRight(1).toInt < c2.takeRight(1).toInt) true else false
  }

  def bubbleSort(c: Array[String], n: Int) {
    for(i <- (0 to n - 1)) {
      for (j <- (n - 1 until i by -1)) {
        if (isLeftSmall(c(j), c(j - 1))) {
          val tmp_v = c(j)
          c(j) = c(j - 1)
          c(j - 1) = tmp_v
        }
      }
    }
    println(c.mkString(" "))
    println("Stable")
  }

  def selectionSort(c: Array[String], n: Int) {
    for (i <- (0 to n - 1)) {
      var min_j = i
      for (j <- (i to n - 1)) {
        if (isLeftSmall(c(j), c(min_j))) {
          min_j = j
        }
      }
      val tmp_v = c(i)
      c(i) = c(min_j)
      c(min_j) = tmp_v
    }
    println(c.mkString(" "))
  }

  val n = readLine.toInt
  val c = readLine.split(" ").toArray
  val c1 = c.clone
  val c2 = c.clone
  bubbleSort(c1, n)
  selectionSort(c2, n)
  if (c1 sameElements c2) println("Stable") else println("Not stable")
}


import collection.mutable.Queue
import java.util._

object Main {
  val sc = new Scanner(System.in)
  val map = new HashMap[String,Int]
  val q = Queue[String]()
  val n = sc.nextInt
  val proces = sc.nextInt

  def main(args: Array[String]): Unit = {
    for( i <- 0 until n){
      var temp = sc.next
      q.enqueue(temp)
      map.put(temp, sc.nextInt)
    }
    new Solve().main
  }

  class Solve{
      def main{
        var count = 0
        while(!q.isEmpty){
          var temp = q.dequeue()

          if(map.get(temp) - proces > 0){
            map.put(temp ,map.get(temp) - proces)
            q.enqueue(temp)
            count += proces
          }else {
            count += map.get(temp)
            println(temp + " " +  count)
          }

        }
    }
  }
}

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
import scala.collection.immutable.Queue

object Main {

  def loop(n:Int,q:Queue[(String,Int)]):Queue[(String,Int)] = {
    if(n==0) q
    else {
      val m = readLine.split(" ")
      loop(n-1,q.enqueue((m(0),m(1).toInt)))
    }
  }

  def rrobin(q:Queue[(String,Int)],total:Int,str:String,qt:Int):String = {
    if(q.isEmpty) str
    else {
      val ((p,t),r) = q.dequeue
      val (newQ,newT,s):(Queue[(String,Int)],Int,String) = if(t>qt) (r.enqueue((p,t-qt)),qt,"") else  (r,t,p + " " + (t+total) + "\n")
      rrobin(newQ,total+newT,str+s,qt)
    }
  }

  def main(args:Array[String]) = {
    val l = readLine.split(" ").map(_.toInt)
    val q = loop(l(0),Queue[(String,Int)]())

    print(rrobin(q,0,"",l(1)))
  }
}


import scala.io.StdIn.{readInt, readLine};
object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val list = new DoublyLinkedList[Long]();
        for (i <- (0 until n)) {
            readLine.split(" ") match {
                case Array("insert", value) => list.insert(value.toLong);
                case Array("delete", value) => list.delete(value.toLong);
                case Array("deleteFirst") => list.deleteFirst;
                case Array("deleteLast") => list.deleteLast;
                case _ => ();
            }
        }
        println(list);
    }
}
class DoublyLinkedList[A]() {
    trait Node {var prev: Node; var next: Node;}
    case class Head(var prev: Node, var next: Node) extends Node;
    case class Elem(key: A, var prev: Node, var next: Node) extends Node;
    var length = 0;
    private val head = Head(null, null);
    def isEmpty: Boolean = length == 0;
    override def toString: String = {
        def go(node: Node, ret: List[A]): List[A] = {
            node match {
                case e: Elem => go(e.prev, e.key :: ret);
                case _ => ret;
            }
        }
        if (isEmpty) "" else go(head.prev, Nil).mkString(" ");
    }
    def insert(key: A): Unit = {
        if (isEmpty) {
            val e = Elem(key, head, head);
            head.next = e;
            head.prev = e;
        } else {
            val e = Elem(key, head, head.next);
            head.next.prev = e;
            head.next = e;
        }
        length += 1;
    }
    def delete(key: A): Unit = {
        def go(node: Node): Elem = {
            node match {
                case e: Elem => if (e.key == key) e else go(e.next);
                case _ => null;
            }
        }
        if (!isEmpty) {
            if (length == 1) {
                deleteFirst;
            } else {
                go(head.next) match {
                    case null => ();
                    case e => {
                        val n = e.next;
                        val p = e.prev;
                        n.prev = p;
                        p.next = n;
                        length -= 1;
                    }
                }
            }
        }
    }

    def deleteFirst: Unit = {
        if (!isEmpty) {
            if (length == 1) {
                head.next = null;
                head.prev = null;
            } else {
                val newFirst = head.next.next;
                newFirst.prev = head;
                head.next = newFirst;
            }
            length -= 1;
        }
    }
    def deleteLast: Unit = {
        if (!isEmpty) {
            if (length == 1) {
                head.next = null;
                head.prev = null;
            } else {
                val newLast = head.prev.prev;
                newLast.next = head;
                head.prev = newLast;
            }
            length -= 1;
        }
    }
}

Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1


object Main{
  def main(args:Array[String]) : Unit = {
      val sc = new java.util.Scanner(System.in)
      val n = sc.nextInt
      val list = List.fill(n)(sc.nextInt)
      val q = sc.nextInt
      val queries = List.fill(q)(sc.nextInt)
      val contained = queries.filter(binarySearch(list, _))
      println(contained.size)
  }
  def binarySearch(list: List[Int], n: Int) : Boolean = {
    val l = list.size
    if (l==0) false
    else if (list(l/2) > n ) binarySearch(list.slice(0, l/2), n)
    else if (list(l/2) == n) true
    else binarySearch(list.slice((l/2) + 1, list.size), n)
  }
}

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.{readInt,readLine}

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

  def search(a:Array[Int],value:Int) = {
    scan(a,value,0,a.length-1)
  }

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


object Main extends App {
  val in = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt).toList).toList
  val src = in.filter(in.indexOf(_) % 2 != 0)

  def binarySearch(li: List[Int], n: Int): Option[Int] = li match {
    case h :: Nil => if (h == n) Some(n) else None
    case _ => {
      val midIndex = li.length / 2
      val midValue = li(midIndex)
      if (n < midValue) binarySearch(li.take(midIndex), n)
      else if (n > midValue) binarySearch(li.drop(midIndex), n)
      else Some(n)
    }
  }

  println((for (i <- src(1)) yield { binarySearch(src(0), i )}).filter(_ != None).length)
}


import scala.io.StdIn.{readInt,readLine}
object Main {
    def main(args: Array[String]): Unit = {
        val input = readLine.split(" ").map(_.toInt)
        val luggages = (1 to input(0)).foldLeft(Nil: List[Int]) { (list, v) => readInt :: list}
        println(allocation(input(1), luggages.reverse))
    }
    def allocation(k: Int, wList: List[Int]): Int = {
        // 最大積載量 = capacity の場合にトラックに荷物が乗り切るかどうか
        def inCapacity(luggages: List[Int], truck: Int, capacity: Int, curr: Int): Boolean = luggages match {
            case Nil => true
            case x :: xs => {
                val tmpCurr = curr + x
                if (tmpCurr > capacity) {
                    if (truck == 1) false
                    else inCapacity(xs, truck - 1, capacity, x)
                } else {
                    inCapacity(xs, truck, capacity, curr + x)
                }
            }
        }
        // 最小の最大積載量を2分木探索で探索
        def binSearch(pc: Array[Int], leftPtr: Int, rightPtr: Int, currMin: Int): Int = (leftPtr + rightPtr) / 2 match {
            case center if leftPtr == rightPtr => if (center < currMin && inCapacity(wList, k, pc(center), 0)) pc(center) else currMin
            case center => inCapacity(wList, k, pc(center), 0) match {
                case true => binSearch(pc, leftPtr, center, pc(center))
                case false => binSearch(pc, center + 1, rightPtr, currMin)
            }
        }

        val maxCapa = wList.sum
        val possibleCapa = (1 to maxCapa).toArray
        binSearch(possibleCapa, 0, possibleCapa.length - 1, maxCapa)
    }
}

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

You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load $P$.

Write a program which reads $n$, $k$ and $w_i$, and reports the minimum value of the maximum load $P$ to load all packages from the belt conveyor.

Input

In the first line, two integers $n$ and $k$ are given separated by a space character. In the following $n$ lines, $w_i$ are given respectively.

Output

Print the minimum value of $P$ in a line.

Constraints

$1 \leq n \leq 100,000$

$1 \leq k \leq 100,000$

$1 \leq w_i \leq 10,000$

Sample Input 1

5 3
8
1
7
3
9

Sample Output 1

10

If the first truck loads two packages of $\{8, 1\}$, the second truck loads two packages of $\{7, 3\}$ and the third truck loads a package of $\{9\}$, then the minimum value of the maximum load $P$ shall be 10.

Sample Input 2

4 2
1
2
2
6

Sample Output 2

6

If the first truck loads three packages of $\{1, 2, 2\}$ and the second truck loads a package of $\{6\}$, then the minimum value of the maximum load $P$ shall be 6.


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

object Main extends App {

  val n  = readInt()
  val xs = readLine().split(" ").map { _.toInt }
  readLine()
  val ys = readLine().split(" ").map { _.toInt }

  val zs = mutable.Set.empty[Int]
  for {
    i  <- 1 to n
    cs <- xs.combinations(i).map { _.sum }
  } {
    zs += cs
  }

  for {
    y  <- ys
    ans = if (zs.contains(y)) "yes" else "no"
  } {
    println(ans)
  }
}

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 {
  def main(args: Array[String]): Unit = {
    val (n, s) = (io.StdIn.readLine().toInt, io.StdIn.readLine().split(' ').map(_.toInt).toList)

    var cnt = 0
    /*
    def merge(left: List[Int], right: List[Int]): List[Int] = (left, right) match {
      case (x :: xs, y :: ys) if x <= y => x :: merge(xs, right)
      case (x :: xs, y :: ys) if x > y => y :: merge(left, ys)
      case (Nil, ys) => right
      case (xs, Nil) => left
    }
    */
    def merge(left: List[Int], right: List[Int]): List[Int] = (left ::: right).sorted
    def mergeSort(list: List[Int]): List[Int] = list match {
      case x :: Nil => list
      case _ =>
        val (l1, l2) = list.splitAt(list.size / 2)
        cnt += l1.size + l2.size
        merge(mergeSort(l1), mergeSort(l2))
    }
    println(mergeSort(s).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.collection.mutable.ListBuffer
import scala.language.postfixOps

object Main {
  var cnt = 0

  def merge(a:Array[Int],left:Int,mid:Int,right:Int) = { val n1 = mid-left
    val n2 = right-mid
    val l = a.slice(left,left+n1) :+ Int.MaxValue
    val r = a.slice(mid,mid+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 sort(n:Int):Iterator[(Int,Int)] = {
    var l2 = Iterator((0,n/2),(n/2,n))
    var n2 = n/2
    while(n2>1) {
      l2 = for(i<-l2;j<-List((i._1,(i._2+i._1)/2),((i._2+i._1)/2,i._2)) iterator) yield j
      n2 = n2/2
    }
    l2
  }

  def mergeSort(l:List[(Int,Int)],a:Array[Int]):Unit = {
    if(l.length==1) return
    else {
      var i = 0
      var left = 0
      var right = 0
      val b = new ListBuffer[(Int,Int)]
      for(e<-l) {
          val mid = (e._2+e._1)/2
          if(e._2-e._1>1)
            merge(a,e._1,mid,e._2)
          if(i==1) {
            right = e._2
            b += ((left,right))
            i = 0
          } else {
            left = e._1
            i+=1
          }
      }
      mergeSort(b.toList,a)
    }
  }

  def main(args:Array[String]) = {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val r = sort(n)
    mergeSort(r.toList,a)
    merge(a,0,n/2,n)
    println(a.mkString(" "))
    println(cnt)
  }
}


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

object Main {
  var cnt = 0
  val l = new Array[Int](260000)
  val r = new Array[Int](260000)
  val b = new ListBuffer[(Int,Int)]

  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 sort(n:Int):Iterator[(Int,Int)] = {
    var l2 = Iterator((0,n/2),(n/2,n))
    var n2 = n/2
    while(n2>1) {
      l2 = for(i<-l2;j<-List((i._1,(i._2+i._1)/2),((i._2+i._1)/2,i._2)) iterator) yield j
      n2 = n2/2
    }
    l2
  }

  def mergeSort(l:List[(Int,Int)],a:Array[Int]):Unit = {
    if(l.length==1) return
    else {
      var i = 0
      var left = 0
      var right = 0
      b.clear()
      for(e<-l) {
          val mid = (e._2+e._1)/2
          if(e._2-e._1>1)
            merge(a,e._1,mid,e._2)
          if(i==1) {
            right = e._2
            b += ((left,right))
            i = 0
          } else {
            left = e._1
            i+=1
          }
      }
      mergeSort(b.toList,a)
    }
  }

  def main(args:Array[String]) = {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val r = sort(n)
    mergeSort(r.toList,a)
    merge(a,0,n/2,n)
    println(a.mkString(" "))
    println(cnt)
  }
}


object Main {
    var res = 0
    def msort(arr: Array[Int]): Array[Int] = {
        if (arr.size > 1) {
            val a = msort(arr.take(arr.size/2))
            val b = msort(arr.drop(arr.size/2))
            var i, j, k = 0
            var f = true
            while (f) {
                if (i == a.size && j == b.size) f = false
                else if (j == b.size) {arr(k) = a(i); i += 1; k += 1}
                else if (i == a.size) {arr(k) = b(j); j += 1; k += 1}
                else if (a(i) < b(j)) {arr(k) = a(i); i += 1; k += 1}
                else {arr(k) = b(j); j += 1; k += 1; res += (a.size-i)}
            }
        }
        arr
    }
    def main(args: Array[String]) = {
        val in = io.Source.stdin.getLines.map(_.split(" ").map(_.toInt))
        in.next
        msort(in.next)
        println(res)
    }
}

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

object Main extends App {

  val rn = StdIn.readLine().trim.toInt
  val ina = StdIn.readLine().trim.split(' ').map(_.toInt)

  final val infity = Int.MaxValue
  def mergeSort(): Long = {
    @inline def copyToArray(start: Int, end: Int): Array[Int] = {
      val alsize = end - start + 1
      val temp = new Array[Int](alsize)
      Array.copy(ina, start, temp, 0, alsize - 1)
      temp(alsize-1) = infity
      temp
    }

    def merge(left: Int, mid: Int, right: Int): Long ={
      val al = copyToArray(left, mid)
      val ar = copyToArray(mid, right)
      var i = 0
      var j = 0
      var cnt = 0L
      //println("left:" + al.toList)
      //println("right:" + ar.toList)
      (left until right).foreach{ k =>
        if(al(i) <= ar(j)){
          ina(k) = al(i)
          i += 1
        } else {
          ina(k) = ar(j)
          j += 1
          cnt += mid - left - i
        }
      }
      //println("all:" + ar2.toList.mkString(" "))
      cnt
    }

    def innerMergeSort(left: Int, right: Int): Long ={

      if(left+1 < right){
        val mid = (left + right) / 2
        val rleft = innerMergeSort(left, mid)
        val rright = innerMergeSort(mid, right)
        val rmerge = merge(left, mid, right)

        rleft + rright + rmerge
      } else {
        0L
      }
    }

    innerMergeSort(0, rn)

  }

  println(mergeSort)

}


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

object Main extends App {
  import CountingSort.countingSort

  val n  = readInt()
  val xs = readLine().split(' ').map { _.toInt }

  val ys = countingSort(xs)
  println(ys.mkString(" "))
}

object CountingSort {
  val MaxValue = 10000

  def countingSort(xs: Array[Int]): Array[Int] = {
    val counts = {
      val counts = Array.fill(MaxValue + 1)(0)
      for (x <- xs) {
        counts(x) += 1
      }

      var i = 1
      while (i <= MaxValue) {
        counts(i) = counts(i) + counts(i - 1)
        i += 1
      }

      counts
    }

    val ys = new Array[Int](xs.length)
    for (x <- xs) {
      ys(counts(x) - 1) = x
      counts(x) -= 1
    }

    ys
  }
}

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


object Main extends App {
  val n: Int = io.StdIn.readLine().toInt
  val arr: Array[Int] = io.StdIn.readLine().split(" ") map(_.toInt)

  def partition(arr: Array[Int], i: Int, p: Int, r:Int): (Array[Int], Int) = {
    val a: Array[Int] = arr.clone()
    var p: Int = 0

    for(i <- 0 until r) {
      val (ai, ap, ar) = (a(i), a(p), a(r))
      if (i == p) {if (ai <= ar) p += 1}
      else {if (ai <= ar && ai < ap) {a(i) = ap; a(p) = ai; p += 1}}
    }
    val ap = a(p)
    a(p) = a(r); a(r) = ap

    (a,p)
  }

  val (pa, i): (Array[Int], Int) = partition(arr, 0, 0, n-1)
  println(pa.slice(0, i).mkString(" ") + " [" + pa(i) + "] " + pa.slice(i+1, n).mkString(" "))
}

Partition

Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.

In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).

Your task is to read a sequence A and perform the Partition 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

Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].

Input

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

In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [  ].

Constraints

1 ≤ n ≤ 100,000

0 ≤ Ai ≤ 100,000

Sample Input 1

12
13 19 9 5 12 8 7 4 21 2 6 11

Sample Output 1

9 5 8 7 4 2 6 [11] 21 13 19 12


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 = arr.slice(first, pivot + 1);
        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};

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;
        }
        val s = new Sort[(String, Long)]();
        s.quickSort(arr1, n);
        s.mergeSort(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"));
    }
}
class Sort[A](implicit ord: Ordering[A]) {
    import ord._;

    def quickSort(arr: Array[A], n: Int): 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);
    }

    private def partition(arr: Array[A], first: Int, last: Int): Int = {
        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(arr: Array[A], a: Int, b: Int): Unit = {
        val tmp = arr(a);
        arr(a) = arr(b);
        arr(b) = tmp;
    }

    def mergeSort(arr: Array[A], n: Int): Int = {
        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);
    }

    private def merge(arr: Array[A], first: Int, last: Int, pivot: Int): Unit = {
        val tmpArr = arr.slice(first, pivot + 1);
        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;
                }
            }
        }
    }
}


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

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[Card](n);
        val arr2 = new Array[Card](n);
        (0 until n).foreach { i =>
            val input = readLine.split(" ");
            val elem = Card(input(0), input(1).toInt);
            arr1(i) = elem;
            arr2(i) = elem;
        }
        quickSort(arr1, n);
        mergeSort(arr2, n);

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

    def quickSort(arr: Array[Card], n: Int): Unit = {
        def _quickSort(first: Int, last: Int): Unit = {
            if (first < last){
                val (pivot, needsPartition) = partition(first, last);
                if (needsPartition) {
                    _quickSort(first, pivot - 1);
                    _quickSort(pivot + 1, last);
                }
            }
        }
        def partition(first: Int, last: Int): (Int, Boolean) = {
            val pivot = arr(last);
            def _partition(sep: Int, ptr: Int, flag: Boolean): (Int, Boolean) = {
                if (ptr > last) {
                    (sep, flag);
                } else if (arr(ptr) > pivot) {
                    _partition(sep, ptr + 1, true);
                }else if (arr(ptr) < pivot) {
                    swap(arr, sep + 1, ptr);
                    _partition(sep + 1, ptr + 1, true);
                } else {
                    swap(arr, sep + 1, ptr);
                    _partition(sep + 1, ptr + 1, flag);
                }
            }
            _partition(-1, 0, false);
        }
        _quickSort(0, n - 1);
    }

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

    def mergeSort(arr: Array[Card], n: Int): Unit = {
        def _mergeSort(first: Int, last: Int): Unit = {
            if (first < last) {
                val pivot = (first + last) / 2;
                val cnt1 = _mergeSort(first, pivot);
                val cnt2 = _mergeSort(pivot + 1, last);
                merge(first, last, pivot);
            }
        }
        def merge(first: Int, last: Int, pivot: Int): Unit = {
            val tmpArr = arr.slice(first, pivot + 1);
            var ptr1 = 0;
            var ptr2 = pivot + 1;
            for (i <- (first to last)) {
                if (ptr1 >= tmpArr.length) {
                    ptr2 += 1;
                } else if (ptr2 > last || tmpArr(ptr1) <= arr(ptr2)) {
                    arr(i) = tmpArr(ptr1);
                    ptr1 += 1;
                } else {
                    arr(i) = arr(ptr2);
                    ptr2 += 1;
                }
            }
        }

        _mergeSort(0, n - 1);
    }
}
case class Card(symbol: String, num: Int) {
    override def toString(): String = symbol + " " + num
    def <(a: Card): Boolean = this.num < a.num
    def <=(a: Card): Boolean = this.num <= a.num
    def >(a: Card): Boolean =  this.num > a.num
    def >=(a: Card): Boolean =  this.num >= a.num
}


object Main extends App {
  val children = collection.mutable.Map.empty[String, Array[String]]
  val parent = collection.mutable.Map.empty[String, String]
  val n = io.StdIn.readInt()

  for {
    _ <- 0 until n
    l = io.StdIn.readLine()split(" ", 3)
  } l match {
    case Array(id, _) => children.put(id, Array.empty[String])
    case Array(id, _, nodes) =>
      val nodeSeq = nodes.split(" ")
      children.put(id, nodeSeq)
      nodeSeq foreach(parent.put(_, id))
  }

  for (i <- 0 until n) {
    val current = i.toString
    val p = parent.get(current) match {
      case None => "-1"
      case Some(x) => x
    }
    def depth(s: String): Int = parent.get(s) match {
      case None => 0
      case Some(x) => depth(x)
    }
    val d = depth(current)
    val c = children(current).mkString("[", ", ", "]")

    val t = if (p == "-1") "root" else if (c == "[]") "leaf" else "internal node"

    println(s"node $i: parent = $p, depth = $d, $t, $c")
  }
}

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

object Main {
  def main(args: Array[String]): Unit = {
    val n: Int = io.StdIn.readInt()
    val children = Array.fill(n)(Seq(-1,-1))
    val parent: Array[Option[Int]] = Array.fill(n)(None)

    for {
      _ <- 0 until n
      l = io.StdIn.readLine()
    } {
      val Seq(i, c1, c2): Seq[Int] = l.split(" ", 3).map(_.toInt)
      children(i) = Seq(c1, c2)
      if (c1 != -1) parent(c1) = Some(i)
      if (c2 != -1) parent(c2) = Some(i)
    }

    def depth: Memoized[Int, Int] = Memoized {i =>
      parent(i) match {
        case None => 0
        case Some(x) => 1 + depth(x)
      }
    }
    def hight: Memoized[Int, Int] = Memoized {i =>
      children(i) match {
        case Seq(-1, -1) => 0
        case Seq(x,  -1) => 1 + hight(x)
        case Seq(-1,  y) => 1 + hight(y)
        case Seq(x,   y) => 1 + (hight(x) max hight(y))
      }
    }

    for (i <- 0 until n) {
      val p = parent(i).getOrElse(-1)
      val s: Int = if (p == -1) -1 else children(p).filterNot(_ == i).head
      val deg: Int = children(i).filterNot(_ == -1).length
      val t = if (p == -1) "root" else if (deg == 0) "leaf" else "internal node"

      println(s"node $i: parent = $p, sibling = $s, degree = $deg, depth = ${depth(i)}, height = ${hight(i)}, $t")
    }
  }

  case class Memoized[Arg, Ret](f: Arg => Ret) extends (Arg => Ret) {
    val cache: mutable.Map[Arg, Ret] = mutable.Map[Arg, Ret]()
    def apply(arg: Arg): Ret = cache.getOrElseUpdate(arg, f(arg))

  }
}

Binary Tree

A rooted binary tree is a tree with a root node in which every node has at most two children.

Your task is to write a program which reads a rooted binary tree T and prints the following information for each node u of T:

node ID of u

parent of u

sibling of u

the number of children of u

depth of u

height of u

node type (root, internal node or leaf)

If two nodes have the same parent, they are siblings. Here, if u and v have the same parent, we say u is a sibling of v (vice versa).

The height of a node in a tree is the number of edges on the longest simple downward path from the node to a leaf.

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

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 is given in the following format:

id left right

id is the node ID, left is ID of the left child and right is ID of the right child. If the node does not have the left (right) child, the left(right) is indicated by -1.

Output

Print the information of each node in the following format:

node id: parent = p, sibling = s, degree = deg, depth = dep, height = h, type

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

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

deg, dep and h are the number of children, depth and height of the node respectively.

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.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 25

Sample Input 1

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

Sample Output 1

node 0: parent = -1, sibling = -1, degree = 2, depth = 0, height = 3, root
node 1: parent = 0, sibling = 4, degree = 2, depth = 1, height = 1, internal node
node 2: parent = 1, sibling = 3, degree = 0, depth = 2, height = 0, leaf
node 3: parent = 1, sibling = 2, degree = 0, depth = 2, height = 0, leaf
node 4: parent = 0, sibling = 1, degree = 2, depth = 1, height = 2, internal node
node 5: parent = 4, sibling = 8, degree = 2, depth = 2, height = 1, internal node
node 6: parent = 5, sibling = 7, degree = 0, depth = 3, height = 0, leaf
node 7: parent = 5, sibling = 6, degree = 0, depth = 3, height = 0, leaf
node 8: parent = 4, sibling = 5, degree = 0, depth = 2, height = 0, leaf

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 };
object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val l = (0 until n).map{ a =>
            readLine.split(" ") match {
                case Array(v, l, r) => Some((v.toInt, l.toInt, r.toInt));
                case _ => None;
            }
        }.toList
        val bTree = new BinaryTrees(n);
        bTree.build(l);
        bTree.dump();
    }
}
class BinaryTrees(len: Int) {
    case class Node(left: Int, right: Int)
    var root = -1;
    val tree = new Array[Node](len);
    def build(data: List[Option[(Int, Int, Int)]]): Unit = data match {
        case Some((value, left, right)) :: xs =>
            tree(value) = Node(left, right);
            if (root == -1 || left == root || right == root) root = value;
            build(xs);
        case x :: xs => build(xs);
        case Nil => ()
    }
    def dump(): Unit = {
        val dumpArr = new Array[String](len);
        def _dump(curr: Int, parent: Int, sibling: Int, depth: Int): Unit = {
            if (curr == -1) {
                //  nop
            } else {
                val degree = getDegree(curr);
                val nodeType = getNodeType(curr, parent);
                val height = getHeight(curr);
                dumpArr(curr) = nodeToString(curr, parent, sibling, degree, depth, height, nodeType);
                _dump(tree(curr).left, curr, tree(curr).right, depth + 1);
                _dump(tree(curr).right, curr, tree(curr).left, depth + 1);
            }
        }
        _dump(root, -1, -1, 0);
        println(dumpArr.mkString("\n"));
    }
    def getHeight(curr: Int): Int = {
        if (curr == -1) {
            -1;
        } else {
            val leftHeight = getHeight(tree(curr).left);
            val rightHeight = getHeight(tree(curr).right);
            if (leftHeight < rightHeight) rightHeight + 1 else leftHeight + 1;
        }
    }
    def nodeToString(curr: Int, parent: Int, sibling: Int, degree: Int, depth: Int, height: Int, nodeType: String): String = {
        s"node ${curr}: parent = ${parent}, sibling = ${sibling}, degree = ${degree}, depth = ${depth}, height = ${height}, ${nodeType}";
    }
    def getDegree(v: Int): Int = {
        val n = tree(v);
        var ret = 2;
        if (n.left == -1) ret -= 1;
        if (n.right == -1) ret -= 1;
        ret;
    }
    def getNodeType(v: Int, parent: Int): String = {
        if (parent == -1) "root" else if (tree(v).left == -1 && tree(v).right == -1) "leaf" else "internal node";
    }
}


import scala.io.StdIn

object Main extends App {

  final val nil = -1

  case class Node(var parent: Int = -1,var left: Int = -1, var right: Int = -1){

    def typeInfo: String = if(parent == -1) {
      "root"
    } else if(left == nil && right == nil) {
      "leaf"
    } else {
      "internal node"
    }

    def nodeLiteral(depth: Int, sibling: Int, height: Int): String = {
      val degree = (if(left == nil) 0 else 1) + (if(right == nil) 0 else 1)
      s"parent = $parent, sibling = $sibling, degree = $degree, depth = $depth, height = $height, $typeInfo"
    }
    override def toString: String = s"parent = $parent, depth = X, $typeInfo, [child]"

  }

  def setDepth(index: Int, cnt: Int): Unit = {
    //println("setDepth:" + index)
    depth(index) = cnt
    if(input(index).right != nil){
      setDepth(input(index).right, cnt + 1)
    }
    if(input(index).left != nil){
      setDepth(input(index).left, cnt + 1)
    }
  }

  def setHeight(index: Int): Int = {
    //println("setDepth:" + index)
    val h1 = if(input(index).right != nil){
      setHeight(input(index).right) + 1
    } else 0
    val h2 = if(input(index).left != nil){
      setHeight(input(index).left) + 1
    } else 0
    height(index) = scala.math.max(h1, h2)
    height(index)
  }

  def getChild(index: Int): Array[Int] = (input(index).left, input(index).right) match {
    case (-1,      -1) => Array.empty[Int]
    case (left,    -1) => Array(left)
    case (-1,   right) => Array(right)
    case (left, right) => Array(left, right)
  }

  val n = StdIn.readLine().trim.toInt
  val input  = Array.fill[Node](n)(Node())
  val depth  = Array.fill[Int](n)(0)
  val height = Array.fill[Int](n)(0)

  (0 until n).foreach{ _ =>
    val Array(current, left, right) = StdIn.readLine().trim.split(" ").map(_.toInt)
    input(current).left = left
    input(current).right = right
    if(left != nil) input(left).parent = current
    if(right != nil) input(right).parent = current
  }

  var root = nil
  (0 until n).foreach{ i =>
    //println(s"$i:" + input(i))
    if(input(i).parent == nil) root = i
  }

  setDepth(root, 0)
  setHeight(root)

  (0 until n).foreach{ i =>
    val ch = getChild(i)
    val parent = input(i).parent
    val sibling = if(parent != nil){
      if(input(parent).left == i) input(parent).right
      else input(parent).left
    } else -1

    println(s"node $i: " + input(i).nodeLiteral(depth(i), sibling, height(i)))
  }

}


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

object Main {
  val tree0 = new Array[Int](500001)
  val tree1 = new Array[Int](500001)
  val tree2 = new Array[Int](500001)
  val a = new ArrayBuffer[Int]

  def insert(i:Int, j:Int):Unit =
    if(tree0(i) > tree0(j)) {
      if(tree1(i) == -1) tree1(i) = j
      else insert(tree1(i), j)
    } else {
      if(tree2(i) == -1) tree2(i) = j
      else insert(tree2(i), j)
    }

  def inOrder():Unit = {
    var stack:List[Int] = Nil
    var curr = 0
    var flg = true

    while(flg) {
      while(curr != -1) {
        stack = curr::stack
        curr = tree1(curr)
      }
      if(curr == -1 && stack != Nil) {
        val item = stack.head
        stack = stack.tail
        a.append(tree0(item))
        curr = tree2(item)
      } else {
        flg = false
      }
    }
  }

  def scan(list:List[Int]):Unit = {
    list match {
      case Nil => ()
      case hd::tl => {
        a.append(tree0(hd))
        val hd2 =
          if(tree2(hd) != -1 && tree1(hd) != -1) tree1(hd)::tree2(hd)::tl
          else if(tree2(hd) != -1 && tree1(hd) == -1) tree2(hd)::tl
          else if(tree2(hd) == -1 && tree1(hd) != -1) tree1(hd)::tl
          else tl
        scan(hd2)
      }
    }
  }

  def preOrder(i:Int):Unit =
    if(i == -1) return
    else scan(i::Nil)

  def main(args:Array[String]) = {
    val n = readInt
    var j = 0
    val out:BufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512)

    for(i<-0 until n) {
      val s = readLine.split(" ")
      s(0) match {
        case "insert" => {
          tree0(j) = s(1).toInt
          tree1(j) = -1
          tree2(j) = -1
          if(j!=0) insert(0, j)
          j+=1
        }
        case _ => {
          a.clear
          inOrder();
          out.write(" ")
          out.write(a.mkString(" "))
          out.write("\n")
          out.flush()
          a.clear
          preOrder(0)
          out.write(" ")
          out.write(a.mkString(" "))
          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 java.io._
import scala.io.StdIn.{readInt, readLine}

object Main {
  val tree0 = new Array[Int](500001)
  val tree1 = new Array[Int](500001)
  val tree2 = new Array[Int](500001)
  val out:BufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512)
  var count = 0

  def insert(i:Int, j:Int):Unit =
    if(tree0(i) > tree0(j)) {
      if(tree1(i) == -1) tree1(i) = j
      else insert(tree1(i), j)
    } else {
      if(tree2(i) == -1) tree2(i) = j
      else insert(tree2(i), j)
    }

  def inOrder():Unit = {
    var stack:List[Int] = Nil
    var curr = 0
    var flg = true

    while(flg) {
      while(curr != -1) {
        stack = curr::stack
        curr = tree1(curr)
      }
      if(curr == -1 && stack != Nil) {
        val item = stack.head
        stack = stack.tail
        out.write(" ")
        out.write(tree0(item).toString)
        if(count<100) count += 1
        else {
          out.flush
          count = 0
        }
        curr = tree2(item)
      } else {
        flg = false
      }
    }
  }

  def scan(list:List[Int]):Unit = {
    list match {
      case Nil => ()
      case hd::tl => {
        out.write(" ")
        out.write(tree0(hd).toString)
        if(count<100) count += 1
        else {
          out.flush
          count = 0
        }
        val hd2 =
          if(tree2(hd) != -1 && tree1(hd) != -1) tree1(hd)::tree2(hd)::tl
          else if(tree2(hd) != -1 && tree1(hd) == -1) tree2(hd)::tl
          else if(tree2(hd) == -1 && tree1(hd) != -1) tree1(hd)::tl
          else tl
        scan(hd2)
      }
    }
  }

  def preOrder(i:Int):Unit =
    if(i == -1) return
    else scan(i::Nil)

  def main(args:Array[String]) = {
    val n = readInt
    var j = 0

    for(i<-0 until n) {
      val s = readLine.split(" ")
      s(0) match {
        case "insert" => {
          tree0(j) = s(1).toInt
          tree1(j) = -1
          tree2(j) = -1
          if(j!=0) insert(0, j)
          j+=1
        }
        case _ => {
          inOrder()
          out.write("\n")
          out.flush()
          preOrder(0)
          out.write("\n")
          out.flush()
        }
      }
    }
  }
}


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 loop(node:Node):Node =
      if(node.key > keyNode.key) {
        if(node.left == null) node
        else loop(node.left)
      } else {
        if(node.right == null) node
        else loop(node.right)
      }

    val target = loop(tree)

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

  def inOrder(root:Node):Unit = {
    var stack:List[Node] = Nil
    var curr = root
    var flg = true

    while(flg) {
      while(curr != null) {
        stack = curr::stack
        curr = curr.left
      }
      if(curr == null && stack != Nil) {
        val item = stack.head
        stack = stack.tail
        out.write(" ")
        out.write(item.key.toString)
        if(count<100) count += 1
        else {
          out.flush
          count = 0
        }
        curr = item.right
      } else {
        flg = false
      }
    }
  }

  def scan(list:List[Node]):Unit = {
    list match {
      case Nil => ()
      case hd::tl => {
        out.write(" ")
        out.write(hd.key.toString)
        if(count<100) count += 1
        else {
          out.flush
          count = 0
        }
        val hd2 = if(hd.right!=null) hd.right::tl else tl
        val hd3 =if(hd.left!=null) hd.left::hd2 else hd2
        scan(hd3)
      }
    }
  }

  def preOrder(tree:Node):Unit =
    if(tree == null) return
    else  scan(tree::Nil)

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


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

object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val arr = readLine.split(" ").map(_.toInt);
        build(n, arr);
        println(arr.mkString(" "));
    }

    def build(length: Int, arr: Array[Int]): Unit = {
        def go(curr: Int): Unit = {
            if (curr < length) {
                go(curr * 2 + 1);
                heapify(length, arr, curr);
                go(curr * 2 + 2);
            }
        }
        go(0);
    }

    def heapify(length: Int, arr: Array[Int], idx: Int): Unit = {
        val left = idx * 2 + 1;
        val right = idx * 2 + 2;
        if (right < length) {
            val m = max(arr, idx, left, right);
            if (idx != m) {
                swap(arr, idx, m);
                heapify(length, arr, m);
            }
        } else if (left < length) {
            if (arr(left) > arr(idx)) swap(arr, left, idx);
        } else {
            // nop
        }
    }

    def max(arr: Array[Int], k1: Int, k2: Int, k3: Int): Int = {
        val v1 = arr(k1); val v2 = arr(k2); val v3 = arr(k3);
        if (v1 > v2) {
            if (v1 > v3) k1 else k3;
        } else {
            if (v2 > v3) k2 else k3;
        }
    }

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

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

Maximum Heap

A binary heap which satisfies max-heap property is called max-heap. In a max-heap, for every node $i$ other than the root, $A[i] \leq A[parent(i)]$, that is, the value of a node is at most the value of its parent. The largest element in a max-heap is stored at the root, and the subtree rooted at a node contains values no larger than that contained at the node itself.

Here is an example of a max-heap.

Write a program which reads an array and constructs a max-heap from the array based on the following pseudo code.

$maxHeapify(A, i)$ move the value of $A[i]$ down to leaves to make a sub-tree of node $i$ a max-heap. Here, $H$ is the size of the heap.

1 maxHeapify(A, i)
2 l = left(i)
3 r = right(i)
4 // select the node which has the maximum value
5 if l ≤ H and A[l] > A[i]
6 largest = l
7 else
8 largest = i
9 if r ≤ H and A[r] > A[largest]
10 largest = r
11
12 if largest ≠ i　// value of children is larger than that of i
13 swap A[i] and A[largest]
14 maxHeapify(A, largest) // call recursively

The following procedure buildMaxHeap(A) makes $A$ a max-heap by performing maxHeapify in a bottom-up manner.

1 buildMaxHeap(A)
2 for i = H/2 downto 1
3 maxHeapify(A, i)

Input

In the first line, an integer $H$ is given. In the second line, $H$ integers which represent elements in the binary heap are given in order of node id (from $1$ to $H$).

Output

Print values of nodes in the max-heap in order of their id (from $1$ to $H$). Print a single space character before each value.

Constraint

$1 \leq H \leq 500,000$

$-2,000,000,000 \leq$ value of a node $\leq 2,000,000,000$

Sample Input 1

10
4 1 3 2 16 9 10 14 8 7

Sample Output 1

16 14 10 8 7 9 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.io.StdIn.{readInt, readLine};

object Main {
    def main(args: Array[String]): Unit = {
        val n = readInt;
        val arr = readLine.split(" ").map(_.toInt);
        build(n, arr);
        println(" " + arr.mkString(" "));
    }

    def build(length: Int, arr: Array[Int]): Unit = {
        def go(curr: Int): Unit = {
            if (curr < length) {
                go(curr * 2 + 1);
                heapify(length, arr, curr);
                go(curr * 2 + 2);
            }
        }
        go(0);
    }

    def heapify(length: Int, arr: Array[Int], idx: Int): Unit = {
        val left = idx * 2 + 1;
        val right = idx * 2 + 2;
        if (right < length) {
            val m = max(arr, idx, left, right);
            if (idx != m) {
                swap(arr, idx, m);
                heapify(length, arr, m);
            }
        } else if (left < length) {
            if (arr(left) > arr(idx)) swap(arr, left, idx);
        } else {
            // nop
        }
    }

    def max(arr: Array[Int], k1: Int, k2: Int, k3: Int): Int = {
        val v1 = arr(k1); val v2 = arr(k2); val v3 = arr(k3);
        if (v1 > v2) {
            if (v1 > v3) k1 else k3;
        } else {
            if (v2 > v3) k2 else k3;
        }
    }

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


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

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

  def toZero(x:Double) = if(x == -0.0) 0.0 else x
  def main(args:Array[String]) = {
   val p = readLine.split(" ").map(_.toDouble)
   val n = readInt

   val (x0,y0,x1,y1) = (p(0),p(1),p(2),p(3))
   for(i<-0 until n) {
     val p1 = readLine.split(" ").map(_.toDouble)
     val (x2,y2) = (p1(0),p1(1))
     val sqrt = Math.pow(x1-x0,2) + Math.pow(y1-y0,2)
     val inner = (x1-x0)*(x2-x0) + (y1-y0)*(y2-y0)
     val (xt,yt) = (inner*(x1-x0)/sqrt + x0, inner*(y1-y0)/sqrt + y0)
     out.write(toZero(xt).toString)
     out.write(" ")
     out.write(toZero(yt).toString)
     out.write("\n")
     if(count<10) count += 1
     else {
      out.flush
      count = 0
     }
   }
   out.flush
   out.close
  }
}

Projection

For given three points p1, p2, p, find the projection point x of p onto p1p2.

Input

xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpq−1 ypq−1

In the first line, integer coordinates of p1 and p2 are given. Then, q queries are given for integer coordinates of p.

Output

For each query, print the coordinate of the projection point x. The output values should be in a decimal fraction with an error less than 0.00000001.

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xi, yi ≤ 10000

p1 and p2 are not identical.

Sample Input 1

0 0 2 0
3
-1 1
0 1
1 1

Sample Output 1

-1.0000000000 0.0000000000
0.0000000000 0.0000000000
1.0000000000 0.0000000000

Sample Input 2

0 0 3 4
1
2 5

Sample Output 2

3.1200000000 4.1600000000


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

object Main {
  def cross(x0:Double, y0:Double, x1:Double, y1:Double) = x0*y1-x1*y0
  def inner(x0:Double, y0:Double, x1:Double, y1:Double) = x0*x1+y0*y1
  def norm(x:Double, y:Double) = x*x+y*y

  def dir(x0:Double,y0:Double,x1:Double,y1:Double) =
    if(cross(x0,y0,x1,y1) > (1e-10)) (-1)
    else if(cross(x0,y0,x1,y1) < -(1e-10)) 1
    else if(inner(x0,y0,x1,y1) < -(1e-10)) 1
    else if(norm(x0,y0) < norm(x1,y1)) 0
    else 0

  def intersect(x0:Double,y0:Double,x1:Double,y1:Double,x2:Double,y2:Double,x3:Double,y3:Double) = {
   (dir(x2-x0,y2-y0,x1-x0,y1-y0) * dir(x3-x0,y3-y0,x1-x0,y1-y0) <= 0) &&
    (dir(x1-x2,y1-y2,x3-x2,y3-y2) * dir(x0-x2,y0-y2,x3-x2,y3-y2) <= 0)
  }

  def main(args:Array[String]) = {
    val n = readInt
    for(i<-0 until n) {
      val s = readLine.split(" ").map(_.toDouble)
      if(intersect(s(0),s(1),s(2),s(3),s(4),s(5),s(6),s(7))) println(1)
      else println(0)
    }
  }
}

Intersection

For given two segments s1 and s2, print "1" if they are intersect, "0" otherwise.

s1 is formed by end points p0 and p1, and
s2 is formed by end points p2 and p3.

Input

The entire input looks like:

q (the number of queries)
1st query
2nd query
...
qth query

Each query consists of integer coordinates of end points of s1 and s2 in the following format:

xp0 yp0 xp1 yp1 xp2 yp2 xp3 yp3

Output

For each query, print "1" or "0".

Constraints

1 ≤ q ≤ 1000

-10000 ≤ xpi, ypi ≤ 10000

p0 ≠ p1 and
p2 ≠ p3.

Sample Input 1

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

Sample Output 1

1
1
0


object Main {
  def main(args: Array[String]): Unit = {
    val (num, limit) = {
      val nw = io.StdIn.readLine().split(" ").map(_.toInt)
      (nw(0), nw(1))
    }
    val items = new Array[(Int, Int)](num)
    for (i <- 0 until num) {
      val vw = io.StdIn.readLine().split(" ").map(_.toInt)
      items(i) = (vw(0), vw(1))
    }

    val dp = solve(limit, items)
    println(dp(num)(limit))
  }

  def solve(limit: Int, items: Array[(Int, Int)]): Array[Array[Int]] = {
    val dp = Array.ofDim[Int](items.length + 1, limit + 1)

    items.zipWithIndex.foreach { case ((v, w), i) =>
      for (l <- 1 to limit) {
        if (w <= l && dp(i)(l) < dp(i)(l - w) + v) {
          dp(i + 1)(l) = dp(i)(l - w) + v
        } else {
          dp(i + 1)(l) = dp(i)(l)
        }
      }
    }
    dp
  }
}

Knapsack Problem

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

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 as many items as possible into a knapsack for each kind.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following lines, the value and weight 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 ≤ 1000

1 ≤ wi ≤ 1000

1 ≤ W ≤ 10000

Sample Input 1

4 8
4 2
5 2
2 1
8 3

Sample Output 1

21

Sample Input 2

2 20
5 9
4 10

Sample Output 2

10

Sample Input 3

3 9
2 1
3 1
5 2

Sample Output 3

27


object Main {

  class UnionFind(val n: Int) {
    private[this] val par = Array.range(0, n)

    def root(x: Int): Int = if(par(x) == x) x else root(par(x))

    def same(x: Int, y: Int): Boolean = root(x) == root(y)

    def unite(x: Int, y: Int): Unit = par(root(x)) = root(y)
  }

  def main(args: Array[String]): Unit = {
    val Array(n,q,_*) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val uf = new UnionFind(n)

    for(i <- 1 to q){
      val Array(com,x,y,_*) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
      if(com==0)uf.unite(x,y)
      else println(if(uf.same(x,y)) 1 else 0)
    }
  }
}

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