You are given n segments on the coordinate axis Ox and the number k. The point is satisfied if it belongs to at least k segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 106) — the number of segments and the value of k. The next n lines contain two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109) each — the endpoints of the i-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.

First line contains integer m — the smallest number of segments. Next m lines contain two integers aj, bj (aj ≤ bj) — the ends of j-th segment in the answer. The segments should be listed in the order from left to right.

import java.io.PrintWriter
import java.io.IOException
import java.io.InputStreamReader
import java.io.BufferedReader
import java.util.InputMismatchException
import java.util.StringTokenizer
import java.util.Scanner
import scala.Nil
import scala.annotation.tailrec

object Main {
  def main(args: Array[String]) {
    val scan = new FasterScanner();
    val out: PrintWriter = new PrintWriter(System.out)

    val n:Int = scan.nextInt
    val k:Int = scan.nextInt

    val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)
    for(i <- 0 until n){
      val x:Int = i*2
      val y:Int = i*2 + 1
      segments(x) = (scan.nextInt*2,1)
      segments(y) = (scan.nextInt*2+1,-1)
    }

    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))

    var kk: Int = 0
    var resN: Int = 0
    var i: Int = 0
    val res:Array[Int] = new Array[Int](n*2)
    while (i < 2 * n) {
      {
        kk += sortedSeg(i)._2
        if (kk >= k) {
          res(resN*2) = sortedSeg(i)._1/2
          while (kk >= k) {
            i += 1
            kk += sortedSeg(i)._2
          }
          res(resN*2+1) = (sortedSeg(i)._1-1)/2
          resN += 1
        }
      }
      i += 1
    }
    out.println(resN)
    for( i <- 0 until resN){
      out.println(res(i*2)+" "+res(i*2+1))
    }
    out.close();
  }

  class FasterScanner {
    private var buf: Array[Byte] = new Array[Byte](1024)
    private var curChar: Int = 0
    private var numChars: Int = 0

    def read: Int = {
      if (numChars == -1) throw new InputMismatchException
      if (curChar >= numChars) {
        curChar = 0
        try {
          numChars = System.in.read(buf)
        }
        catch {
          case e: IOException => {
            throw new InputMismatchException
          }
        }
        if (numChars <= 0) return -1
      }
      return buf(({
        curChar += 1; curChar - 1
      }))
    }

    def nextLine: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isEndOfLine(c))
      return res.toString
    }

    def nextString: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isSpaceChar(c))
      return res.toString
    }

    def nextLong: Long = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Long = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      return res * sgn
    }

    def nextInt: Int = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Int = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      return res * sgn
    }

    def nextIntArray(n: Int): Array[Int] = {
      val arr: Array[Int] = new Array[Int](n)
        var i: Int = 0
        while (i < n) {
          {
            arr(i) = nextInt
          }
          ({
            i += 1; i - 1
          })
        }
      return arr
    }

    def nextLongArray(n: Int): Array[Long] = {
      val arr: Array[Long] = new Array[Long](n)
        var i: Int = 0
        while (i < n) {
          {
            arr(i) = nextLong
          }
          ({
            i += 1; i - 1
          })
        }
      return arr
    }

    private def isSpaceChar(c: Int): Boolean = {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1
    }

    private def isEndOfLine(c: Int): Boolean = {
      return c == '\n' || c == '\r' || c == -1
    }
  }
}

import java.io.PrintWriter
import java.io.IOException
import java.util.InputMismatchException
import scala.annotation.tailrec

object Main {
  def main(args: Array[String]) {
    val scan = new FasterScanner();
    val out: PrintWriter = new PrintWriter(System.out)

    val n:Int = scan.nextInt
    val k:Int = scan.nextInt

    val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)
    for(i <- 0 until n){
      val x:Int = i*2
      val y:Int = i*2 + 1
      segments(x) = (scan.nextInt*2,1)
      segments(y) = (scan.nextInt*2+1,-1)
    }

    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))

    var kk: Int = 0
    var resN: Int = 0
    var i: Int = 0
    val res:Array[Int] = new Array[Int](n*2)
    while (i < 2 * n) {
      {
        kk += sortedSeg(i)._2
        if (kk >= k) {
          res(resN*2) = sortedSeg(i)._1/2
          while (kk >= k) {
            i += 1
            kk += sortedSeg(i)._2
          }
          res(resN*2+1) = (sortedSeg(i)._1-1)/2
          resN += 1
        }
      }
      i += 1
    }
    out.println(resN)
    for( i <- 0 until resN){
      out.println(res(i*2)+" "+res(i*2+1))
    }
    out.close()
  }

  class FasterScanner {
    private val buf: Array[Byte] = new Array[Byte](1024)
    private var curChar: Int = 0
    private var numChars: Int = 0

    def read: Int = {
      if (numChars == -1) throw new InputMismatchException
      if (curChar >= numChars) {
        curChar = 0
        try {
          numChars = System.in.read(buf)
        }
        catch {
          case e: IOException =>
            throw new InputMismatchException
        }
        if (numChars <= 0) return -1
      }
      buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]
    }

    def nextLine: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isEndOfLine(c))
      res.toString
    }

    def nextString: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isSpaceChar(c))
      res.toString
    }

    def nextLong: Long = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Long = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt: Int = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Int = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextIntArray(n: Int): Array[Int] = {
      val arr: Array[Int] = new Array[Int](n)
      for(i <- 0 until n){
        arr(i) = nextInt
      }
      arr
    }

    def nextLongArray(n: Int): Array[Long] = {
      val arr: Array[Long] = new Array[Long](n)
      for(i <- 0 until n){
        arr(i) = nextLong
      }
      arr
    }

    private def isSpaceChar(c: Int): Boolean = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1
    }

    private def isEndOfLine(c: Int): Boolean = {
      c == '\n' || c == '\r' || c == -1
    }
  }
}

import java.io._
import java.util.InputMismatchException

import scala.annotation.tailrec

object Codeforces_Scala{
  def main(args: Array[String]) {
    val scan = new FasterScanner();
    val out: PrintWriter = new PrintWriter(System.out)

    val n:Int = scan.nextInt
    val k:Int = scan.nextInt

    val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)
    for(i <- 0 until n){
      val x:Int = i*2
      val y:Int = i*2 + 1
      segments(x) = (scan.nextInt*2,1)
      segments(y) = (scan.nextInt*2+1,-1)
    }

    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))
  /*
    val proSeg = Process(sortedSeg,0,0,k,Nil,Nil)
    out.println(proSeg.length)
    proSeg.foreach(e=>out.println(e._1+" "+e._2))
    out.flush()
    out.close()
    */
    Run(sortedSeg,n,k,out)
  }

  def Run(sortedSeg: Array[(Int, Int)],n:Int,k:Int,out: PrintWriter): Unit ={
    var kk: Int = 0
    var resN: Int = 0
    var i: Int = 0
    val res:Array[Int] = new Array[Int](n*2)
    while (i < 2 * n) {
      {
        kk += sortedSeg(i)._2
        if (kk >= k) {
          res(resN*2) = sortedSeg(i)._1/2
          while (kk >= k) {
            i += 1
            kk += sortedSeg(i)._2
          }
          res(resN*2+1) = (sortedSeg(i)._1-1)/2
          resN += 1
        }
      }
      i += 1
    }
    out.println(resN)
    for( i <- 0 until resN){
      out.println(res(i*2)+" "+res(i*2+1))
    }
    out.close()
  }
  //Nothing: 所有类型的子类
  //Nil: 空的List即List[Nothing]
  //Null: 引用的空值
  //None: 空的object
  @tailrec
  def Process(seg: List[(Int,Int)], len:Int, k:Int, K:Int, p:List[Int], resList:List[(Int, Int)]) :List[(Int, Int)] = {
    if(len>=seg.length){
      resList
    }else{
      val x = seg(len)
      val kk = k+x._2
      if(kk>=K && p == Nil){
        Process(seg,len+1,kk,K,List(x._1),resList)
      }else if(kk<K && p != Nil){
        Process(seg,len+1,kk,K,Nil,resList:::List((p(0)/2,x._1/2)))
      }else{
        Process(seg,len+1,kk,K,p,resList)
      }
    }
  }

  class FasterScanner {
    private val buf: Array[Byte] = new Array[Byte](1024)
    private var curChar: Int = 0
    private var numChars: Int = 0

    def read: Int = {
      if (numChars == -1) throw new InputMismatchException
      if (curChar >= numChars) {
        curChar = 0
        try {
          numChars = System.in.read(buf)
        }
        catch {
          case e: IOException =>
            throw new InputMismatchException
        }
        if (numChars <= 0) return -1
      }
      buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]
    }

    def nextLine: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isEndOfLine(c))
      res.toString
    }

    def nextString: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isSpaceChar(c))
      res.toString
    }

    def nextLong: Long = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Long = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt: Int = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Int = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextIntArray(n: Int): Array[Int] = {
      val arr: Array[Int] = new Array[Int](n)
      for(i <- 0 until n){
        arr(i) = nextInt
      }
      arr
    }

    def nextLongArray(n: Int): Array[Long] = {
      val arr: Array[Long] = new Array[Long](n)
      for(i <- 0 until n){
        arr(i) = nextLong
      }
      arr
    }

    private def isSpaceChar(c: Int): Boolean = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1
    }

    private def isEndOfLine(c: Int): Boolean = {
      c == '\n' || c == '\r' || c == -1
    }
  }
}

