You are given $$$n$$$ sticks with positive integral length $$$a_1, a_2, \ldots, a_n$$$.You can perform the following operation any number of times (possibly zero):   choose one stick, then either increase or decrease its length by $$$1$$$. After each operation, all sticks should have positive lengths. What is the minimum number of operations that you have to perform such that it is possible to select three of the $$$n$$$ sticks and use them without breaking to form an equilateral triangle?An equilateral triangle is a triangle where all of its three sides have the same length.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 300$$$) — the number of sticks. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the lengths of the sticks. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$300$$$.

For each test case, print one integer on a single line — the minimum number of operations to be made.

NoteIn the first test case, you can increase the length of the first stick by $$$1$$$, then decrease the length of the third stick by $$$1$$$. In total, you perform $$$2$$$ operations, such that the three sticks form an equilateral triangle of side length $$$2$$$.In the fourth test case, you can decrease the length of the seventh stick by $$$1$$$. An equilateral triangle of side length $$$1$$$ can be selected and formed by the second, fourth, and seventh sticks.

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt()
    for(i <- 0 until t) {
      val n = readInt()
      val sticks: Array[Int] = readLine.split(" ").map(_.toInt)
      val sortedSticks = sticks.sorted
      var ans: Long = 1e9.toLong
      for(j <- 2 until n) {
        val c = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j-1) -sortedSticks(j-2)
        ans = Math.min(ans,c)
      }

      println(ans)
    }
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt()
    for(i <- 0 until t) {
      val n = readInt()
      val sticks: Array[Int] = readLine.split(" ").map(_.toInt)
      val sortedSticks = sticks.sorted
      var ans: Long = 1e9.toLong
      for(j <- 2 until n) {
        val a = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j) - sortedSticks(j-2)
        val b = sortedSticks(j) - sortedSticks(j-2) + sortedSticks(j-1) -sortedSticks(j-2)
        val c = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j-1) -sortedSticks(j-2)
        ans = List(ans,a,b,c).min
      }

      println(ans)
    }
  }
}

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 10:08
 * @note
 * 1734A. Select Three Sticks | 难度：800
 */
object Solution1734A {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 0 until t) {
      val _ = StdIn.readInt()
      val arr = StdIn.readLine().split(" ").map(_.toInt).sorted
      var minimum = Int.MaxValue
      for (j <- 0 until arr.length - 2) {
        minimum = minimum min (arr(j + 2) + arr(j + 1) - 2 * arr(j)) min
          (arr(j + 2) * 2 - arr(j + 1) - arr(j)) min (arr(j + 2) - arr(j))
      }
      println(minimum)
    }
  }
}

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 10:08
 * @note
 * 1734A. Select Three Sticks | 难度：800
 */
object Solution1734A {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (i <- 0 until t) {
      val n = StdIn.readInt()
      val arr = StdIn.readLine().split(" ").map(_.toInt).sorted
      var min = Int.MaxValue
      for (j <- 0 until arr.length - 2) {
        min = min min (arr(j+2) + arr(j+1) - 2 * arr(j))
      }
      println(min)
    }
  }
}


Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves — from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j — Place a book at position j at shelf i if there is no book at it. 2 i j — Remove the book from position j at shelf i if there is a book at it. 3 i — Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k — Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so?

The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 103, 1 ≤ q ≤ 105) — the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order — i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0.

For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order.

NoteThis image illustrates the second sample case.

//package merofeev.contests.codeforces.rnd368

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
  * @author erofeev
  * @since 03.09.16
  */
//noinspection ReferenceMustBePrefixed
object DGraphPersistence {

  val MAX_COMMANDS = 100010

  val cCodes = new Array[Int](MAX_COMMANDS)
  //0 if it was step
  val cRows = new Array[Int](MAX_COMMANDS)
  //0 if not upplicable
  val cPositions = new Array[Int](MAX_COMMANDS)
  var rowSize = 0

  val book = Array.ofDim[Boolean](1000, 1000)
  val rowSums = new Array[Int](1000)
  val isRowFlipped = new Array[Boolean](1000)
  var currAnsw = 0
  val commandsTree = new Array[ArrayBuffer[Int]](MAX_COMMANDS)
  val answers = new Array[Int](MAX_COMMANDS)

  def solve(parentCmmand: Int): Unit = {
    answers(parentCmmand) = currAnsw
    for (command <- commandsTree(parentCmmand)) {
      val code: Int = cCodes(command)
      var updates = false
      val row: Int = cRows(command)
      for (rollback <- 0 to 1) {
        if (code == 3) {
          currAnsw -= rowSums(row) // rm current value
          isRowFlipped(row) = !isRowFlipped(row)
          rowSums(row) = rowSize - rowSums(row) // compute new val
          currAnsw += rowSums(row) //up new value
        } else if (code != 4) {
          val pos = cPositions(command)
          val isSet = book(row)(pos) ^ isRowFlipped(row)
          val upVal = if (code == 1) 1 else -1
          if (rollback == 0) {
            updates = isSet ^ code == 1
            if (updates) {
              book(row)(pos) = !book(row)(pos)
              rowSums(row) += upVal
              currAnsw += upVal
            }
          } else if (rollback == 1 && updates) {
            book(row)(pos) = !book(row)(pos)
            rowSums(row) -= upVal
            currAnsw -= upVal
          }
        }
        if (rollback == 0) {
          solve(command)
        }
      }
    }
  }

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

    val in = new Scanner(System.in)
    val rows = in.nextInt()
    this.rowSize = in.nextInt()
    val ops = in.nextInt()
    for (i <- 0 to ops) {
      commandsTree(i) = new ArrayBuffer()
    }

    //save every shelf as a bitset object (30b), 30b * 10000 = 3mb??
    //save every bookcase as a list of shelfs (100 * 8 + 20 = 850) * 100000 = 85mb
    var pos = 1
    while (in.hasNextInt) {
      cCodes(pos) = in.nextInt()
      cRows(pos) = in.nextInt() //step in case of 4 coe
      if (cCodes(pos) == 4) {
        commandsTree(cRows(pos)) += pos
      } else {
        cRows(pos) -= 1 //alignment
        commandsTree(pos - 1) += pos //children of previous
      }
      if (cCodes(pos) == 1 || cCodes(pos) == 2) {
        cPositions(pos) = in.nextInt() - 1 //alignment
      }
      pos += 1
    }
    solve(0)
    for (comm <- 1 to ops) {
      println(answers(comm))
    }
  }

}

import scala.annotation.tailrec
import scala.collection.breakOut

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
object Main {
  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  class Shelf(val books: Vector[Boolean],val inverted: Boolean, val count: Int) {
    def invert() : Shelf = new Shelf(books, !inverted, books.size - count)
    def place(j: Int) : Shelf = {
      val p = if(!inverted) true else false
      val i = if(books(j) != p) 1 else 0
      new Shelf(books.updated(j, p), inverted, count + i)
    }
    def remove(j: Int) : Shelf = {
      val p = if(!inverted) false else true
      val i = if(books(j) != p) -1 else 0
      new Shelf(books.updated(j, p), inverted, count + i)
    }
  }

