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


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


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

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

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

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


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

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

  }

}


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


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

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

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


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

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

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


import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val in = new Scanner(System.in)
    val n = in.nextInt
    val a = new Array[Int](n)
    for (i <- 0 to n - 1)
      a(i) = in.nextInt

    val x = new Array[Int](n + 1)
    val y = new Array[Int](n + 1)
    x(0) = 0
    y(0) = 0
    for (i <- 1 to n) {
      x(i) = x(i - 1) + a(i - 1)
      y(i) = y(i - 1) + (if (i % 2 == 0) -1 else 1) * a(i - 1)
    }

    var minY = 0;
    var maxY = 0;
    for (i <- 0 to n) {
      minY = Math.min(minY, y(i))
      maxY = Math.max(maxY, y(i))
    }

    val ans = new Array[Array[Char]](maxY - minY)
    for (i <- 0 to maxY - minY - 1) {
      ans(i) = new Array[Char](x(n))
      for (j <- 0 to ans(i).length - 1)
        ans(i)(j) = ' '
    }

    var curj = 0
    for (i <- 0 to n - 1) {
      if (y(i) < y(i + 1)) {
        val c = '/';
        for (j <- y(i) to y(i + 1) - 1) {
          ans(j - minY)(curj) = c
          curj = curj + 1
        }
      } else {
        val c = '\\';
        var curi = y(i) - 1
        for (j <- y(i + 1) to y(i) - 1) {
          ans(curi - minY)(curj) = c
          curj = curj + 1
          curi = curi - 1
        }
      }
    }

    for (i <- 0 to maxY - minY - 1) {
      println(ans(maxY - minY - 1 - i).mkString)
    }

  }
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object C extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  var y, minY, maxY = 0
  for (i <- as.indices) {
    if (i % 2 == 0) y += as(i) else y -= as(i)
    minY = minY min y
    maxY = maxY max y
  }

  val res = Array.fill(maxY - minY, as.sum)(' ')

  y = 0
  var x = 0
  for (i <- as.indices) {
    for (j <- 0 until as(i)) {
      if (i % 2 == 0) y += 1 else y -= 1
      res(maxY - y)(x) = if (i % 2 == 0) '/' else '\\'
      x += 1
    }
    if (i % 2 == 0) y += 1 else y -= 1
  }

  res.foreach { s => println(s.mkString) }
}

import java.util.Scanner

object Main {
  def main(args: Array[String]) {
    val in = new Scanner(System.in)
    val n = in.nextInt
    val a = new Array[Int](n)
    for (i <- 0 to n - 1)
      a(i) = in.nextInt

    val x = new Array[Int](n + 1)
    val y = new Array[Int](n + 1)
    x(0) = 0
    y(0) = 0
    for (i <- 1 to n) {
      x(i) = x(i - 1) + a(i - 1)
      y(i) = y(i - 1) + (if (i % 2 == 0) -1 else 1) * a(i - 1)

      println(x(i) + " " + y(i))
    }

    var minY = 0;
    var maxY = 0;
    for (i <- 0 to n) {
      minY = Math.min(minY, y(i))
      maxY = Math.max(maxY, y(i))
    }

    val ans = new Array[Array[Char]](maxY - minY)
    for (i <- 0 to maxY - minY - 1) {
      ans(i) = new Array[Char](x(n))
      for (j <- 0 to ans(i).length - 1)
        ans(i)(j) = ' '
    }

    var curj = 0
    for (i <- 0 to n - 1) {
      if (y(i) < y(i + 1)) {
        val c = '/';
        for (j <- y(i) to y(i + 1) - 1) {
          ans(j - minY)(curj) = c
          curj = curj + 1
        }
      } else {
        val c = '\\';
        var curi = y(i) - 1
        for (j <- y(i + 1) to y(i) - 1) {
          ans(curi - minY)(curj) = c
          curj = curj + 1
          curi = curi - 1
        }
      }
    }

    for (i <- 0 to maxY - minY - 1) {
      for (j <- 0 to ans(i).length - 1)
        print(ans(maxY - minY - 1 - i)(j))
      println
    }

  }
}


object D459 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val arr = readInts(n)

    val map = cu.Map.empty[Int, Int].withDefaultValue(0)
    val left = new Array[Int](n)
    val right = new Array[Int](n)
    for(i <- 0 until n) {
      left(i) = map(arr(i))
      map(arr(i)) += 1
    }
    map.clear()
    for(i <- n-1 to 0 by -1) {
      right(i) = map(arr(i))
      map(arr(i)) += 1
    }

    var ret = 0L
    val fenwickTree = new FenwickTree(n+10)
    for(i <- n-1 to 0 by -1) {
      ret += fenwickTree.get(left(i))
      fenwickTree.add(right(i)+1, 1)
    }
    out.println(ret)

    out.close()
  }

  class FenwickTree(n: Int) {
    private val sum = new Array[Int](n+1)
    def get(r: Int): Int = {
      var idx = r
      var ret = 0
      while(idx > 0) {
        ret += sum(idx)
        idx -= Integer.lowestOneBit(idx)
      }
      ret
    }
    def add(r: Int, value: Int) {
      var idx = r
      while(idx <= n) {
        sum(idx) += value
        idx += Integer.lowestOneBit(idx)
      }
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

    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 java.util._
import java.io._

object D {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

  def next: String = {
    while (st == null || !st.hasMoreTokens) {
      st = new StringTokenizer(br.readLine)
    }
    return st.nextToken
  }

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

  def nextLong: Long = {
    return java.lang.Long.parseLong(next)
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    if (n == 1) {
      out.println(0)
      return 1
    }
    val f1i = new Array[Int](n - 1)
    val map = scala.collection.mutable.Map[Int, Int]()
    f1i(0) = 1
    map.put(a(0), 1)
    for (i <- 1 to n - 2) {
      val num = map.getOrElse(a(i), 0) + 1
      map.put(a(i), num)
      f1i(i) = num
    }
    map.clear
    val fjn = new Array[Int](n - 1)
    fjn(n - 2) = 1
    map.put(a(n - 1), 1)
    for (i <- n - 3 to 0 by -1) {
      val num = map.getOrElse(a(i + 1), 0) + 1
      map.put(a(i + 1), num)
      fjn(i) = num
    }
    map.clear
    object SegmentTree {

      val N = Math.pow(2, 21).toInt
      //      val N = 8
      val tree = new Array[Int](2 * N)

      def build(a: Array[Int]): Unit = {
        for (i <- N until tree.length) {
          tree(i) = a(i - N)
        }
        for (i <- N - 1 to 1 by -1) {
          tree(i) = tree(2 * i) + tree(2 * i + 1)
        }
      }

      def sum(l: Int, r: Int): Int = {
        var sum = 0
        var left = l + N
        var right = r + N
        while (left < right) {
          if (left % 2 == 1) {
            sum += tree(left)
            left += 1
          }
          if (right % 2 != 1) {
            sum += tree(right)
            right -= 1
          }
          left /= 2
          right /= 2
        }
        if (left == right) {
          return sum + tree(left)
        }
        return sum
      }

      def dec(pos: Int): Unit = {
        var i = pos + N
        while (i > 0) {
          tree(i) -= 1
          i /= 2
        }
      }
    }
    val ranges = new Array[Int](SegmentTree.N)
    for (i <- 0 until fjn.length) {
      ranges(fjn(i)) += 1
    }
    SegmentTree.build(ranges)
    var ans: Long = 0
    for (i <- 0 until f1i.length) {
      ans += SegmentTree.sum(0, f1i(i) - 1)
      SegmentTree.dec(fjn(i))
    }
    out.println(ans)
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}