import java.io._
import java.util.InputMismatchException

import scala.annotation.tailrec

object Codeforces_Scala{
  def main(args: Array[String]) {
    val scan = new FasterScanner();
    val out: PrintWriter = new PrintWriter(System.out)

    val n:Int = scan.nextInt
    val k:Int = scan.nextInt

    val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)
    for(i <- 0 until n){
      val x:Int = i*2
      val y:Int = i*2 + 1
      segments(x) = (scan.nextInt*2,1)
      segments(y) = (scan.nextInt*2+1,-1)
    }

    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))

    val res:Array[Int] = new Array[Int](n*2)
    val resN:Int = Process(sortedSeg,0,0,k,res,0,false)
    out.println(resN)
    for(i <- 0 until resN){
      out.println(res(i*2)+" "+res(i*2+1))
    }
    out.flush()
    out.close()

    //Run(sortedSeg,n,k,out)
  }

  def Run(sortedSeg: Array[(Int, Int)],n:Int,k:Int,out: PrintWriter): Unit ={
    var kk: Int = 0
    var resN: Int = 0
    var i: Int = 0
    val res:Array[Int] = new Array[Int](n*2)
    while (i < 2 * n) {
      {
        kk += sortedSeg(i)._2
        if (kk >= k) {
          res(resN*2) = sortedSeg(i)._1/2
          while (kk >= k) {
            i += 1
            kk += sortedSeg(i)._2
          }
          res(resN*2+1) = (sortedSeg(i)._1-1)/2
          resN += 1
        }
      }
      i += 1
    }
    out.println(resN)
    for( i <- 0 until resN){
      out.println(res(i*2)+" "+res(i*2+1))
    }
    out.close()
  }
  //Nothing: 所有类型的子类
  //Nil: 空的List即List[Nothing]
  //Null: 引用的空值
  //None: 空的object
  @tailrec
  def Process(seg : Array[(Int, Int)], len:Int, k:Int, K:Int, res:Array[Int], resN:Int, flag: Boolean) :Int = {
    if(len>=seg.length){
      resN
    }else{
      val x = seg(len)
      val kk = k+x._2
      if(kk>=K && !flag){
        res(resN*2)=seg(len)._1/2
        Process(seg,len+1,kk,K,res,resN,true)
      }else if(kk<K && flag){
        res(resN*2+1)=(seg(len)._1-1)/2
        Process(seg,len+1,kk,K,res,resN+1,false)
      }else{
        Process(seg,len+1,kk,K,res,resN,flag)
      }
    }
  }

  class FasterScanner {
    private val buf: Array[Byte] = new Array[Byte](1024)
    private var curChar: Int = 0
    private var numChars: Int = 0

    def read: Int = {
      if (numChars == -1) throw new InputMismatchException
      if (curChar >= numChars) {
        curChar = 0
        try {
          numChars = System.in.read(buf)
        }
        catch {
          case e: IOException =>
            throw new InputMismatchException
        }
        if (numChars <= 0) return -1
      }
      buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]
    }

    def nextLine: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isEndOfLine(c))
      res.toString
    }

    def nextString: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isSpaceChar(c))
      res.toString
    }

    def nextLong: Long = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Long = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt: Int = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Int = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextIntArray(n: Int): Array[Int] = {
      val arr: Array[Int] = new Array[Int](n)
      for(i <- 0 until n){
        arr(i) = nextInt
      }
      arr
    }

    def nextLongArray(n: Int): Array[Long] = {
      val arr: Array[Long] = new Array[Long](n)
      for(i <- 0 until n){
        arr(i) = nextLong
      }
      arr
    }

    private def isSpaceChar(c: Int): Boolean = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1
    }

    private def isEndOfLine(c: Int): Boolean = {
      c == '\n' || c == '\r' || c == -1
    }
  }
}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
  	val scan = new Scanner(System.in)
  	val n = scan.nextInt()
  	val K = scan.nextInt()
  	val segments = Input(scan,n)
    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortWith(Compare)
    //sortedSeg.foreach(p=>println(p._1+" "+p._2))
    val proSeg = Process(sortedSeg,1)
    //proSeg.foreach(p=>println(p._1+" "+p._2))
    val mergeSeg = Merge(proSeg,1)
    println(mergeSeg.length)
    mergeSeg.foreach(p=>println(p._1+" "+p._2))
  }

  def Input(scan:Scanner,n: Int) :List[(Int, Int)] = {
    if (n <= 0) {
      Nil
    } else {
      val x0 = scan.nextInt()
      val x1 = scan.nextInt()
      (x0,x1)::Input(scan,n-1)
    }
  }

  def Compare(a :(Int, Int),b :(Int, Int)) :Boolean= {
    if(a._1 == b._1){
        a._2 < b._2
      }else{
        a._1 < b._1
      }

  }

  def Process(seg: List[(Int,Int)],k:Int) :List[(Int, Int)] = {
    if(k>=seg.length){
      Nil
    }else{
      val a = seg(k-1)
      val b = seg(k)
      if(a._2>=b._1){
        (b._1,a._2)::Process(seg,k+1)
      }else{
          Process(seg,k+1)
      }
    }
  }

  def Merge(seg: List[(Int,Int)],k:Int) :List[(Int, Int)] = {
    if(k>=seg.length){
      seg.takeRight(1)
    }else{
      val s = Merge(seg,k+1)
      val a = seg(k-1)
      val b = s(0)
      if(a._2>=b._1){
        (a._1,b._2)::s.drop(1)
      }else{
        a::s
      }
    }
  }
}

import java.io.IOException
import java.io.InputStreamReader
import java.io.BufferedReader
import java.util.InputMismatchException
import java.util.StringTokenizer
import java.util.Scanner
import scala.Nil
import scala.annotation.tailrec

object Main {
  def main(args: Array[String]) {
    val scan = new FasterScanner();
    val n:Int = scan.nextInt
    val k:Int = scan.nextInt

    val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)
    for(i <- 0 until n){
      val x:Int = i*2
      val y:Int = i*2 + 1
      segments(x) = (scan.nextInt*2,1)
      segments(y) = (scan.nextInt*2+1,-1)
    }

    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))

    var kk: Int = 0
    var resN: Int = 0
    var i: Int = 0
    val res:Array[Int] = new Array[Int](n*2)
    while (i < 2 * n) {
      {
        kk += sortedSeg(i)._2
        if (kk >= k) {
          res(resN*2) = sortedSeg(i)._1/2
          while (kk >= k) {
            i += 1
            kk += sortedSeg(i)._2
          }
          res(resN*2+1) = sortedSeg(i)._1/2
          resN += 1
        }
      }
      i += 1
    }
    println(resN)
    for( i <- 0 until resN){
      println(res(i*2)+" "+res(i*2+1))
    }
  }

  class FasterScanner {
    private var buf: Array[Byte] = new Array[Byte](1024)
    private var curChar: Int = 0
    private var numChars: Int = 0

    def read: Int = {
      if (numChars == -1) throw new InputMismatchException
      if (curChar >= numChars) {
        curChar = 0
        try {
          numChars = System.in.read(buf)
        }
        catch {
          case e: IOException => {
            throw new InputMismatchException
          }
        }
        if (numChars <= 0) return -1
      }
      return buf(({
        curChar += 1; curChar - 1
      }))
    }

    def nextLine: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isEndOfLine(c))
      return res.toString
    }

    def nextString: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isSpaceChar(c))
      return res.toString
    }

    def nextLong: Long = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Long = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      return res * sgn
    }

    def nextInt: Int = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Int = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      return res * sgn
    }

    def nextIntArray(n: Int): Array[Int] = {
      val arr: Array[Int] = new Array[Int](n)
        var i: Int = 0
        while (i < n) {
          {
            arr(i) = nextInt
          }
          ({
            i += 1; i - 1
          })
        }
      return arr
    }

    def nextLongArray(n: Int): Array[Long] = {
      val arr: Array[Long] = new Array[Long](n)
        var i: Int = 0
        while (i < n) {
          {
            arr(i) = nextLong
          }
          ({
            i += 1; i - 1
          })
        }
      return arr
    }

    private def isSpaceChar(c: Int): Boolean = {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1
    }

    private def isEndOfLine(c: Int): Boolean = {
      return c == '\n' || c == '\r' || c == -1
    }
  }
}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
  	val scan = new Scanner(System.in)
  	val n = scan.nextInt()
  	val k = scan.nextInt()
  	val segments = Input(scan,n)
    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))
    val proSeg = Process(sortedSeg,0,0,k,Nil)
    if(proSeg.length ==0){
      println(-1)
    }else{
      println(proSeg.length)
      proSeg.foreach(e=>println(e._1+" "+e._2))
    }

  }

  def Input(scan:Scanner,n: Int) :List[(Int, Int)] = {
    if (n <= 0) {
      Nil
    } else {
      val x0 = scan.nextInt()
      val x1 = scan.nextInt()
      //x*2,x*2+1避免两个点重复
      (x0*2,1)::(x1*2+1,-1)::Input(scan,n-1)
    }
  }