  class BookCase(val shelves: Vector[Shelf], val count: Int) {
    def place(i: Int, j: Int) : BookCase = {
      val oldone = shelves(i)
      val newone = oldone.place(j)
      new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)
    }
    def remove(i: Int, j: Int) : BookCase = {
      val oldone = shelves(i)
      val newone = oldone.remove(j)
      new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)
    }
    def invert(i: Int) : BookCase = {
      val oldone = shelves(i)
      val newone = oldone.invert
      new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)
    }
  }

  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    def main() : Unit = {
      val n, m, q = nextInt()
      val logs : Array[BookCase] = Array.fill(q+1)(null)
      logs(0) = new BookCase(Vector.fill(n)(new Shelf(Vector.fill(m)(false), false, 0)), 0)
      for(qu <- 1 to q) {
        val t = nextInt()
        t match {
          case 1 => { // place
            val i, j = nextInt()-1
            logs(qu) = logs(qu-1).place(i, j)
          }
          case 2 => { // remove
            val i, j = nextInt()-1
            logs(qu) = logs(qu-1).remove(i, j)
          }
          case 3 => { // invert
            val i = nextInt()-1
            logs(qu) = logs(qu-1).invert(i)
          }
          case 4 => { // return
            val k = nextInt()
            logs(qu) = logs(k)
          }
          case _ => {
          }
        }
        println(logs(qu).count)
      }
    }
  }

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

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

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

}

object Solution {

  case class State(flip: Vector[Boolean], shelves: Vector[Vector[Boolean]], cnt: Vector[Int], total: Int) {
    def existBook(i: Int, j: Int): Boolean = flip.apply(i) ^ shelves(i)(j)
    def place(i: Int, j: Int): State = {
      if (existBook(i, j)) this
      else
        State(flip, shelves.updated(i, shelves(i).updated(j, !flip(i))), cnt.updated(i, cnt(i) + 1), total + 1)
    }
    def remove(i: Int, j: Int): State = {
      if (!existBook(i, j)) this
      else
        State(flip, shelves.updated(i, shelves(i).updated(j, flip(i))), cnt.updated(i, cnt(i) - 1), total - 1)
    }
    def turn(i: Int): State =
      State(flip.updated(i, !flip(i)), shelves, cnt.updated(i, shelves(0).size - cnt(i)), total - 2*cnt(i) + shelves(0).size)
  }

  def main(args: Array[String]): Unit = {
    val tokens = scala.io.Source.stdin.getLines
      .flatMap(_ split ' ' filter (_.nonEmpty))

    def nextInt() = tokens.next().toInt

    val N, M, Q = nextInt()
    val states = Array.ofDim[State](Q + 1)
    states(0) = State(Vector.fill(N)(false), Vector.fill(N)(Vector.fill(M)(false)), Vector.fill(N)(0), 0)

    for (i <- 1 to Q) {
      states(i) = nextInt() match {
        case 1 => val s, p = nextInt() - 1; states(i - 1).place(s, p)
        case 2 => val s, p = nextInt() - 1; states(i - 1).remove(s, p)
        case 3 => states(i - 1).turn(nextInt() - 1)
        case 4 => states(nextInt())
      }
      println(states(i).total)
    }
  }
}

object Solution {

case class State(flip: Vector[Boolean], shelves: Vector[Vector[Boolean]], cnt: Vector[Int], total: Int) {
  def existBook(i: Int, j: Int): Boolean = flip.apply(i) ^ shelves(i)(j)
  def place(i: Int, j: Int): State = {
    if (existBook(i, j)) this
    else
      State(flip, shelves.updated(i, shelves(i).updated(j, !flip.apply(i))), cnt.updated(i, cnt(i) + 1), total + 1)
  }
  def remove(i: Int, j: Int): State = {
    if (!existBook(i, j)) this
    else
      State(flip, shelves.updated(i, shelves(i).updated(j, flip.apply(i))), cnt.updated(i, cnt(i) - 1), total - 1)
  }
  def flip(i: Int): State =
    State(flip.updated(i, !flip.apply(i)), shelves, cnt.updated(i, shelves(0).size - cnt(i)), total - cnt(i) + shelves(0).size - cnt(i))
}

  def main(args: Array[String]): Unit = {
    val br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    var st: java.util.StringTokenizer = null
    val writer =  new java.io.PrintWriter(System.out)

    def nextInt(): Int = {
      while (st == null || !st.hasMoreElements())
          st = new java.util.StringTokenizer(br.readLine())
      return st.nextToken().toInt
    }

    val N, M, Q = nextInt()
    val states = Array.ofDim[State](Q + 1)
    states(0) = State(
      Vector.fill(N)(false),
      Vector.fill(N)(Vector.fill(M)(false)),
      Vector.fill(N)(0),
      0
    )

    for (i <- 1 to Q) {
      states(i) = nextInt() match {
        case 1 => val s, p = nextInt() - 1; states(i - 1).place(s, p)
        case 2 => val s, p = nextInt() - 1; states(i - 1).remove(s, p)
        case 3 => states(i - 1).flip(nextInt() - 1)
        case 4 => states(nextInt())
      }
      writer.println(states(i).total)
    }

    writer.close()
  }
}

//package merofeev.contests.codeforces.rnd368

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
  * @author erofeev
  * @since 03.09.16
  */
//noinspection ReferenceMustBePrefixed
object DGraphPersistence {

  val MAX_COMMANDS = 100000

  val cCodes = new Array[Int](MAX_COMMANDS)
  //0 if it was step
  val cRows = new Array[Int](MAX_COMMANDS)
  //0 if not upplicable
  val cPositions = new Array[Int](MAX_COMMANDS)
  var rowSize = 0

  val book = Array.ofDim[Boolean](1000, 1000)
  val rowSums = new Array[Int](1000)
  val isRowFlipped = new Array[Boolean](1000)
  var currAnsw = 0
  val commandsTree = new Array[ArrayBuffer[Int]](MAX_COMMANDS)
  val answers = new Array[Int](MAX_COMMANDS)

  def solve(parentCmmand: Int): Unit = {
    answers(parentCmmand) = currAnsw
    for (command <- commandsTree(parentCmmand)) {
      val code: Int = cCodes(command)
      var updates = false
      val row: Int = cRows(command)
      for (rollback <- 0 to 1) {
        if (code == 3) {
          currAnsw -= rowSums(row) // rm current value
          isRowFlipped(row) = !isRowFlipped(row)
          rowSums(row) = rowSize - rowSums(row) // compute new val
          currAnsw += rowSums(row) //up new value
        } else {
          val pos = cPositions(command)
          val isSet = book(row)(pos) ^ isRowFlipped(row)
          val upVal = if (code == 1) 1 else -1
          if (rollback == 0) {
            updates = isSet ^ code == 1
            if (updates) {
              book(row)(pos) = !book(row)(pos)
              rowSums(row) += upVal
              currAnsw += upVal
            }
          } else if (rollback == 1 && updates) {
            book(row)(pos) = !book(row)(pos)
            rowSums(row) -= upVal
            currAnsw -= upVal
          }
        }
        if (rollback == 0) {
          solve(command)
        }
      }
    }
  }

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

    for (i <- commandsTree.indices) {
      commandsTree(i) = new ArrayBuffer()
    }

    val in = new Scanner(System.in)
    val rows = in.nextInt()
    this.rowSize = in.nextInt()
    val ops = in.nextInt()

    //save every shelf as a bitset object (30b), 30b * 10000 = 3mb??
    //save every bookcase as a list of shelfs (100 * 8 + 20 = 850) * 100000 = 85mb
    var pos = 1
    while (in.hasNextInt) {
      cCodes(pos) = in.nextInt()
      cRows(pos) = in.nextInt()
      if (cCodes(pos) == 4) {
        commandsTree(cRows(pos)) += pos
      } else {
        cRows(pos) -= 1 //alignment
        commandsTree(pos - 1) += pos
      }
      if (cCodes(pos) == 1 || cCodes(pos) == 2) {
        cPositions(pos) = in.nextInt() - 1 //alignment
      }
      pos += 1
    }
    solve(0)
    for (comm <- 1 to ops) {
      println(answers(comm))
    }
  }

}


There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves.Tablecity can be represented as 1000 × 2 grid, where every cell represents one district. Each district has its own unique name “(X, Y)”, where X and Y are the coordinates of the district in the grid. The thief’s movement is as Every hour the thief will leave the district (X, Y) he is currently hiding in, and move to one of the districts: (X - 1, Y), (X + 1, Y), (X - 1, Y - 1), (X - 1, Y + 1), (X + 1, Y - 1), (X + 1, Y + 1) as long as it exists in Tablecity. Below is an example of thief’s possible movements if he is located in district (7,1):Albert has enough people so that every hour he can pick any two districts in Tablecity and fully investigate them, making sure that if the thief is located in one of them, he will get caught. Albert promised the President that the thief will be caught in no more than 2015 hours and needs your help in order to achieve that.

The first line of output contains integer N – duration of police search in hours. Each of the following N lines contains exactly 4 integers Xi1, Yi1, Xi2, Yi2 separated by spaces, that represent 2 districts (Xi1, Yi1), (Xi2, Yi2) which got investigated during i-th hour. Output is given in chronological order (i-th line contains districts investigated during i-th hour) and should guarantee that the thief is caught in no more than 2015 hours, regardless of thief’s initial position and movement.   N ≤ 2015  1 ≤ X ≤ 1000  1 ≤ Y ≤ 2

В этой задаче нет примеров ввода-вывода.
This problem doesn't have sample input and output.

Смотрите замечание ниже.
See the note below.

NoteLet's consider the following output:25 1 50 28 1 80 2This output is not guaranteed to catch the thief and is not correct. It is given to you only to show the expected output format. There exists a combination of an initial position and a movement strategy such that the police will not catch the thief.Consider the following initial position and thief’s movement:In the first hour, the thief is located in district (1,1). Police officers will search districts (5,1) and (50,2) and will not find him.At the start of the second hour, the thief moves to district (2,2). Police officers will search districts (8,1) and (80,2) and will not find him.Since there is no further investigation by the police, the thief escaped!

object Main {

  def main(args: Array[String]) {
    println(2000)
    for (i <- 1 to 1000) {
      println(i + " " + 1 + " " + i + " " + 2)
    }
     for (i <- (1 to 1000).reverse)  {
      println(i + " " + 1 + " " + i + " " + 2)
    }
  }
}

object Main {

  def main(args: Array[String]) {
    println(1000)
    for (i <- 1 to 1000) {
      println(i + " " + 1 + " " + i + " " + 2)
    }
  }
}

object Main {

  def main(args: Array[String]) {
    println(1999)
    for (i <- 1 to 1000) {
      println(i + " " + 1 + " " + i + " " + 2)
    }
     for (i <- (1 to 999).reverse)  {
      println(i + " " + 1 + " " + i + " " + 2)
    }
  }
}


Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review  — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the dishes are different, because Mr. Apple doesn't like to eat the same food. For each pair of dishes from different days he remembers exactly which was better, or that they were of the same quality. After this the gourmet evaluates each dish with a positive integer.Once, during a revision of a restaurant of Celtic medieval cuisine named «Poisson», that serves chestnut soup with fir, warm soda bread, spicy lemon pie and other folk food, Mr. Apple was very pleasantly surprised the gourmet with its variety of menu, and hence ordered too much. Now he's confused about evaluating dishes.The gourmet tasted a set of $$$n$$$ dishes on the first day and a set of $$$m$$$ dishes on the second day. He made a table $$$a$$$ of size $$$n \times m$$$, in which he described his impressions. If, according to the expert, dish $$$i$$$ from the first set was better than dish $$$j$$$ from the second set, then $$$a_{ij}$$$ is equal to ">", in the opposite case $$$a_{ij}$$$ is equal to "<". Dishes also may be equally good, in this case $$$a_{ij}$$$ is "=".Now Mr. Apple wants you to help him to evaluate every dish. Since Mr. Apple is very strict, he will evaluate the dishes so that the maximal number used is as small as possible. But Mr. Apple also is very fair, so he never evaluates the dishes so that it goes against his feelings. In other words, if $$$a_{ij}$$$ is "<", then the number assigned to dish $$$i$$$ from the first set should be less than the number of dish $$$j$$$ from the second set, if $$$a_{ij}$$$ is ">", then it should be greater, and finally if $$$a_{ij}$$$ is "=", then the numbers should be the same.Help Mr. Apple to evaluate each dish from both sets so that it is consistent with his feelings, or determine that this is impossible.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 1000$$$) — the number of dishes in both days. Each of the next $$$n$$$ lines contains a string of $$$m$$$ symbols. The $$$j$$$-th symbol on $$$i$$$-th line is $$$a_{ij}$$$. All strings consist only of "<", ">" and "=".

The first line of output should contain "Yes", if it's possible to do a correct evaluation for all the dishes, or "No" otherwise. If case an answer exist, on the second line print $$$n$$$ integers — evaluations of dishes from the first set, and on the third line print $$$m$$$ integers — evaluations of dishes from the second set.

NoteIn the first sample, all dishes of the first day are better than dishes of the second day. So, the highest score will be $$$2$$$, for all dishes of the first day.In the third sample, the table is contradictory — there is no possible evaluation of the dishes that satisfies it.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, M = ni()

    val mat = nm_c(N, M)

    val uf = new UnionFind(N + M)

    REP(N) { i =>
      REP(M) { j =>
        if (mat(i)(j) == '=') uf.unite(i, N + j)
      }
    }

    // 矢印の方向は大きいほうから小さい方へ
    val g = Array.fill[ArrayBuffer[Int]](N + M)(ArrayBuffer())
    REP(N) { i =>
      REP(M) { j =>
        val v = uf.find(i)
        val u = uf.find(j + N)
        mat(i)(j) match {
          case '<' => g(u) += v
          case '>' => g(v) += u
          case _ =>
        }
      }
    }

    val ans = Array.ofDim[Int](N + M)
    val visit = Array.ofDim[Int](N + M)

    def dfs(v: Int): Boolean = {
//      debug(s"dfs($v)")
      visit(v) = 1
      if (g(v).isEmpty) ans(v) = 1
      else {
        var mx = 0
        REP(g(v).length) { j =>
          val u = g(v)(j)
          if (visit(u) == 0) {
            if (!dfs(u)) return false
          } else if (visit(u) == 1) return false
          mx = max(ans(u), mx)
        }
        ans(v) = mx + 1 // 最大の子供 + 1
//        debug(s"ans($v) = ${ans(v)}")
      }

      visit(v) = 2
      true
    }

    var ok = true
    REP(N + M) { i =>
      val v = uf.find(i)
      if (ok && visit(v) == 0) ok &&= dfs(v)
    }

    if (!ok) out.println("No")
    else {
      out.println("Yes")
      val first = map(N) { i =>
        val v = uf.find(i)
        ans(v)
      }.mkString(" ")

      val second = map(M) { i =>
        val v = uf.find(N + i)
        ans(v)
      }.mkString(" ")

      out.println(first)
      out.println(second)
    }
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, M = ni()

    val mat = nm_c(N, M)

    val uf = new UnionFind(N + M)

    REP(N) { i =>
      REP(M) { j =>
        if (mat(i)(j) == '=') uf.unite(i, N + j)
      }
    }

    // 矢印の方向は大きいほうから小さい方へ
    val g = Array.fill[ArrayBuffer[Int]](N + M)(ArrayBuffer())
    REP(N) { i =>
      REP(M) { j =>
        val v = uf.find(i)
        val u = uf.find(j + N)
        mat(i)(j) match {
          case '<' => g(u) += v
          case '>' => g(v) += u
          case _ =>
        }
      }
    }

    val ans = Array.ofDim[Int](N + M)
    val visit = Array.ofDim[Int](N + M)

    def dfs(v: Int): Boolean = {
      visit(v) = 1
      if (g(v).isEmpty) ans(v) = 1
      else {
        var mx = 0
        REP(g(v).length) { j =>
          val u = g(v)(j)
          if (visit(u) == 0) dfs(u)
          else if (visit(u) == 1) return false
          mx = max(ans(u), mx)
        }
        ans(v) = mx + 1 // 最大の子供 + 1
      }

      visit(v) = 2
      true
    }

    var ok = true
    REP(N + M) { i =>
      val v = uf.find(i)
      if (ok && visit(v) == 0) ok &&= dfs(v)
    }

    if (!ok) out.println("No")
    else {
      out.println("Yes")
      val first = map(N) { i =>
        val v = uf.find(i)
        ans(v)
      }.mkString(" ")

      val second = map(M) { i =>
        val v = uf.find(N + i)
        ans(v)
      }.mkString(" ")

      out.println(first)
      out.println(second)
    }
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter. Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.You are given an encoding s of some word, your task is to decode it.