//Nothing: 所有类型的子类
//Nil: 空的List即List[Nothing]
//Null: 引用的空值
//None: 空的object
  def Process(seg: List[(Int,Int)],l:Int,d:Int,K:Int,p:List[Int]) :List[(Int, Int)] = {
    if(l>=seg.length){
      Nil
    }else{
      val x = seg(l)
      val dd = d+x._2
      if(dd>=K && p == Nil){
        Process(seg,l+1,dd,K,List(x._1))
      }else if(dd<K && p != Nil){
        (p(0)/2,x._1/2)::Process(seg,l+1,dd,K,Nil)
      }else{
        Process(seg,l+1,dd,K,p)
      }
    }
  }

}

import java.io._
import java.util.InputMismatchException

import scala.annotation.tailrec

object Codeforces_Scala{
  def main(args: Array[String]) {
    val scan = new FasterScanner();
    val out: PrintWriter = new PrintWriter(System.out)

    val n:Int = scan.nextInt
    val k:Int = scan.nextInt

    val segments:Array[(Int, Int)] = new Array[(Int, Int)](2*n)
    for(i <- 0 until n){
      val x:Int = i*2
      val y:Int = i*2 + 1
      segments(x) = (scan.nextInt*2,1)
      segments(y) = (scan.nextInt*2+1,-1)
    }

    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))

    val proSeg = Process(sortedSeg,0,0,k,Nil,Nil)
    out.println(proSeg.length)
    proSeg.foreach(e=>out.println(e._1+" "+e._2))
    out.flush()
    out.close()

    //Run(sortedSeg,n,k,out)
  }

  def Run(sortedSeg: Array[(Int, Int)],n:Int,k:Int,out: PrintWriter): Unit ={
    var kk: Int = 0
    var resN: Int = 0
    var i: Int = 0
    val res:Array[Int] = new Array[Int](n*2)
    while (i < 2 * n) {
      {
        kk += sortedSeg(i)._2
        if (kk >= k) {
          res(resN*2) = sortedSeg(i)._1/2
          while (kk >= k) {
            i += 1
            kk += sortedSeg(i)._2
          }
          res(resN*2+1) = (sortedSeg(i)._1-1)/2
          resN += 1
        }
      }
      i += 1
    }
    out.println(resN)
    for( i <- 0 until resN){
      out.println(res(i*2)+" "+res(i*2+1))
    }
    out.close()
  }
  //Nothing: 所有类型的子类
  //Nil: 空的List即List[Nothing]
  //Null: 引用的空值
  //None: 空的object
  @tailrec
  def Process(seg : Array[(Int, Int)], len:Int, k:Int, K:Int, p:List[Int], resList:List[(Int, Int)]) :List[(Int, Int)] = {
    if(len>=seg.length){
      resList
    }else{
      val x = seg(len)
      val kk = k+x._2
      if(kk>=K && p == Nil){
        Process(seg,len+1,kk,K,List(x._1),resList)
      }else if(kk<K && p != Nil){
        Process(seg,len+1,kk,K,Nil,resList:::List((p(0)/2,x._1/2)))
      }else{
        Process(seg,len+1,kk,K,p,resList)
      }
    }
  }

  class FasterScanner {
    private val buf: Array[Byte] = new Array[Byte](1024)
    private var curChar: Int = 0
    private var numChars: Int = 0

    def read: Int = {
      if (numChars == -1) throw new InputMismatchException
      if (curChar >= numChars) {
        curChar = 0
        try {
          numChars = System.in.read(buf)
        }
        catch {
          case e: IOException =>
            throw new InputMismatchException
        }
        if (numChars <= 0) return -1
      }
      buf({curChar += 1; curChar - 1}) //相当于buf[curChar++]
    }

    def nextLine: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isEndOfLine(c))
      res.toString
    }

    def nextString: String = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      val res: StringBuilder = new StringBuilder
      do {
        res.append(c)
        c = read
      } while (!isSpaceChar(c))
      res.toString
    }

    def nextLong: Long = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Long = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt: Int = {
      var c: Int = read
      while (isSpaceChar(c)) c = read
      var sgn: Int = 1
      if (c == '-') {
        sgn = -1
        c = read
      }
      var res: Int = 0
      do {
        if (c < '0' || c > '9') throw new InputMismatchException
        res *= 10
        res += c - '0'
        c = read
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextIntArray(n: Int): Array[Int] = {
      val arr: Array[Int] = new Array[Int](n)
      for(i <- 0 until n){
        arr(i) = nextInt
      }
      arr
    }

    def nextLongArray(n: Int): Array[Long] = {
      val arr: Array[Long] = new Array[Long](n)
      for(i <- 0 until n){
        arr(i) = nextLong
      }
      arr
    }

    private def isSpaceChar(c: Int): Boolean = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1
    }

    private def isEndOfLine(c: Int): Boolean = {
      c == '\n' || c == '\r' || c == -1
    }
  }
}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val scan = new Scanner(System.in)
    val n = scan.nextInt()
    val K = scan.nextInt()
    val segments = Input(scan,n)
    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))
    var k = 0
    var p :List[Int]= Nil
    var proSeg:List[(Int, Int)] = List()
    sortedSeg.foreach(e=>{
      k += e._2
      if(k >= K && p == Nil){
        p = List(e._1)
      }else if(k < K && p != Nil){
        proSeg = (p(0)/2,e._1/2)::proSeg
        p = Nil
      }
    })
    println(proSeg.length)
    proSeg.foreach(e=>println(e._1+" "+e._2))

  }

  def Input(scan:Scanner,n: Int) :List[(Int, Int)] = {
    if (n <= 0) {
      Nil
    } else {
      val x0 = scan.nextInt()
      val x1 = scan.nextInt()
      //x*2,x*2+1避免两个点重复
      (x0*2,1)::(x1*2+1,-1)::Input(scan,n-1)
    }
  }

}

import java.util.Scanner

import scala.annotation.tailrec

object Main {
  def main(args: Array[String]) {
    val scan = new Scanner(System.in)
    val n = scan.nextInt()
    val k = scan.nextInt()
    val segments = Input(scan,n,Nil)
    //segments.foreach(p=>println(p._1+" "+p._2))
    val sortedSeg = segments.sortBy(e=>e._1)
    //sortedSeg.foreach(p=>println(p._1/2+" "+p._2))
    if(n<10000 ){

    val proSeg = Process(sortedSeg,0,0,k,Nil,Nil)
    println(proSeg.length)
    proSeg.foreach(e=>println(e._1+" "+e._2))
    }

  }

  @tailrec
  def Input(scan:Scanner,n: Int,inList:List[(Int, Int)]) :List[(Int, Int)] = {
    if (n <= 0) {
      inList
    } else {
      val x0 = scan.nextInt()
      val x1 = scan.nextInt()
      //x*2,x*2+1避免两个点重复
      Input(scan,n-1,inList:::List((x0*2,1),(x1*2+1,-1)))
    }
  }
//Nothing: 所有类型的子类
//Nil: 空的List即List[Nothing]
//Null: 引用的空值
//None: 空的object
  @tailrec
  def Process(seg: List[(Int,Int)],l:Int,d:Int,K:Int,p:List[Int],resList:List[(Int, Int)]) :List[(Int, Int)] = {
    if(l>=seg.length){
      resList
    }else{
      val x = seg(l)
      val dd = d+x._2
      if(dd>=K && p == Nil){
        Process(seg,l+1,dd,K,List(x._1),resList)
      }else if(dd<K && p != Nil){
        Process(seg,l+1,dd,K,Nil,resList:::List((p(0)/2,x._1/2)))
      }else{
        Process(seg,l+1,dd,K,p,resList)
      }
    }
  }
}