The first line contains a positive integer n (1 ≤ n ≤ 2000) — the length of the encoded word. The second line contains the string s of length n consisting of lowercase English letters — the encoding.

NoteIn the first example Polycarp encoded the word volga. At first, he wrote down the letter l from the position 3, after that his word looked like voga. After that Polycarp wrote down the letter o from the position 2, his word became vga. Then Polycarp wrote down the letter g which was at the second position, the word became va. Then he wrote down the letter v, then the letter a. Thus, the encoding looked like logva.In the second example Polycarp encoded the word no. He wrote down the letter n, the word became o, and he wrote down the letter o. Thus, in this example, the word and its encoding are the same.In the third example Polycarp encoded the word baba. At first, he wrote down the letter a, which was at the position 2, after that the word looked like bba. Then he wrote down the letter b, which was at the position 2, his word looked like ba. After that he wrote down the letter b, which was at the position 1, the word looked like a, and he wrote down that letter a. Thus, the encoding is abba.

import java.util.StringTokenizer

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

  read()
  val n = int()
  val s = readLine()

  var s2 = Array.fill(n)(' ')

  (0 until n).foreach { i =>
    val l = n - i
    var m = (l - 1) / 2
    var j = 0
    while (m >= 0) {
      if (s2(j) == ' ') m -= 1
      if (m < 0) s2(j) = s(i)
      j += 1
    }
  }

  println(s2.mkString)
}


You are given two integers $$$n$$$ and $$$k$$$. Your task is to find if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The only line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 10^7$$$).

For each test case, print the answer — "YES" (without quotes) if $$$n$$$ can be represented as a sum of $$$k$$$ distinct positive odd (not divisible by $$$2$$$) integers and "NO" otherwise.

NoteIn the first test case, you can represent $$$3$$$ as $$$3$$$.In the second test case, the only way to represent $$$4$$$ is $$$1+3$$$.In the third test case, you cannot represent $$$10$$$ as the sum of three distinct positive odd integers.In the fourth test case, you can represent $$$10$$$ as $$$3+7$$$, for example.In the fifth test case, you can represent $$$16$$$ as $$$1+3+5+7$$$.In the sixth test case, you cannot represent $$$16$$$ as the sum of five distinct positive odd integers.

object Main {

	def main(arr: Array[String]): Unit = {
		var n: Int = readLine().toInt
		while (n > 0) {
			var _pairs = readLine().split(" ")
			var num1 : Long = _pairs(0).toLong
			var num2 : Long = _pairs(1).toLong
			if (num1 % 2 == num2 % 2 && num1 >= num2 * num2){
			    println("YES")
			} else {
			    println("NO")
			}
			n -= 1
		}

	}

}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val n = in.nextLong()
      val k = in.nextLong()
      if((n-k)%2 == 0){
        val x: Long = (n-k)/2
        if(2L*x>=(k*(k-1L))){
          out.println("YES")
        }else{
          out.println("NO")
        }

      }else{
        out.println("NO")
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

	def main(arr: Array[String]): Unit = {
		var n: Int = readLine().toInt
		while (n > 0) {
			var _pairs = readLine().split(" ")
			var num1 : Int = _pairs(0).toInt
			var num2 : Int = _pairs(1).toInt
			if (num1 % 2 == num2 % 2 && num1 >= num2 * num2){
			    println("YES")
			} else {
			    println("NO")
			}
			n -= 1
		}

	}

}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      val k = in.nextInt()
      if((n-k)%2 == 0){
        val x = (n-k)/2
        if(2*x>=(k*(k-1))){
          out.println("YES")
        }else{
          out.println("NO")
        }

      }else{
        out.println("NO")
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


Polycarp wants to train before another programming competition. During the first day of his training he should solve exactly $$$1$$$ problem, during the second day — exactly $$$2$$$ problems, during the third day — exactly $$$3$$$ problems, and so on. During the $$$k$$$-th day he should solve $$$k$$$ problems.Polycarp has a list of $$$n$$$ contests, the $$$i$$$-th contest consists of $$$a_i$$$ problems. During each day Polycarp has to choose exactly one of the contests he didn't solve yet and solve it. He solves exactly $$$k$$$ problems from this contest. Other problems are discarded from it. If there are no contests consisting of at least $$$k$$$ problems that Polycarp didn't solve yet during the $$$k$$$-th day, then Polycarp stops his training.How many days Polycarp can train if he chooses the contests optimally?

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of contests. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$) — the number of problems in the $$$i$$$-th contest.

Print one integer — the maximum number of days Polycarp can train if he chooses the contests optimally.

object codeForces extends App
{
    val n=scala.io.StdIn.readInt()
    val line=scala.io.StdIn.readLine()
    val ara=scala.collection.mutable.ArrayBuffer.empty[Int]
    val input=line.split(" ").map(_.toInt)
    var i=0
    for(i<-0 until n)    {
        ara+=input(i)
    }
    val sorted=ara.sorted

    var ans=1
    for (x<-sorted)    {
        if(x>=ans)    ans+=1
    }

    println(ans-1)
}

object _1165B extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val as = io.read[Seq[Int]].sorted
    val ans = as.foldLeft(1)({ case (i, j) => if (i <= j) i+1 else i})
    io.write(ans - 1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object Main extends CodeForcesApp {

  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val sortedContests = io.read[Seq[Int]].sorted

    var i = 0
    var k = 1
    var ans = 0
    while (i < sortedContests.length) {
      if (sortedContests(i) >= k) {
        k += 1
        ans += 1
      }
      i += 1
    }
    io.writeLine(ans)
  }
}

/** **************************[Ignore Template Below] ****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)

  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)

  def apply(io: IO): io.type

  def main(args: Array[String]): Unit = this (new IO(System.in, System.out)).close()
}

/** *********************************[Scala I/O] *********************************************/

import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))

  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while (tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)

  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)

  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()

  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }

  def writeLine(): this.type = {
    printer.println()
    this
  }

  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }

  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")

  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()

  def close() = {
    flush()
    in.close()
    printer.close()
  }
}

object IO {

  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))

    implicit val string: Read[String] = new Read(_.next())
    implicit val int: Read[Int] = string.map(_.toInt)
    implicit val long: Read[Long] = string.map(_.toLong)
    implicit val bigInt: Read[BigInt] = string.map(BigInt(_))
    implicit val double: Read[Double] = string.map(_.toDouble)
    implicit val bigDecimal: Read[BigDecimal] = string.map(BigDecimal(_))

    implicit def tuple2[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    implicit def tuple3[A: Read, B: Read, C: Read]: Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))

    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]: Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))

    implicit val boolean: Read[Boolean] = string map { s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }

}