Inna likes sweets and a game called the "Candy Matrix". Today, she came up with the new game "Candy Matrix 2: Reload".The field for the new game is a rectangle table of size n × m. Each line of the table contains one cell with a dwarf figurine, one cell with a candy, the other cells of the line are empty. The game lasts for several moves. During each move the player should choose all lines of the matrix where dwarf is not on the cell with candy and shout "Let's go!". After that, all the dwarves from the chosen lines start to simultaneously move to the right. During each second, each dwarf goes to the adjacent cell that is located to the right of its current cell. The movement continues until one of the following events occurs:  some dwarf in one of the chosen lines is located in the rightmost cell of his row;  some dwarf in the chosen lines is located in the cell with the candy. The point of the game is to transport all the dwarves to the candy cells.Inna is fabulous, as she came up with such an interesting game. But what about you? Your task is to play this game optimally well. Specifically, you should say by the given game field what minimum number of moves the player needs to reach the goal of the game.

The first line of the input contains two integers n and m (1 ≤ n ≤ 1000; 2 ≤ m ≤ 1000).  Next n lines each contain m characters — the game field for the "Candy Martix 2: Reload". Character "*" represents an empty cell of the field, character "G" represents a dwarf and character "S" represents a candy. The matrix doesn't contain other characters. It is guaranteed that each line contains exactly one character "G" and one character "S".

In a single line print a single integer — either the minimum number of moves needed to achieve the aim of the game, or -1, if the aim cannot be achieved on the given game field.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val result = (1 to n).map{ _ =>
      val str = in.next()
      val sweet = str.indexOf('S')
      val gnome = str.indexOf('G')
      if (gnome > sweet)
        -1
      else
        sweet - gnome
  }.sorted.distinct
  if (result.head == -1)
    println(-1)
  else
    println(result.length)
}

import java.util.Scanner
import scala.collection.immutable.HashSet

/**
 * Created by hama_du on 2014/02/24.
 */
object ProblemB extends App {
  val in = new Scanner(System.in)

  val n,m = in.nextInt()
  in.nextLine()
  val diffs = (0 until n).map(_ => diff(in.nextLine.toCharArray))
  if (diffs.filter(a => a < 0).size >= 1) {
    println("-1")
  } else {
    val answer = diffs.foldLeft(new HashSet[Int]())((a, b) => a + b)
    println(answer.size)
  }

  def diff(line: Array[Char]): Int = {
    val g = line.indexWhere(_ == 'G')
    val s = line.indexWhere(_ == 'S')
    s - g
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  (1 to n).foldLeft(0){
    case(-1, _) => -1
    case(acc, _) =>
      val str = in.next()
      val sweet = str.indexOf('S')
      val gnome = str.indexOf('G')
      if (gnome > sweet)
        -1
      else
        Math.max(acc, sweet - gnome)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  println((1 to n).foldLeft(0){
    case(-1, _) => -1
    case(acc, _) =>
      val str = in.next()
      val sweet = str.indexOf('S')
      val gnome = str.indexOf('G')
      if (gnome > sweet)
        -1
      else
        Math.max(acc, sweet - gnome)
  })
}


Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection. Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively. The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.

Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.

NoteIn the first sample, Kevin must pack his two cowbells into the same box. In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.In the third sample, the optimal solution is {3, 5} and {7}.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  if (k >= n)
    println(data.last)
  else {
    val d = data.dropRight(2 * k - n)
    val small = d.take(d.length / 2)
    val big = d.takeRight(d.length / 2).reverse
    val zipped = big.zip(small).map(i => i._1 + i._2).max
    if (d.length == data.length)
      println(zipped)
    else
      println(Math.max(zipped, data.last))
  }

}

import scala.collection._

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, k) = readInts(2)
  val ss = readInts(n)

  def can(s: Long): Boolean = {
    if (s < ss.last) false
    else {
      var i = 0
      var j = n - 1
      var cnt = 0
      while (i <= j) {
        if (ss(i) + ss(j) <= s && i < j) {
          cnt += 1
          i += 1
          j -= 1
        } else {
          cnt += 1
          j -= 1
        }
      }
      cnt <= k
    }
  }

  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) >>> 1
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  var res = binSearch(1, 5000000)
  println(res)
}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 15 Aug 2016
 */
object B604 extends App {

  def check(boxSize: Int, s: Array[Int], k: Int): Boolean = {
    var lastIndex = s.length
    var firstIndex = -1
    for (i <- 0 until k) {
      if (lastIndex > 0 && firstIndex < s.length-1) {
        if (s(lastIndex-1) + s(firstIndex+1) <= boxSize) {
          firstIndex += 1
        }
        lastIndex -= 1
      }
    }

    lastIndex - firstIndex <= 1
  }

  def solve() = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val Array(n, k): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    val s: Array[Int] = reader.readLine().split(" ").map(_.toInt)
    val sum = s.sum
    var lowerS = math.max(if (sum % k == 0) sum / k else sum / k + 1, s.last)
    var upperS = s.last * 2
    var found = false
    while (!found) {
      if (upperS - lowerS <= 1) {
        found = true
      } else {
        val midS = (upperS + lowerS) >> 1
        if (check(midS, s, k)) {
          upperS = midS
        } else {
          lowerS = midS
        }
      }
    }

    if (check(lowerS, s, k)) {
      println(lowerS)
    } else {
      println(upperS)
    }
    reader.close()
  }

  solve()

}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _604B extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, k) = (nextInt(), nextInt())
    val s = Seq.fill(n)(nextInt())
    val (a, b) = s splitAt (n-k)
    val (s1, s2) = a.reverse.zipAll(b, 0, 0) maxBy { case (p, q) => p + q }
    s1 + s2
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/21125
  * All next methods throw NoSuchElementException when !hasNext
  */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
    * Unlike Java's scanner which returns till end of current line, this actually returns the next line
    * @see line() if you want the Java behaviour
    */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

object B{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

    def nextInt():Int = {
        return next.toInt
    }

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val k=nextInt
    val s=for(i<-0 until n) yield nextInt
    if(n<k){
      out.println(s(n-1))
    }
    else{
      var maximum=s(n-1)
      for(i<-0 until n-k){
        if(s(i)+s(2*(n-k)-1-i)>maximum){
          maximum=s(i)+s(2*(n-k)-1-i)
        }
      }
      out.println(maximum)
    }

    //code ends here
    out.flush
    out.close
  }
}

/*
 * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/
 */

object Main extends App {
  import java.{util => ju}
  import scala.annotation._
  import scala.collection._
  import scala.collection.{mutable => mu}
  import scala.collection.JavaConverters._
  import scala.math._

  val sc = new ju.Scanner(System.in)
  val n, k = sc.nextInt
  val s = Array.fill(n)(sc.nextInt)
  val twos = 0 max (n - k)
  0 until twos foreach {i => s(i) += s(2 * twos - i - 1)}
  println(s.max)
}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 15 Aug 2016
 */
object B604 extends App {

  def check(boxSize: Int, s: Array[Int], k: Int): Boolean = {
    var lastIndex = s.length - 1
    var firstIndex = 0
    for (i <- 0 until k) {
      if (lastIndex >= 0 && firstIndex < s.length) {
        if (s(lastIndex) + s(firstIndex) <= boxSize) {
          firstIndex += 1
        }
        lastIndex -= 1
      }
    }

    lastIndex - firstIndex <= 1
  }

  def solve() = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val Array(n, k): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    val s: Array[Int] = reader.readLine().split(" ").map(_.toInt)
    val sum = s.sum
    var lowerS = math.max(if (sum % k == 0) sum / k else sum / k + 1, s.last)
    var upperS = s.last * 2
    var found = false
    while (!found) {
      if (upperS - lowerS <= 1) {
        found = true
      } else {
        val midS = (upperS + lowerS) >> 1
        if (check(midS, s, k)) {
          upperS = midS
        } else {
          lowerS = midS
        }
      }
    }

    if (check(lowerS, s, k)) {
      println(lowerS)
    } else {
      println(upperS)
    }
    reader.close()
  }

  solve()

}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 15 Aug 2016
 */
object B604 extends App {

  def check(boxSize: Int, s: Array[Int], k: Int): Boolean = {
    var lastIndex = s.length - 1
    var firstIndex = 0
    for (i <- 0 until k) {
      if (s(lastIndex) + s(firstIndex) <= boxSize) {
        firstIndex += 1
      }
      lastIndex -= 1
    }

    lastIndex - firstIndex <= 1
  }

  def solve() = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val Array(n, k): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    val s: Array[Int] = reader.readLine().split(" ").map(_.toInt)
    val sum = s.sum
    var lowerS = math.max(if (sum % k == 0) sum / k else sum / k + 1, s.last)
    var upperS = s.last * 2
    var found = false
    while (!found) {
      if (upperS - lowerS <= 1) {
        found = true
      } else {
        val midS = (upperS + lowerS) >> 1
        if (check(midS, s, k)) {
          upperS = midS
        } else {
          lowerS = midS
        }
      }
    }

    println(lowerS)
    reader.close()
  }

  solve()

}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _604B extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, k) = (nextInt(), nextInt())
    val s = Seq.fill(n)(nextInt())
    val (a, b) = s splitAt (n-k)
    val (s1, s2) = a.zipAll(b.reverse, 0, 0) maxBy { case (p, q) => p + q }
    s1 + s2
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
  * Scala implementation of a faster java.util.Scanner
  * See: http://codeforces.com/blog/entry/21125
  * All next methods throw NoSuchElementException when !hasNext
  */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
    * Unlike Java's scanner which returns till end of current line, this actually returns the next line
    * @see line() if you want the Java behaviour
    */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._, control._
import scala.math.Ordering.Implicits._

object _604B extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, k) = (nextInt(), nextInt())
    val s = Seq.fill(n)(nextInt())
    val (a, b) = s splitAt (n-k)
    val (s1, s2) = a.zipAll(b, 0, 0) maxBy { case (p, q) => p + q }
    s1 + s2
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}


Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at least ai any pieces of information from the other computers. Doc can hack the computer only if he is right next to it.The robot is assembled using modern technologies and can move along the line of computers in either of the two possible directions, but the change of direction requires a large amount of resources from Doc. Tell the minimum number of changes of direction, which the robot will have to make to collect all n parts of information if initially it is next to computer with number 1.It is guaranteed that there exists at least one sequence of the robot's actions, which leads to the collection of all information. Initially Doc doesn't have any pieces of information.

The first line contains number n (1 ≤ n ≤ 1000). The second line contains n non-negative integers a1, a2, ..., an (0 ≤ ai < n), separated by a space. It is guaranteed that there exists a way for robot to collect all pieces of the information.

Print a single number — the minimum number of changes in direction that the robot will have to make in order to collect all n parts of information.

NoteIn the first sample you can assemble all the pieces of information in the optimal manner by assembling first the piece of information in the first computer, then in the third one, then change direction and move to the second one, and then, having 2 pieces of information, collect the last piece.In the second sample to collect all the pieces of information in the optimal manner, Doc can go to the fourth computer and get the piece of information, then go to the fifth computer with one piece and get another one, then go to the second computer in the same manner, then to the third one and finally, to the first one. Changes of direction will take place before moving from the fifth to the second computer, then from the second to the third computer, then from the third to the first computer.In the third sample the optimal order of collecting parts from computers can look like that: 1->3->4->6->2->5->7.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val visited = Array.ofDim[Boolean](n)
  var gathered = 0
  var position = 0
  var changes = 0
  var right = true
  while (gathered != n) {
    if (position < 0) {
      right = true
      position = 0
      changes += 1
    } else if (position > n - 1) {
      right = false
      position = n - 1
      changes += 1
    }

    if (!visited(position) && data(position) <= gathered) {
      gathered += 1
      visited(position) = true
    }
    if (right)
      position += 1
    else
      position -= 1
  }

  println(changes)
}