object Main extends App {
  final object InOut {
    val in =
      new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, true)
    var arr = Array[String]()
    var index: Int = 0
    def nextToken: String = {
      if (index >= arr.length) {
        index = 0
        arr = in.readLine.split(" ")
      }
      val ans = arr(index)
      index += 1
      ans
    }

    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 InOut._

  val n = nextInt
  val arr = nextInts(n).sorted

  var count = 0
  var k = 1
  for (i <- arr){
    if (i >= k){
      count += 1
      k += 1
    }
  }

  println(count)

}

object Main extends App {
  final object InOut {
    val in =
      new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, true)
    var arr = Array[String]()
    var index: Int = 0
    def nextToken: String = {
      if (index >= arr.length) {
        index = 0
        arr = in.readLine.split(" ")
      }
      val ans = arr(index)
      index += 1
      ans
    }

    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 InOut._

  val n = nextInt
  //scala one line magic
  println(nextInts(n).sorted.foldLeft(1)({ (i, j) => if (i <= j) i+1 else i}) -1 )
}

import java.util.Scanner

import scala.io.StdIn

object Btask560 extends App {
  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()
  val x = StdIn.readLine().split(' ').map(_.toInt).sorted

  var day = 1

  for (i <- 0 until n) {
    if (x(i) >= day) {
      day += 1
    }
  }

  println(day-1)
}


In the year of $$$30XX$$$ participants of some world programming championship live in a single large hotel. The hotel has $$$n$$$ floors. Each floor has $$$m$$$ sections with a single corridor connecting all of them. The sections are enumerated from $$$1$$$ to $$$m$$$ along the corridor, and all sections with equal numbers on different floors are located exactly one above the other. Thus, the hotel can be represented as a rectangle of height $$$n$$$ and width $$$m$$$. We can denote sections with pairs of integers $$$(i, j)$$$, where $$$i$$$ is the floor, and $$$j$$$ is the section number on the floor.The guests can walk along the corridor on each floor, use stairs and elevators. Each stairs or elevator occupies all sections $$$(1, x)$$$, $$$(2, x)$$$, $$$\ldots$$$, $$$(n, x)$$$ for some $$$x$$$ between $$$1$$$ and $$$m$$$. All sections not occupied with stairs or elevators contain guest rooms. It takes one time unit to move between neighboring sections on the same floor or to move one floor up or down using stairs. It takes one time unit to move up to $$$v$$$ floors in any direction using an elevator. You can assume you don't have to wait for an elevator, and the time needed to enter or exit an elevator is negligible.You are to process $$$q$$$ queries. Each query is a question "what is the minimum time needed to go from a room in section $$$(x_1, y_1)$$$ to a room in section $$$(x_2, y_2)$$$?"

The first line contains five integers $$$n, m, c_l, c_e, v$$$ ($$$2 \leq n, m \leq 10^8$$$, $$$0 \leq c_l, c_e \leq 10^5$$$, $$$1 \leq c_l + c_e \leq m - 1$$$, $$$1 \leq v \leq n - 1$$$) — the number of floors and section on each floor, the number of stairs, the number of elevators and the maximum speed of an elevator, respectively. The second line contains $$$c_l$$$ integers $$$l_1, \ldots, l_{c_l}$$$ in increasing order ($$$1 \leq l_i \leq m$$$), denoting the positions of the stairs. If $$$c_l = 0$$$, the second line is empty. The third line contains $$$c_e$$$ integers $$$e_1, \ldots, e_{c_e}$$$ in increasing order, denoting the elevators positions in the same format. It is guaranteed that all integers $$$l_i$$$ and $$$e_i$$$ are distinct. The fourth line contains a single integer $$$q$$$ ($$$1 \leq q \leq 10^5$$$) — the number of queries. The next $$$q$$$ lines describe queries. Each of these lines contains four integers $$$x_1, y_1, x_2, y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1 \leq y_1, y_2 \leq m$$$) — the coordinates of starting and finishing sections for the query. It is guaranteed that the starting and finishing sections are distinct. It is also guaranteed that these sections contain guest rooms, i. e. $$$y_1$$$ and $$$y_2$$$ are not among $$$l_i$$$ and $$$e_i$$$.

Print $$$q$$$ integers, one per line — the answers for the queries.

NoteIn the first query the optimal way is to go to the elevator in the 5-th section in four time units, use it to go to the fifth floor in two time units and go to the destination in one more time unit.In the second query it is still optimal to use the elevator, but in the third query it is better to use the stairs in the section 2.

import scala.collection.mutable

object A 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, m, cl, ce, v) = readInts(5)
  val ls, es = new java.util.TreeSet[Integer]

  val _ls = readInts(cl)
  for (x <- _ls) ls.add(x)

  val _es = readInts(ce)
  for (x <- _es) es.add(x)

  val Array(q) = readInts(1)

  val res = new mutable.ArrayBuilder.ofInt

  for (_ <- 0 until q) {
    val Array(y1, x1, y2, x2) = readInts(4)
    var min = Int.MaxValue

    def elev(x: Int): Int = {
      (Math.abs(y1 - y2) + v - 1) / v + Math.abs(x1 - x) + Math.abs(x2 - x)
    }

    def stair(x: Int): Int = {
      Math.abs(y1 - y2) + Math.abs(x1 - x) + Math.abs(x2 - x)
    }

    if (y1 == y2) min = Math.abs(x1 - x2)
    else {

      val eLeft = es.floor(x1)
      val eRight = es.ceiling(x1)
      val lLeft = ls.floor(x1)
      val lRight = ls.ceiling(x1)

      if (eLeft != null && elev(eLeft) < min) min = elev(eLeft)
      if (eRight != null && elev(eRight) < min) min = elev(eRight)

      if (lLeft != null && stair(lLeft) < min) min = stair(lLeft)
      if (lRight != null && stair(lRight) < min) min = stair(lRight)
    }

    res += min
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(res.result.mkString("\n"))

  Console.flush
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader
    val n, m = r.read[Long]
    val cl, ce = r.read[Int]
    val v = r.read[Long]
    val cls = r.read[Array[Long]](cl)
    val ces = r.read[Array[Long]](ce)
    val q = r.read[Int]
    val qs = r.read[List[(Long, Long, Long, Long)]](q)

    qs.foreach {
      case (x1, y1, x2, y2) => {
        val ds = if (cl > 0) {
          val i1 = 0.max(lb(cls(_) > y1, 0, cl-1)).min(cl-1)
          val i12 = (cl-1).min(i1+1)
          val i2 = 0.max(lb(cls(_) > y2, 0, cl-1)).min(cl-1)
          val i22 = (cl-1).min(i2+1)
          val s1 = (y1 - cls(i1)).abs + (y2 - cls(i1)).abs
          val s2 = (y1 - cls(i12)).abs + (y2 - cls(i12)).abs
          val s3 = (y1 - cls(i2)).abs + (y2 - cls(i2)).abs
          val s4 = (y1 - cls(i22)).abs + (y2 - cls(i22)).abs
          s1.min(s2.min(s3.min(s4))) + (x2 - x1).abs
        } else Long.MaxValue

        val de = if (ce > 0) {
          val j1 = 0.max(lb(ces(_) > y1, 0, ce-1)).min(ce-1)
          val j12 = (ce-1).min(j1+1)
          val j2 = 0.max(lb(ces(_) > y2, 0, ce-1)).min(ce-1)
          val j22 = (ce-1).min(j2+1)

          val e1 = (y1 - ces(j1)).abs + (y2 - ces(j1)).abs
          val e2 = (y1 - ces(j12)).abs + (y2 - ces(j12)).abs
          val e3 = (y1 - ces(j2)).abs + (y2 - ces(j2)).abs
          val e4 = (y1 - ces(j22)).abs + (y2 - ces(j22)).abs
          e1.min(e2.min(e3.min(e4))) + ((x2 - x1).abs - 1) / v + 1
        } else Long.MaxValue

        val dx = if (x1 == x2) (y2 - y1).abs else Long.MaxValue

        println(ds.min(de.min(dx)))
      }
    }
  }

  def lb(test: (Int => Boolean), from: Int, to: Int) = {
    import annotation.tailrec
    @tailrec
    def go(l: Int, r: Int): Int =
      if (l <= r) {
        val m = (r + l) / 2
        if (test(m)) go(l, m - 1) else go(m + 1, r)
      } else r

    go(from, to)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)

    implicit def tuple[A: Read]: Read[(A, A, A, A)] = new Read(r => (r.read[A], r.read[A], r.read[A], r.read[A]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader
    val n, m = r.read[Long]
    val cl, ce = r.read[Int]
    val v = r.read[Long]
    val cls = r.read[Array[Long]](cl)
    val ces = r.read[Array[Long]](ce)
    val q = r.read[Int]
    val qs = r.read[List[(Long, Long, Long, Long)]](q)

    qs.foreach {
      case (x1, y1, x2, y2) => {
        val ds = if (cl > 0) {
          val i1 = 0.max(lb(cls(_) > y1, 0, cl-1)).min(cl-1)
          val i12 = (cl-1).min(i1+1)
          val i2 = 0.max(lb(cls(_) > y2, 0, cl-1)).min(cl-1)
          val i22 = (cl-1).min(i2+1)
          val s1 = (y1 - cls(i1)).abs + (y2 - cls(i1)).abs
          val s2 = (y1 - cls(i12)).abs + (y2 - cls(i12)).abs
          val s3 = (y1 - cls(i2)).abs + (y2 - cls(i2)).abs
          val s4 = (y1 - cls(i22)).abs + (y2 - cls(i22)).abs
          s1.min(s2.min(s3.min(s4))) + (x2 - x1).abs
        } else Long.MaxValue

        val de = if (ce > 0) {
          val j1 = 0.max(lb(ces(_) > y1, 0, ce-1)).min(ce-1)
          val j12 = (ce-1).min(j1+1)
          val j2 = 0.max(lb(ces(_) > y2, 0, ce-1)).min(ce-1)
          val j22 = (ce-1).min(j2+1)

          val e1 = (y1 - ces(j1)).abs + (y2 - ces(j1)).abs
          val e2 = (y1 - ces(j12)).abs + (y2 - ces(j12)).abs
          val e3 = (y1 - ces(j2)).abs + (y2 - ces(j2)).abs
          val e4 = (y1 - ces(j22)).abs + (y2 - ces(j22)).abs
          e1.min(e2.min(e3.min(e4))) + ((x2 - x1).abs - 1) / v + 1
        } else Long.MaxValue

        println(ds.min(de))
      }
    }
  }

  def lb(test: (Int => Boolean), from: Int, to: Int) = {
    import annotation.tailrec
    @tailrec
    def go(l: Int, r: Int): Int =
      if (l <= r) {
        val m = (r + l) / 2
        if (test(m)) go(l, m - 1) else go(m + 1, r)
      } else r

    go(from, to)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)

    implicit def tuple[A: Read]: Read[(A, A, A, A)] = new Read(r => (r.read[A], r.read[A], r.read[A], r.read[A]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}


Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the power of Sunlight, and uses it to either:  Remove a single cow from a chosen non-empty pile.  Choose a pile of cows with even size 2·x (x > 0), and replace it with k piles of x cows each. The player who removes the last cow wins. Given n, k, and a sequence a1, a2, ..., an, help Kevin and Nicky find the winner, given that both sides play in optimal way.

The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109). The second line contains n integers, a1, a2, ... an (1 ≤ ai ≤ 109) describing the initial state of the game.

Output the name of the winning player, either "Kevin" or "Nicky" (without quotes).

NoteIn the second sample, Nicky can win in the following way: Kevin moves first and is forced to remove a cow, so the pile contains two cows after his move. Next, Nicky replaces this pile of size 2 with two piles of size 1. So the game state is now two piles of size 1. Kevin then removes one of the remaining cows and Nicky wins by removing the other.

object E{
  //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,k)=(nextInt,nextInt)
    def f(a:Int):Int={
      if(k%2==0){
        a match {
          case 0 => 0
          case 1 => 1
          case 2 => 2
          case _ => if(a%2==1) 0 else 1
        }
      }else{
        a match {
          case 0 => 0
          case 1 => 1
          case 2 => 0
          case 3 => 1
          case 4 => 2
          case _ => if(a%2==1) 0 else if(f(a/2)==1){
            2
          }else 1
        }
      }
    }
    var ans=0
    for(i<-0 until n) ans^=f(nextInt)
    out.println(if (ans==0) "Nicky" else "Kevin")
    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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,k)=(nextInt,nextInt)
    def f(a:Int):Int={
      if(k%2==0){
        a match {
          case 0 => 0
          case 1 => 1
          case 2 => 2
          case _ => if(a%2==1) 0 else 1
        }
      }else{
        a match {
          case 0 => 0
          case 1 => 1
          case 2 => 0
          case _ => if(a%2==1) 0 else if(f(a/2)==1){
            2
          }else 1
        }
      }
    }
    var ans=0
    for(i<-0 until n) ans^=f(nextInt)
    out.println(if (ans==0) "Nicky" else "Kevin")
    //code ends here
    out.flush
    out.close
  }
}


Eric has an array $$$b$$$ of length $$$m$$$, then he generates $$$n$$$ additional arrays $$$c_1, c_2, \dots, c_n$$$, each of length $$$m$$$, from the array $$$b$$$, by the following way:Initially, $$$c_i = b$$$ for every $$$1 \le i \le n$$$. Eric secretly chooses an integer $$$k$$$ $$$(1 \le k \le n)$$$ and chooses $$$c_k$$$ to be the special array.There are two operations that Eric can perform on an array $$$c_t$$$: Operation 1: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-1$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+1]$$$. That operation can only be used on a non-special array, that is when $$$t \neq k$$$.; Operation 2: Choose two integers $$$i$$$ and $$$j$$$ ($$$2 \leq i < j \leq m-2$$$), subtract $$$1$$$ from both $$$c_t[i]$$$ and $$$c_t[j]$$$, and add $$$1$$$ to both $$$c_t[i-1]$$$ and $$$c_t[j+2]$$$. That operation can only be used on a special array, that is when $$$t = k$$$.Note that Eric can't perform an operation if any element of the array will become less than $$$0$$$ after that operation.Now, Eric does the following:  For every non-special array $$$c_i$$$ ($$$i \neq k$$$), Eric uses only operation 1 on it at least once. For the special array $$$c_k$$$, Eric uses only operation 2 on it at least once.Lastly, Eric discards the array $$$b$$$.For given arrays $$$c_1, c_2, \dots, c_n$$$, your task is to find out the special array, i.e. the value $$$k$$$. Also, you need to find the number of times of operation $$$2$$$ was used on it.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$7 \leq m \leq 3 \cdot 10^5$$$) — the number of arrays given to you, and the length of each array. The next $$$n$$$ lines contains $$$m$$$ integers each, $$$c_{i,1}, c_{i,2}, \dots , c_{i,m}$$$. It is guaranteed that each element of the discarded array $$$b$$$ is in the range $$$[0,10^6]$$$, and therefore $$$0 \leq c_{i,j} \leq 3 \cdot 10^{11}$$$ for all possible pairs of $$$(i,j)$$$. It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^6$$$. It is guaranteed that the input is generated according to the procedure above.