object B583 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    var res = 0
    var dir = +1
    var sec = 0
    while(in.exists(_ != -1)) {
      val range = if(dir == 1) 0 until n else n-1 to 0 by -1
      for(i <- range){
        if(in(i) != -1 && in(i) <= sec) {
          sec += 1
          in(i) = -1
        }
      }
      if(dir == +1) dir = -1 else dir = +1
      if(in.exists(_ != -1))
        res += 1
    }

    println(res)
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInts(n: Int): Array[Int] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toInt)
    }

    def readLongs(n: Int): Array[Long] = {
      val tl = tokenizeLine;
      Array.fill(n)(tl.nextToken.toLong)
    }

    def readBigs(n: Int): Array[BigInt] = {
      val tl = tokenizeLine;
      Array.fill(n)(BigInt(tl.nextToken))
    }
  }

}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _583B extends CodeForcesApp[Int]({scanner => import scanner._
  val n = nextInt
  val computers = IndexedSeq.fill(n)(nextInt)
  val (left, right) = (true, false)
  var ans = 0
  var hacked = bag[Int]

  @tailrec
  def move(pos: Int, dir: Boolean): Int = (pos, dir) match {
    case _ if hacked.size == n => ans

    case (`n`, `right`) =>
      ans += 1
      move(n-1, left)

    case (-1, `left`) =>
      ans += 1
      move(0, right)

    case _ =>
      if(computers(pos) <= hacked.size) {
        hacked += pos
      }
      move(pos + (if (dir == right) 1 else -1), dir)
  }

  move(0, right)
}) {
  override def format(result: Result) = super.format(result)
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

import scala.io.StdIn._

object B extends App {
  val n = readInt()
  val A = readLine().split(" ").map(_.toInt)
  val V = Array.ofDim[Boolean](A.length + 1)

  var power = 0
  var changeDir = -1
  while (power < A.length) {
    changeDir += 1
    for (i <- 0 until A.length) {
      if (!V(i) && A(i) <= power) {
        power += 1
        V(i) = true
      }
    }

    if (power < A.length) {
      changeDir += 1
      for (i <- A.length - 1 to 0 by -1) {
        if (!V(i) && A(i) <= power) {
          power += 1
          V(i) = true
        }
      }
    }
  }

  println(changeDir)
}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object B_Robots {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(t25.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val line2 = br.readLine().split(" ")
    var comps = line2.map(_.toInt)
    var compsColl = Array.fill(number)(false)
    //---------------------------- parameters reading end --------------------------------

    var collected = 0
    var pointer = 0
    var previousRigh = true
    var turns = 0
    while (collected != number) {
      val r = lookRight()
      val l = lookLeft
      var toProcess = List[Int]()
      if (r.size > l.size) {
        toProcess = r
        if (!previousRigh) turns += 1
        previousRigh = true
      } else if (l.size > r.size) {
        toProcess = l
        if (previousRigh) turns += 1
        previousRigh = false
      } else {
        if (previousRigh) {
          toProcess = r
        } else {
          toProcess = l
        }
      }
      pointer = toProcess.head
      collected += toProcess.size
      toProcess.foreach { x => compsColl(x) = true }

    }
    println(turns)

    def lookRight():List[Int] = {
      var res = List[Int]();
      var couldBe = collected
      for(i<-pointer until number) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

    def lookLeft():List[Int] = {
      var res = List[Int]();
      var couldBe = collected
      var i = pointer
      while (i >= 0) {
         if (comps(i) <= couldBe && !compsColl(i)) {
          res ::= i
          couldBe += 1
        }
         i -= 1
      }
      return res
    }

  }
}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object B_Robots {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val line2 = br.readLine().split(" ")
    var comps = line2.map(_.toInt)
    var compsColl = Array.fill(number)(false)
    //---------------------------- parameters reading end --------------------------------

    var collected = 0
    var pointer = 0
    var previousRigh = true
    var turns = 0
    var rightFirst = -1
    var leftFirst = -1
    while (collected != number) {
      val r = lookRight()
      val l = lookLeft
      var toProcess = List[Int]()
      if (r.size > l.size) {
        toProcess = r
        if (!previousRigh) turns += 1
        previousRigh = true
        pointer = r.head
      } else if (l.size > r.size) {
        toProcess = l
        if (previousRigh) turns += 1
        previousRigh = false
        pointer = l.last
      } else {
        if (previousRigh) {
          toProcess = r
        } else {
          toProcess = l
        }
      }
      collected += toProcess.size
      toProcess.foreach { x => compsColl(x) = true }

    }
    println(turns)

    def lookRight():List[Int] = {
      var res = List[Int]();
      rightFirst = -1
      var couldBe = collected
      for(i<-pointer until number) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          if (rightFirst == -1) rightFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

    def lookLeft():List[Int] = {
      var res = List[Int]();
      leftFirst = -1
      var couldBe = collected
      for(i<-0 to pointer) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          if (leftFirst == -1) leftFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object B_Robots {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val line2 = br.readLine().split(" ")
    var comps = line2.map(_.toInt)
    var compsColl = Array.fill(number)(false)
    //---------------------------- parameters reading end --------------------------------

    var collected = 0
    var pointer = 0
    var previousRigh = true
    var turns = 0
    var rightFirst = -1
    var leftFirst = -1
    while (collected != number) {
      val r = lookRight()
      val l = lookLeft
      var toProcess = List[Int]()
      if (r.size > l.size) {
        toProcess = r
        if (!previousRigh) turns += 1
        previousRigh = true
      } else {
        toProcess = l
        if (previousRigh) turns += 1
        previousRigh = false
      }
      pointer = toProcess.head
      collected += toProcess.size
      toProcess.foreach { x => compsColl(x) = true }

    }
    println(turns)

    def lookRight():List[Int] = {
      var res = List[Int]();
      rightFirst = -1
      var couldBe = collected
      for(i<-pointer until number) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          if (rightFirst == -1) rightFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

    def lookLeft():List[Int] = {
      var res = List[Int]();
      leftFirst = -1
      var couldBe = collected
      for(i<-0 to pointer) {
        if (comps(i) <= collected && !compsColl(i)) {
          if (leftFirst == -1) leftFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object B_Robots {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val line2 = br.readLine().split(" ")
    var comps = line2.map(_.toInt)
    var compsColl = Array.fill(number)(false)
    //---------------------------- parameters reading end --------------------------------

    var collected = 0
    var pointer = 0
    var previousRigh = true
    var turns = 0
    var rightFirst = -1
    var leftFirst = -1
    while (collected != number) {
      val r = lookRight()
      val l = lookLeft
      var toProcess = List[Int]()
      if (r.size > l.size) {
        toProcess = r
        if (!previousRigh) turns += 1
        previousRigh = true
        pointer = r.head
      } else if (l.size > r.size) {
        toProcess = l
        if (previousRigh) turns += 1
        previousRigh = false
        pointer = l.last
      } else {
        if (previousRigh) {
          toProcess = r
        } else {
          toProcess = l
        }
      }
      collected += toProcess.size
      toProcess.foreach { x => compsColl(x) = true }

    }
    println(turns)

    def lookRight():List[Int] = {
      var res = List[Int]();
      rightFirst = -1
      var couldBe = collected
      for(i<-pointer until number) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          if (rightFirst == -1) rightFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

    def lookLeft():List[Int] = {
      var res = List[Int]();
      leftFirst = -1
      var couldBe = collected
      for(i<- pointer to 0 by -1) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          if (leftFirst == -1) leftFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object B_Robots {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val line2 = br.readLine().split(" ")
    var comps = line2.map(_.toInt)
    var compsColl = Array.fill(number)(false)
    //---------------------------- parameters reading end --------------------------------

    var collected = 0
    var pointer = 0
    var previousRigh = true
    var turns = 0
//    var rightFirst = -1
//    var leftFirst = -1
    while (collected != number) {
      val r = lookRight()
      val l = lookLeft
      var toProcess = List[Int]()
      if (r.size > l.size) {
        toProcess = r
        if (!previousRigh) turns += 1
        previousRigh = true
        pointer = r.head
      } else if (l.size > r.size) {
        toProcess = l
        if (previousRigh) turns += 1
        previousRigh = false
        pointer = l.last
      } else {
        if (previousRigh) {
          toProcess = r
        } else {
          toProcess = l
        }
      }
      collected += toProcess.size
      toProcess.foreach { x => compsColl(x) = true }

    }
    println(turns)

    def lookRight():List[Int] = {
      var res = List[Int]();
//      rightFirst = -1
      var couldBe = collected
      for(i<-pointer until number) {
        if (comps(i) <= collected && !compsColl(i)) {
//          if (rightFirst == -1) rightFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

    def lookLeft():List[Int] = {
      var res = List[Int]();
//      leftFirst = -1
      var couldBe = collected
      var i = pointer
      while (i >= 0) {
         if (comps(i) <= collected && !compsColl(i)) {
          res ::= i
          couldBe += 1
        }
         i -= 1
      }
//      for(i<- pointer to 0 by -1) {
//        if (comps(i) <= couldBe && !compsColl(i)) {
////          if (leftFirst == -1) leftFirst = i
//          res ::= i
//          couldBe += 1
//        }
//      }
      return res
    }

  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object B_Robots {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val line2 = br.readLine().split(" ")
    var comps = line2.map(_.toInt)
    var compsColl = Array.fill(number)(false)
    //---------------------------- parameters reading end --------------------------------

    var collected = 0
    var pointer = 0
    var previousRigh = true
    var turns = 0
    var rightFirst = -1
    var leftFirst = -1
    while (collected != number) {
      val r = lookRight()
      val l = lookLeft
      var toProcess = List[Int]()
      if (r.size > l.size) {
        toProcess = r
        if (!previousRigh) turns += 1
        previousRigh = true
      } else if (l.size > r.size) {
        toProcess = l
        if (previousRigh) turns += 1
        previousRigh = false
      } else {
        if (previousRigh) {
          toProcess = r
        } else {
          toProcess = l
        }
      }
      pointer = toProcess.head
      collected += toProcess.size
      toProcess.foreach { x => compsColl(x) = true }

    }
    println(turns)

    def lookRight():List[Int] = {
      var res = List[Int]();
      rightFirst = -1
      var couldBe = collected
      for(i<-pointer until number) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          if (rightFirst == -1) rightFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

    def lookLeft():List[Int] = {
      var res = List[Int]();
      leftFirst = -1
      var couldBe = collected
      for(i<-0 to pointer) {
        if (comps(i) <= collected && !compsColl(i)) {
          if (leftFirst == -1) leftFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

  }

}

import java.io._
import java.util.ArrayList
import java.util.StringTokenizer

object B_Robots {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val number = line1.nextToken().toInt

    val line2 = br.readLine().split(" ")
    var comps = line2.map(_.toInt)
    var compsColl = Array.fill(number)(false)
    //---------------------------- parameters reading end --------------------------------

    var collected = 0
    var pointer = 0
    var previousRigh = true
    var turns = 0
    var rightFirst = -1
    var leftFirst = -1
    while (collected != number) {
      val r = lookRight()
      val l = lookLeft
      var toProcess = List[Int]()
      if (r.size > l.size) {
        toProcess = r
        if (!previousRigh) turns += 1
        previousRigh = true
        pointer = r.head
      } else if (l.size > r.size) {
        toProcess = l
        if (previousRigh) turns += 1
        previousRigh = false
        pointer = l.last
      } else {
        if (previousRigh) {
          toProcess = r
        } else {
          toProcess = l
        }
      }
      collected += toProcess.size
      toProcess.foreach { x => compsColl(x) = true }

    }
    println(turns)

    def lookRight():List[Int] = {
      var res = List[Int]();
      rightFirst = -1
      var couldBe = collected
      for(i<-pointer until number) {
        if (comps(i) <= couldBe && !compsColl(i)) {
          if (rightFirst == -1) rightFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

    def lookLeft():List[Int] = {
      var res = List[Int]();
      leftFirst = -1
      var couldBe = collected
      for(i<-0 to pointer) {
        if (comps(i) <= collected && !compsColl(i)) {
          if (leftFirst == -1) leftFirst = i
          res ::= i
          couldBe += 1
        }
      }
      return res
    }

  }

}


You have an $$$n \times n$$$ chessboard and $$$k$$$ rooks. Rows of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from top to bottom and columns of this chessboard are numbered by integers from $$$1$$$ to $$$n$$$ from left to right. The cell $$$(x, y)$$$ is the cell on the intersection of row $$$x$$$ and collumn $$$y$$$ for $$$1 \leq x \leq n$$$ and $$$1 \leq y \leq n$$$.The arrangement of rooks on this board is called good, if no rook is beaten by another rook.A rook beats all the rooks that shares the same row or collumn with it.The good arrangement of rooks on this board is called not stable, if it is possible to move one rook to the adjacent cell so arrangement becomes not good. Otherwise, the good arrangement is stable. Here, adjacent cells are the cells that share a side.  Such arrangement of $$$3$$$ rooks on the $$$4 \times 4$$$ chessboard is good, but it is not stable: the rook from $$$(1, 1)$$$ can be moved to the adjacent cell $$$(2, 1)$$$ and rooks on cells $$$(2, 1)$$$ and $$$(2, 4)$$$ will beat each other. Please, find any stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard or report that there is no such arrangement.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$k$$$ ($$$1 \leq k \leq n \leq 40$$$) — the size of the chessboard and the number of rooks.

If there is a stable arrangement of $$$k$$$ rooks on the $$$n \times n$$$ chessboard, output $$$n$$$ lines of symbols . and R. The $$$j$$$-th symbol of the $$$i$$$-th line should be equals R if and only if there is a rook on the cell $$$(i, j)$$$ in your arrangement. If there are multiple solutions, you may output any of them. If there is no stable arrangement, output $$$-1$$$.

NoteIn the first test case, you should find stable arrangement of $$$2$$$ rooks on the $$$3 \times 3$$$ chessboard. Placing them in cells $$$(3, 1)$$$ and $$$(1, 3)$$$ gives stable arrangement.In the second test case it can be shown that it is impossbile to place $$$3$$$ rooks on the $$$3 \times 3$$$ chessboard to get stable arrangement.

object A extends App {

  sealed trait Row {
    def size: Int
  }
  final case class Empty(size: Int)           extends Row {
    override def toString(): String = "." * size
  }
  final case class Rook(size: Int, rook: Int) extends Row {
    override def toString(): String = "." * rook + "R" + "." * (size - rook - 1)
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextInt()
    val k = nextInt()

    val m = 2 * (k - 1) + 1

    if (n >= m)
      (0 until n).foldLeft(k) {
        case (rooks, row) if row % 2 == 0 && rooks > 0 =>
          out.println(Rook(n, row))
          rooks - 1
        case (rooks, _) =>
          out.println(Empty(n))
          rooks
      }
    else
      out.println(-1)
  }
  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object A extends App {
  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextInt()
    val k = nextInt()

    val m = 2 * (k - 1) + 1

    if (n >= m)
      (0 until n).foldLeft(k) {
        case (rooks, row) if row % 2 == 0 && rooks > 0 =>
          val line = (0 until n).map {
            case column if row == column => 'R'
            case _                       => '.'
          }.mkString("")
          out.println(line)
          rooks - 1
        case (rooks, _) =>
          out.println("." * n)
          rooks
      }
    else
      out.println(-1)
  }
  out.flush()

  object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    private[this] def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}


There is a rectangular grid of size $$$n \times m$$$. Each cell has a number written on it; the number on the cell ($$$i, j$$$) is $$$a_{i, j}$$$. Your task is to calculate the number of paths from the upper-left cell ($$$1, 1$$$) to the bottom-right cell ($$$n, m$$$) meeting the following constraints:  You can move to the right or to the bottom only. Formally, from the cell ($$$i, j$$$) you may move to the cell ($$$i, j + 1$$$) or to the cell ($$$i + 1, j$$$). The target cell can't be outside of the grid.  The xor of all the numbers on the path from the cell ($$$1, 1$$$) to the cell ($$$n, m$$$) must be equal to $$$k$$$ (xor operation is the bitwise exclusive OR, it is represented as '^' in Java or C++ and "xor" in Pascal). Find the number of such paths in the given grid.

The first line of the input contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n, m \le 20$$$, $$$0 \le k \le 10^{18}$$$) — the height and the width of the grid, and the number $$$k$$$. The next $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line is $$$a_{i, j}$$$ ($$$0 \le a_{i, j} \le 10^{18}$$$).

Print one integer — the number of paths from ($$$1, 1$$$) to ($$$n, m$$$) with xor sum equal to $$$k$$$.

NoteAll the paths from the first example:   $$$(1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3)$$$;  $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3)$$$;  $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3)$$$. All the paths from the second example:   $$$(1, 1) \rightarrow (2, 1) \rightarrow (3, 1) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (3, 2) \rightarrow (3, 3) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (2, 1) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (2, 4) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4)$$$;  $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3) \rightarrow (3, 3) \rightarrow (3, 4)$$$.

import scala.collection.mutable

/*

link- http://codeforces.com/problemset/problem/1006/F

There is a rectangular grid of size n×m. Each cell has a number written on it; the number on the cell (i,j) is a(i,j).
Your task is to calculate the number of paths from the upper-left cell (1,1) to the bottom-right cell (n,m) meeting the
following constraints:

You can move to the right or to the bottom only. Formally, from the cell (i,j) you may move to the
cell (i,j+1) or to the cell (i+1,j). The target cell can't be outside of the grid. The xor of all the numbers on the path
from the cell (1,1) to the cell (n,m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented
as '^' in Java or C++ and "xor" in Pascal).Find the number of such paths in the given grid.InputThe first line of the
input contains three integers n, m and k (1≤n,m≤20, 0≤k≤1018) — the height and the width of the grid, and the number k.

The next n lines contain m integers each, the j-th element in the i-th line is ai,j (0≤ai,j≤1018). OutputPrint one integer-
the number of paths from (1,1) to (n,m) with xor sum equal to k.

Meet in the Middle

 */
object XorPaths {

  def main(args: Array[String]): Unit = {

    var arr = io.StdIn.readLine.split(" ").map(_.toLong)
    val n = arr(0).toInt
    val m = arr(1).toInt
    val k = arr(2)

    val source = Array.ofDim[Long](n, m)
    for (i <- 0 until n) io.StdIn.readLine.split(" ").map(_.toLong).zipWithIndex.foreach { case (x, j) => source(i)(j) = x }

    def recurForward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Unit = {
      if (depth == 1) {
        val res = xor ^ source(x)(y)
        val count: mutable.Map[Long, Int] = middle.getOrElseUpdate((x, y), collection.mutable.Map[Long, Int]())
        count(res) = count.getOrElse(res, 0) + 1

      } else {
        if (x + 1 < n) {
          recurForward(x + 1, y, xor ^ source(x)(y), depth - 1)
        }
        if (y + 1 < m) {
          recurForward(x, y + 1, xor ^ source(x)(y), depth - 1)
        }
      }
    }

    def recurBackward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Long = {
      if (depth == 1) middle.getOrElse((x, y), collection.mutable.Map[Long, Int]()).getOrElse(xor ^ k, 0).toLong
      else {
        var ans: Long = 0
        if (x - 1 >= 0) {
          ans += recurBackward(x - 1, y, xor ^ source(x)(y), depth - 1)
        }
        if (y - 1 >= 0) {
          ans += recurBackward(x, y - 1, xor ^ source(x)(y), depth - 1)
        }

        ans
      }
    }

    implicit val middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]] = collection.mutable.Map[(Int, Int), collection.mutable.Map[Long, Int]]()
    val depth = (n + m) >> 1

    recurForward(0, 0, 0, depth)
    println(recurBackward(n - 1, m - 1, 0, n + m - depth))
  }
}

import scala.collection.mutable

/*

link- http://codeforces.com/problemset/problem/1006/F

There is a rectangular grid of size n×m. Each cell has a number written on it; the number on the cell (i,j) is a(i,j).
Your task is to calculate the number of paths from the upper-left cell (1,1) to the bottom-right cell (n,m) meeting the
following constraints:

You can move to the right or to the bottom only. Formally, from the cell (i,j) you may move to the
cell (i,j+1) or to the cell (i+1,j). The target cell can't be outside of the grid. The xor of all the numbers on the path
from the cell (1,1) to the cell (n,m) must be equal to k (xor operation is the bitwise exclusive OR, it is represented
as '^' in Java or C++ and "xor" in Pascal).Find the number of such paths in the given grid.InputThe first line of the
input contains three integers n, m and k (1≤n,m≤20, 0≤k≤1018) — the height and the width of the grid, and the number k.

The next n lines contain m integers each, the j-th element in the i-th line is ai,j (0≤ai,j≤1018). OutputPrint one integer-
the number of paths from (1,1) to (n,m) with xor sum equal to k.

Meet in the Middle

 */
object XorPaths {

  def main(args: Array[String]): Unit = {

    var arr = io.StdIn.readLine.split(" ").map(_.toLong)
    val n = arr(0).toInt
    val m = arr(1).toInt
    val k = arr(2)

    val source = Array.ofDim[Long](n, m)
    for (i <- 0 until n) io.StdIn.readLine.split(" ").map(_.toLong).zipWithIndex.foreach { case (x, j) => source(i)(j) = x }

    def recurForward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Unit = {
      if (depth == 1) {
        val res = xor ^ source(x)(y)
        val count: mutable.Map[Long, Int] = middle.getOrElseUpdate((x, y), collection.mutable.Map[Long, Int]())
        count(res) = count.getOrElse(res, 0) + 1

      } else {
        if (x + 1 < n) {
          recurForward(x + 1, y, xor ^ source(x)(y), depth - 1)
        }
        if (y + 1 < m) {
          recurForward(x, y + 1, xor ^ source(x)(y), depth - 1)
        }
      }
    }

    def recurBackward(x: Int, y: Int, xor: Long, depth: Int)(implicit middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]]): Int = {
      if (depth == 1) middle.getOrElse((x, y), collection.mutable.Map[Long, Int]()).getOrElse(xor ^ k, 0)
      else {
        var ans = 0
        if (x - 1 >= 0) {
          ans += recurBackward(x - 1, y, xor ^ source(x)(y), depth - 1)
        }
        if (y - 1 >= 0) {
          ans += recurBackward(x, y - 1, xor ^ source(x)(y), depth - 1)
        }

        ans
      }
    }

    implicit val middle: mutable.Map[(Int, Int), mutable.Map[Long, Int]] = collection.mutable.Map[(Int, Int), collection.mutable.Map[Long, Int]]()
    val depth = (n + m) >> 1

    recurForward(0, 0, 0, depth)
    println(recurBackward(n - 1, m - 1, 0, n + m - depth))
  }
}


Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apartment has three windows, a five-room — five windows, and a seven-room — seven windows.Monocarp went around the building and counted $$$n$$$ windows. Now he is wondering, how many apartments of each type the building may have.Unfortunately, Monocarp only recently has learned to count, so he is asking you to help him to calculate the possible quantities of three-room, five-room, and seven-room apartments in the building that has $$$n$$$ windows. If there are multiple answers, you can print any of them.Here are some examples:  if Monocarp has counted $$$30$$$ windows, there could have been $$$2$$$ three-room apartments, $$$2$$$ five-room apartments and $$$2$$$ seven-room apartments, since $$$2 \cdot 3 + 2 \cdot 5 + 2 \cdot 7 = 30$$$;  if Monocarp has counted $$$67$$$ windows, there could have been $$$7$$$ three-room apartments, $$$5$$$ five-room apartments and $$$3$$$ seven-room apartments, since $$$7 \cdot 3 + 5 \cdot 5 + 3 \cdot 7 = 67$$$;  if Monocarp has counted $$$4$$$ windows, he should have mistaken since no building with the aforementioned layout can have $$$4$$$ windows.

Th first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of windows in the building.

For each test case, if a building with the new layout and the given number of windows just can't exist, print $$$-1$$$. Otherwise, print three non-negative integers — the possible number of three-room, five-room, and seven-room apartments. If there are multiple answers, print any of them.

import scala.io.Source

object task extends App {
  for (ws <- Source.stdin.getLines().drop(1).map(_.toInt)) {
    var found: Boolean = false;
    var result: String = "-1";
    var w3: Int = 0
    var w5: Int = 0
    var w7: Int = 0

    while ((w3 <= ws / 3) && !found) {
      w5 = 0
      while ((w5 <= ws / 5) && !found) {
        w7 = 0
        while (w7 <= ws / 7 && !found) {
          if (w3 * 3 + w5 * 5 + w7 * 7 == ws) {
            found = true;
            result = s"$w3 $w5 $w7"
          }
          w7 += 1
        }
        w5 += 1
      }
      w3 += 1
    }
    println(result)
  }
}

object A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val (a, b, c) = n % 3 match {
        case 0 =>
          (n / 3, 0, 0)
        case 1 =>
          (n / 3 - 2, 0, 1)
        case 2 =>
          (n / 3 - 1, 1, 0)
      }

      if (a >= 0) out.println(s"$a $b $c")
      else out.println(-1)
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

object A extends App {
  import scala.io.StdIn._

  (0 until readInt()).foreach { _ =>
    val n = readInt()

    val (i, j, k) = n % 3 match {
      case 0 => (n / 3, 0, 0)
      case 1 => (n / 3 - 2, 0, 1) // n = 3 * i + 1 = 3 * (i - 2) + 7
      case 2 => (n / 3 - 1, 1, 0) // n = 3 * i + 2 = 3 * (i - 1) + 5
    }

    if (i < 0) println(-1)
    else println(s"$i $j $k")
  }
}


Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres.In the bookshop, Jack decides to buy two books of different genres.Based on the genre of books on sale in the shop, find the number of options available to Jack for choosing two books of different genres for Emily. Options are considered different if they differ in at least one book.The books are given by indices of their genres. The genres are numbered from 1 to m.

The first line contains two positive integers n and m (2 ≤ n ≤ 2·105, 2 ≤ m ≤ 10) — the number of books in the bookstore and the number of genres. The second line contains a sequence a1, a2, ..., an, where ai (1 ≤ ai ≤ m) equals the genre of the i-th book. It is guaranteed that for each genre there is at least one book of that genre.

Print the only integer — the number of ways in which Jack can choose books. It is guaranteed that the answer doesn't exceed the value 2·109.

NoteThe answer to the first test sample equals 5 as Sasha can choose:  the first and second books,  the first and third books,  the first and fourth books,  the second and third books,  the third and fourth books.

import java.util.Scanner
import java.lang.System

import scala.io.StdIn
import scala.math.pow
import scala.collection.mutable._

object Main {
  implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }

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

    val (n, m) = (scanner.nextInt(), scanner.nextInt())
    val array = Array.fill[Int](m)(0)

    (1 to n).foreach { i =>
      array(scanner.nextInt() - 1) += 1
    }

    var total: Int = 0

    (0 to m - 2).foreach { i =>
      (i + 1 to m - 1).foreach { k =>
        total += array(i) * array(k)
      }
    }

    println(total)
  }
}

import scala.io.StdIn
import scala.math.pow
import scala.collection.mutable._

object Main {
  implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }

  def main(args: Array[String]): Unit = {
    val inputs = readLine.split(' ').map(_.toInt)
    val (n, m) = (inputs(0), inputs(1))

    val books = readLine.split(' ').map(_.toInt)
    val counts = books.groupBy(identity).mapValues(_.size).values.toArray

    var total: Int = 0

    (0 to counts.size - 2).foreach { i =>
      (i + 1 to counts.size - 1).foreach { k =>
        total += counts(i) * counts(k)
      }
    }

    println(total)
  }
}

import scala.io.StdIn
import scala.math.pow
import scala.collection.mutable._

object Main {
  implicit def bool2int(b: Boolean): Int = { if(b) 1 else 0 }

  def main(args: Array[String]): Unit = {
    val inputs = readLine.split(' ').map(_.toInt)
    val (n, m) = (inputs(0), inputs(1))

    val counts = readLine.split(' ').map(_.toInt).groupBy(identity).mapValues(_.size).values.toArray

    var total: Int = 0

    (0 to counts.size - 2).foreach { i =>
      (i + 1 to counts.size - 1).foreach { k =>
        total += counts(i) * counts(k)
      }
    }

    println(total)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val arr = Array.ofDim[Int](m)
  in.next().split(' ').map(_.toInt - 1).foreach(i => arr(i) += 1)
  val count = arr.sum
  println(arr.foldLeft(0l) {
    case(sum, typeCount) => sum + typeCount * (count - typeCount)
  } / 2)
}

import java.util.Scanner

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

    val bookCount = next
    val genreCount = next
    val bookGenres = 0.until(bookCount).map(_ => next - 1)

    println(countOptions(genreCount, bookGenres))
  }

  def countOptions(genreCount: Int, bookGenres: IndexedSeq[Int]): Int = {
    val byGenre = new Array[Int](genreCount)
    for (genre <- bookGenres) {
      byGenre(genre) += 1
    }

    var result = 0
    for (bigger <- 1.until(genreCount)) {
      for (smaller <- 0.until(bigger)) {
        result += byGenre(smaller) * byGenre(bigger)
      }
    }

    result
  }
}

/*
 * Reference: http://lizan.asia/blog/2012/12/11/scala-competitive/
 */

object Main extends App {
  import java.{util => ju}
  import scala.annotation._
  import scala.collection._
  import scala.collection.{mutable => mu}
  import scala.collection.JavaConverters._
  import scala.math._

  val sc = new ju.Scanner(System.in)
  val n, m = sc.nextInt
  val nl: Long = n
  val g = Array.fill(n)(sc.nextInt)
  val acc = (1 to m).map(i => g.count(_ == i).asInstanceOf[Long]).map(x => x * (x - 1) / 2).sum
  println(nl * (nl - 1) / 2 - acc)
}


As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it...

The first and only line of input contains a single nonempty string s of length at most 1000 composed of lowercase letters (a-z).

Output YES if the string s contains heidi as a subsequence and NO otherwise.

NoteA string s contains another string p as a subsequence if it is possible to delete some characters from s and obtain p.

import java.util.StringTokenizer

object G extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  val s = readLine()

  val heidi = "heidi"

  var i = 0
  var j = 0
  while ((i < s.length) && (j < heidi.length)) {
    if (s(i) == heidi(j)) j += 1
    i += 1
  }

  if (j == heidi.length) println("YES") else println("NO")
}