For each test case, output one line containing two integers — the index of the special array, and the number of times that Operation 2 was performed on it. It can be shown that under the constraints given in the problem, this value is unique and won't exceed $$$10^{18}$$$, so you can represent it as a $$$64$$$-bit integer. It can also be shown that the index of the special array is uniquely determined. In this problem, hacks are disabled.

NoteIn the first test case, the secret array $$$b$$$ is $$$[0, 1, 1, 1, 1, 1, 1, 1, 0]$$$. Array $$$c_1$$$ and array $$$c_2$$$ are generated by using operation 1. Array $$$c_3$$$ is generated by using operation 2.For Array $$$c_1$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 1 one time to generate it. For Array $$$c_2$$$, you can choose $$$i=6$$$ and $$$j=7$$$ perform Operation 1 one time to generate it. For Array $$$c_3$$$,you can choose $$$i=4$$$ and $$$j=5$$$ perform Operation 2 one time to generate it.In the second test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.In the third test case, the secret array $$$b$$$ is $$$[20, 20, 20, 20, 20, 20, 20, 20, 20]$$$. You can also find that array $$$c_1$$$ and array $$$c_2$$$ are generated by using Operation 1. Array $$$c_3$$$ is generated by using Operation 2.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val m = tokenizer.nextToken().toInt
      val B = new Array[Long](m)
      tokenizer = new StringTokenizer(input.readLine())
      for (j <- 1 to m){
        B(j-1) = tokenizer.nextToken().toInt
      }
      var nom = 0
      var s: Long =0
      for (i <- 1 until n){
        var cou: Long = 0
        tokenizer = new StringTokenizer(input.readLine())
        for (j <- 1 to m){
          cou+=j*(B(j-1) - tokenizer.nextToken().toInt)
        }
        if (cou != 0){
          nom = i
          s = cou
        }
      }
      if (s < 0){
        println((nom+1).toString + " " + (-s).toString)
      }
      else {
        println(1+ " " + (s).toString)
      }
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val m = tokenizer.nextToken().toInt
      val A = Array[Long](-1,-1)
      var l1= 0
      var l2= 0
      for (i <- 1 to n){
        var cou: Long = 0
        tokenizer = new StringTokenizer(input.readLine())
        for (j <- 1 to m){
          cou+=j*tokenizer.nextToken().toInt
        }
        if (!A.contains(cou)){
          if (A(0) == -1){
            A(0) = cou
            l1 = i
          }
          else {
            A(1) = cou
            l2 = i
          }
        }
      }
      if (A(0) > A(1)){
        println(l1.toString+" "+ (A.max - A.min).toString )
      }
      else {
        println(l2.toString+" "+ (A.max - A.min).toString )
      }
    }
  }
}


There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downwards, then to the left and so on). Every time he walks (n + 1) meters, he draws a cross (see picture for clarifications).John Doe stops only when the lower left corner of the square has two crosses. How many crosses will John draw?   The figure shows the order in which John draws crosses for a square with side 4. The lower left square has two crosses. Overall John paints 17 crosses.

The first line contains integer t (1 ≤ t ≤ 104) — the number of test cases.  The second line contains t space-separated integers ni (1 ≤ ni ≤ 109) — the sides of the square for each test sample.

For each test sample print on a single line the answer to it, that is, the number of crosses John will draw as he will move along the square of the corresponding size. Print the answers to the samples in the order in which the samples are given in the input. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

import scala.io.StdIn

object Square {

  def solve(n:Long):Long={
    //find min k: 4*n*k/(n+1)+1
    if ((n+1)%4==0){
      n+1
    }else if ((n+1)%2==0){
      2*n+1
    }else{
      4*n+1
    }
  }

  def solveSquare(in:List[Long]):List[Long]={
    in.map { x => solve(x)}
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val l = StdIn.readLine().split(" ").map { x => x.toLong }
    println(solveSquare(l.toList).mkString("\n"))
  }
}

import java.util.Scanner

object Main {

	def main(args: Array[String]): Unit = {
		val scanner = new Scanner (System.in)
		val t = scanner.nextInt()
		for (i <- 1 to t) {
			val n = scanner.nextLong()
				println (solve (n))
		}
	}

	def solve(n: Long): Long = {
		4*n / gcd(4*n, n+1) + 1
	}

	def gcd(x: Long, y: Long): Long = {
		if (y == 0) x else gcd (y, x % y)
	}

}

object Main {
	def main(args: Array[String]) {
		def gcd(a: Long, b: Long):Long = {
			if (a == b) a
			else if (a == 0) b
			else if (b == 0) a
			else if (a > b) gcd(a%b, b)
			else gcd(b%a, a)
		}
		def lcm(a: Long, b: Long) = a/gcd(a,b)*b
		val calc = (size: Long) => {
			val count = size * 4
			lcm(count, size + 1) / (size + 1) + 1
		}
		val t = Integer.parseInt(readLine())
		val result = readLine().split(' ')
			.map(java.lang.Long.parseLong)
			.map(calc)
		result.foreach(println)
	}
}

import scala.io.StdIn

object Square {

  def solveSquare(in:List[Long]):List[Long]={
    in.map { x =>
      if (x==1) 1
      else if (x==2) 4
      else if (x==3) 4
      else (4*x)+1
    }
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val l = StdIn.readLine().split(" ").map { x => x.toLong }
    println(solveSquare(l.toList).mkString("\n"))
  }
}

import java.util.Scanner

object Main {

	def main(args: Array[String]): Unit = {
		val scanner = new Scanner (System.in)
		val t = scanner.nextInt()
		for (i <- 1 to t) {
			val n = scanner.nextInt()
				println (solve (n))
		}
	}

	def solve(n: Int): Int = {
		4*n / gcd(4*n, n+1) + 1
	}

	def gcd(x: Int, y: Int): Int = {
		if (y == 0) x else gcd (y, x % y)
	}

}

import scala.io.StdIn

object Square {

  def solveSquare(in:List[Int]):List[Int]={
    in.map { x =>
      if (x==1) 1
      else if (x==2) 4
      else if (x==3) 4
      else (4*x)+1
    }
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val l = StdIn.readLine().split(" ").map { x => x.toInt }
    println(solveSquare(l.toList).mkString("\n"))
  }
}


Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble.There is a set $$$S$$$ containing very important numbers on his dad's desk. The minute Johnny heard about it, he decided that it's a good idea to choose a positive integer $$$k$$$ and replace each element $$$s$$$ of the set $$$S$$$ with $$$s \oplus k$$$ ($$$\oplus$$$ denotes the exclusive or operation). Help him choose such $$$k$$$ that Johnny's dad will not see any difference after his son is done playing (i.e. Johnny will get the same set as before playing). It is possible that no such number exists. It is also possible that there are many of them. In such a case, output the smallest one. Note that the order of elements in a set doesn't matter, i.e. set $$$\{1, 2, 3\}$$$ equals to set $$$\{2, 1, 3\}$$$.Formally, find the smallest positive integer $$$k$$$ such that $$$\{s \oplus k | s \in S\} = S$$$ or report that there is no such number.For example, if $$$S = \{1, 3, 4\}$$$ and $$$k = 2$$$, new set will be equal to $$$\{3, 1, 6\}$$$. If $$$S = \{0, 1, 2, 3\}$$$ and $$$k = 1$$$, after playing set will stay the same.

In the first line of input, there is a single integer $$$t$$$ ($$$1 \leq t \leq 1024$$$), the number of test cases. In the next lines, $$$t$$$ test cases follow. Each of them consists of two lines.  In the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1024$$$) denoting the number of elements in set $$$S$$$. Second line consists of $$$n$$$ distinct integers $$$s_i$$$ ($$$0 \leq s_i < 1024$$$), elements of $$$S$$$. It is guaranteed that the sum of $$$n$$$ over all test cases will not exceed $$$1024$$$.

Print $$$t$$$ lines; $$$i$$$-th line should contain the answer to the $$$i$$$-th test case, the minimal positive integer $$$k$$$ satisfying the conditions or $$$-1$$$ if no such $$$k$$$ exists.

NoteIn the first test case, the answer is $$$1$$$ because it is a minimum positive integer and it satisfies all the conditions.

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val t  = sn.reduce(_ ^ _)
    val m  = 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)

    val k = (if (t == 0) (1 to m) else (t to t))
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val t  = sn.reduce(_ ^ _)
    val m  = 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)

    val k = (if (t == 0) (1 to m) else (t to t))
      .view
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val t  = sn.reduce(_ ^ _)

    val k = (if (t == 0) (1 to 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)) else (t to t))
      .view
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val ans = sn match {
      case Array(s1, s2, _*) =>
        (sn.reduce(_ ^ _) to 1024)
          .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }
          .getOrElse(-1)
      case _ => -1
    }

    println(ans)
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s  = sn.reduce(_ ^ _)

    val k = (if (s == 0) (1 to 1024) else (s to s))
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ans = sn match {
      case Array(s1, s2, _*) =>
        (sn.reduce(_ ^ _) to 1024)
          .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }
          .getOrElse(-1)
      case _ => -1
    }

    println(ans)
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val ans = sn match {
      case Array(s1, s2, _*) =>
        List(sn.reduce(_ ^ _), s1, s2)
          .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }
          .getOrElse(-1)
      case _ => -1
    }

    println(ans)
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

    val ans =
      if (sn.length == 1) -1
      else {
        val k = List(sn.reduce(_ ^ _), sn.head, sn.tail.head).filter(_ > 0).head

        if (sn.diff(sn.map(_ ^ k)).nonEmpty) -1
        else k
      }

    println(ans)
  }
}


In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are.

The first line of the input contains a positive integer n (2 ≤ n ≤ 200 000) — the number of cities in Berland. Each of the next n - 1 lines contains two numbers ui, vi, meaning that the i-th road connects city ui and city vi (1 ≤ ui, vi ≤ n, ui ≠ vi).

First print number k — the minimum number of days needed to repair all the roads in Berland. In next k lines print the description of the roads that should be repaired on each of the k days. On the i-th line print first number di — the number of roads that should be repaired on the i-th day, and then di space-separated integers — the numbers of the roads that should be repaired on the i-th day. The roads are numbered according to the order in the input, starting from one. If there are multiple variants, you can print any of them.

NoteIn the first sample you can repair all the roads in two days, for example, if you repair roads 1 and 2 on the first day and road 3 — on the second day.

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val except = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }
  var map = mutable.HashMap.empty[(Int, Int), Int]

  (1 until n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    map += (Math.max(a, b), Math.min(a, b)) -> i
    edges(a) ::= b
    edges(b) ::= a
  }
  val max = edges.maxBy(_.length).length
  var answer = Array.fill[List[Int]](max) { Nil }

  var processing = List(0)
  except(0) = -1

  while (processing.nonEmpty) {
    var nextProcessing = List.empty[Int]
    processing.foreach { i =>
      var n = 1
      edges(i).foreach { j =>
        if (except(j) == 0) {
          if (n == except(i)) n += 1
          except(j) = n
          answer(n - 1) ::= map((Math.max(i, j), Math.min(j, i)))
          n += 1
          nextProcessing ::= j
        }
      }
    }
    processing = nextProcessing
  }

  println(max)
  println(answer.map(j => j.mkString(j.length + " ", " ", "")).mkString("\n"))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt

  case class Edge(to: Int, number: Int)

  val nodes = Array.fill[List[Edge]](n) { Nil }
  val power = Array.ofDim[Int](n)

  var joined = 0

  val data = (1 until n).foreach{ i =>
    val Array(from, to) = in.next().split(' ').map(_.toInt - 1)
    nodes(from) ::= Edge(to, i)
    nodes(to) ::= Edge(from, i)
    power(from) += 1
    power(to) += 1
  }
  var solution = List.empty[List[Int]]

  while (joined != n - 1) {
    val processed = Array.ofDim[Boolean](n)
    var list = List.empty[Int]
    power.zipWithIndex.sorted.foreach {
      case((value, index)) if value == 0 || processed(index) =>
      case((_, index)) =>
        val connected = nodes(index).filterNot(edge => processed(edge.to))
        if (connected.nonEmpty) {
          val connect = connected.maxBy(i => power(i.to))
          processed(index) = true
          processed(connect.to) = true
          power(index) -= 1
          power(connect.to) -= 1
          nodes(index) = nodes(index).filter(_.to != connect.to)
          nodes(connect.to) = nodes(connect.to).filter(_.to != index)
          list ::= connect.number
          joined += 1
        }
    }
    solution ::= list
  }

  println(solution.length)
  println(solution.reverse.map(i => i.mkString(s"${i.length} ", " ", "")).mkString("\n"))

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val roadCounts = Array.fill[Set[Int]](n) { Set.empty }
  var fixed = 0
  var map = Map.empty[(Int, Int), Int]
  (1 until n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    roadCounts(a) += b
    roadCounts(b) += a
    map += (a, b) -> i
    map += (b, a) -> i
  }

  val sorted = roadCounts.indices.sortBy(i => -roadCounts(i).size).toArray
  val max = roadCounts(sorted(0)).size
  var answer = List.empty[List[Int]]
  var a = List.empty[String]

  while (fixed != n - 1) {
    val busy = Array.ofDim[Boolean](n)
    var list = List.empty[Int]
    sorted.foreach { i =>
      if (!busy(i)) {
        val roads = roadCounts(i).filterNot(busy)
        if (roads.nonEmpty) {
          val nJ = roads.maxBy(j => roadCounts(j).size)
          roadCounts(nJ) -= i
          roadCounts(i) -= nJ
          list ::= map(i, nJ) + 1
          busy(i) = true
          busy(nJ) = true
          fixed += 1
        }
      }
    }
    a ::= list.reverse.mkString(list.length + " ", " ", "")
  }

  println(max)
  println(a.reverse.mkString("\n"))
}

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val except = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }
  var map = mutable.HashMap.empty[(Int, Int), Int]
  var answer = Array.ofDim[Int](n - 1)
  (1 until n).foreach { i =>
    val Array(a, b) = in.next().split(' ').map(_.toInt - 1)
    map += (a, b) -> i
    map += (b, a) -> i
    edges(a) ::= b
    edges(b) ::= a
  }

  var processing = List(0)
  except(0) = -1

  while (processing.nonEmpty) {
    var nextProcessing = List.empty[Int]
    processing.foreach { i =>
      var n = 1
      edges(i).foreach { j =>
        if (except(j) == 0) {
          if (n == except(i)) n += 1
          except(j) = n
          answer(map((i, j)) - 1) = n
          n += 1
          nextProcessing ::= j
        }
      }
    }
    processing = nextProcessing
  }

  val groupped = answer.zipWithIndex.groupBy(_._1).toList.sortBy(_._1).map(i => (i._1, i._2.map(_._1)))
  println(groupped.length)
  println(groupped.map(j => j._2.mkString(j._2.length + " ", " ", "")).mkString("\n"))
}