Phone number in Berland is a sequence of n digits. Often, to make it easier to memorize the number, it is divided into groups of two or three digits. For example, the phone number 1198733 is easier to remember as 11-987-33. Your task is to find for a given phone number any of its divisions into groups of two or three digits.

The first line contains integer n (2 ≤ n ≤ 100) — amount of digits in the phone number. The second line contains n digits — the phone number to divide into groups.

Output any of divisions of the given phone number into groups of two or three digits. Separate groups by single character -. If the answer is not unique, output any.

object P025B {
  def main(argv: Array[String]) = {
    val n = readInt
    var s = readLine
    val firstWidth = n % 2 + 2
    print(s.slice(0, firstWidth))
    s = s.drop(firstWidth)
    while (s.length() > 0) {
      print('-' + s.slice(0, 2))
      s = s.drop(2)
    }
    println()
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next()
  if (n % 2 == 0)
    println(line.grouped(2).mkString("-"))
  else
    println((line.take(3) :: line.drop(3).grouped(2).toList).mkString("-"))
}

object PhoneNo {
  def main(args: Array[String]) {
    val n = io.StdIn.readLine.toInt
    val p = io.StdIn.readLine
    if (n < 4) {
      println(p)
      return
    }
    for (i<-0 until n-3 by 2) {
      print(p.substring(i,i+2) + '-')
    }
    if (n%2 == 0) println(p.substring(n-2))
    else println(p.substring(n-3))
  }
}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var number = readLine;
    if (n == 2 || n == 3) {
      println(number);
      return;
    }
    var beginInd = 0;
    if (n % 2 != 0) {
      print(number(0).toString + number(1).toString + number(2).toString);
      beginInd = 3;
      if (n > 3) {
        print("-");
      }
    }
    for (i <- beginInd until n) {
      print(number(i));
      if (beginInd == 3) {
        if (i % 2 == 0 && i < n - 1) {
	      print("-");
	    }
      } else {
        if (i % 2 > 0 && i < n - 1) {
	      print("-");
	    }
      }

    }
  }

}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var number = readLine.toCharArray();
    if (n == 2 || n == 3) {
      println(number);
      return;
    }
    var beginInd = 0;
    if (n % 2 != 0) {
      print(number(0).toString + number(1).toString + number(2).toString);
      beginInd = 3;
      if (n > 3) {
        print("-");
      }
    }
    for (i <- beginInd until n) {
      print(number(i));
      if (beginInd == 3) {
        if (i % 2 == 0 && i < n - 1) {
	      print("-");
	    }
      } else {
        if (i % 2 > 0 && i < n - 1) {
	      print("-");
	    }
      }

    }
  }

}


Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.Bob gave you all the values of ai, j that he wrote down. Your job is to reconstruct any permutation that could have generated these values. The input will be formed so that it is guaranteed that there is at least one solution that is consistent with the information given.

The first line of the input will contain a single integer n (2 ≤ n ≤ 50). The next n lines will contain the values of ai, j. The j-th number on the i-th line will represent ai, j. The i-th number on the i-th line will be 0. It's guaranteed that ai, j = aj, i and there is at least one solution consistent with the information given.

Print n space separated integers, which represents a permutation that could have generated these values. If there are multiple possible solutions, print any of them.

NoteIn the first case, the answer can be {1, 2} or {2, 1}.In the second case, another possible answer is {2, 4, 5, 1, 3}.

/**
  * Created by octavian on 30/01/2016.
  */
object GuessPerm {

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

    //System.setIn(new FileInputStream("./src/guessPerm.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/guessPerm.out")))

    val n = readInt()
    var mtx = Array.ofDim[Int](n, 0)

    //println("n is " + n)
    for(i <- 0 until n) {
      mtx(i) = readLine().split(" ").map(_.toInt)
      //println("mtx of " + i + " is " + mtx(i).mkString(" "))
    }

    var result = Array.ofDim[Int](n)
    var madeMax: Boolean = false
    for(i <- 0 until n) {
      result(i) = mtx(i).max
      //println("result of " + i + " is " + result(i))
      if(result(i) == n - 1 && madeMax == false) {
        result(i) = n
        madeMax = true
      }
    }

    println(result.mkString(" "))
  }
}

import scala.collection.mutable

object B341 {
  def main(args: Array[String]) {
    val n = scala.io.StdIn.readInt
    val a = (1 to n).map(q => scala.io.StdIn.readLine.split(" ").map(_.toInt).max).to[mutable.MutableList]
    a(a.indexOf(n-1)) = n
    println(a.mkString(" "))
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  var found = false
  val data = (1 to n).map{_ =>
    val res = in.next().split(' ').map(_.toInt).max
    if (res == n - 1 && !found) {
      found = true
      n
    } else res
  }
  println(data.mkString(" "))
}

import scala.collection._

object B extends App {

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

  val Array(n) = readInts(1)
  val as = Array.fill(n) { readInts(n) }

  val res = Array.fill(n) { 0 }
  for (i <- 1 to n) {
    var maxCnt = -1
    var maxPos = -1
    for (j <- 0 until n) {
      val cnt = as(j).count(_ == i)
      if (cnt > maxCnt && res(j) == 0) {
        maxCnt = cnt
        maxPos = j
      }
    }
    //println(i, maxPos, maxCnt)
    res(maxPos) = i
  }

  println(res.mkString(" "))
}

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

object _618B extends CodeForcesApp {
  override type Result = Seq[Int]

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    var c = n-2
    (1 to n) map {i =>
      val nums = Seq.fill(n)(nextInt()).groupBy(identity).mapValues(_.size)
      nums.maxBy(_._2) match {
        case (_, 1) =>
          c = c + 1
          c
        case (x, _) => x
      }
    }
  }

  override def format(result: Seq[Int]) = result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

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

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

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

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

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

import java.util.Scanner

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

    val perm = Array.ofDim[Int](n, n)

    for(i <- 0 until n)
      for(j <- 0 until n)
        perm(i)(j) = sc.nextInt()

    //
    var flag = false

    val z = perm(0).max
    if(z == n-1){
      flag = true
      print(z)
    }
    else
      print(z)

    for(i <- 1 until n){
      val a = perm(i).max
      print(' ')

      if(a == n-1){
        if(flag)
          print(n)
        else{
          flag = true
          print(n-1)
        }
      }
      else
        print(a)
    }

    println()
  }
}

object Runner {

  def main(args: Array[String]) = {
    val n = readLine.toInt
    var res = List[Int]()
    for (i <- 0 until n) {
      val numbers = readLine().split(" ").map(_.toInt)
      var max: Option[Int] = Option.empty
      for (j <- 0 until numbers.size) {
        if (!j.equals(i)) {
          if (max.isEmpty || max.get < numbers(j)) {
            max = Option(numbers(j))
          }
        }
      }
      res = res :+ max.get
    }
    var flag = false
    var str = new StringBuilder()
    for (i <- 0 until res.size) {
      var a = res(i)
      if (!flag && a == n - 1) {
        flag = true
        a = a + 1
      }
      str.append(a)
      if (i != res.size - 1) {
        str.append(" ")
      }
    }
    println(str)
  }
}

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

object CF2016_B {

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

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

    //---------------------------- parameters reading --------------------------
    br = setupInputOutput();
    val line1 = readLine
    val n = line1.int
    val arr = Array.ofDim[Int](n, n)

    for (i <- 0 until n) {
      val line = readLine
      for(j <- 0 until n) {
        arr(i)(j) = line.int
      }
    }

    val res = new Array[Int](n+1)
    for (d <- 1 to n) {
      var maxLine = -1
      var maxCount = 0
      for (i <- 0 until n) {
        var count = 0
        for (j <- 0 until n) {
          if (arr(i)(j) == d) {
        	  count += 1
          }
        }
        if (maxCount < count) {
          maxLine = i
          maxCount = count
        }
      }
      if (maxLine != -1) {
       res(d) = maxLine + 1
      }
    }

    val res2 = new Array[Int](n+1)
    for(i <- 1 to n) {
      val place = res(i)
      res2(place) = i
    }
    for(i <- 1 to n) {
      if (res2(i) == 0) {
        res2(i) = n
      }
    }

    for(i <- 1 to n) {
    	print(res2(i) + " ")
    }

    //---------------------------- parameters reading end ----------------------

  }

  //---------------------------- service code ----------------------------------

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  var debugV = false
  var is = System.in
  var br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

//============================================================================================
object Test {

val sa1 = """
5
0 2 2 1 2
2 0 4 1 3
2 4 0 1 3
1 1 1 0 1
2 3 3 1 0
"""

}

}

object Runner {

  def main(args: Array[String]) = {
    val n = readLine.toInt
    var res = List[Int]()
    for (i <- 0 until n) {
      val numbers = readLine().split(" ").map(_.toInt)
      var max: Option[Int] = Option.empty
      for (j <- 0 until numbers.size) {
        if (!j.equals(i)) {
          if (max.isEmpty || max.get < numbers(j)) {
            max = Option(numbers(j))
          }
        }
      }
      res = res :+ max.get
    }
    var str = new StringBuilder()
    for (i <- 0 until res.size) {
      str.append(res(i))
      if (i != res.size - 1) {
        str.append(" ")
      }
    }
    println(str)
  }
}


There is a given sequence of integers a1, a2, ..., an, where every number is from 1 to 3 inclusively. You have to replace the minimum number of numbers in it so that all the numbers in the sequence are equal to each other.

The first line contains an integer n (1 ≤ n ≤ 106). The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 3).

Print the minimum number of replacements needed to be performed to make all the numbers in the sequence equal.

NoteIn the example all the numbers equal to 1 and 3 should be replaced by 2.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').groupBy(identity).map(_._2.length).max
  println(n - line)
}


Riley is a very bad boy, but at the same time, he is a yo-yo master. So, he decided to use his yo-yo skills to annoy his friend Anton.Anton's room can be represented as a grid with $$$n$$$ rows and $$$m$$$ columns. Let $$$(i, j)$$$ denote the cell in row $$$i$$$ and column $$$j$$$. Anton is currently standing at position $$$(i, j)$$$ in his room. To annoy Anton, Riley decided to throw exactly two yo-yos in cells of the room (they can be in the same cell).Because Anton doesn't like yo-yos thrown on the floor, he has to pick up both of them and return back to the initial position. The distance travelled by Anton is the shortest path that goes through the positions of both yo-yos and returns back to $$$(i, j)$$$ by travelling only to adjacent by side cells. That is, if he is in cell $$$(x, y)$$$ then he can travel to the cells $$$(x + 1, y)$$$, $$$(x - 1, y)$$$, $$$(x, y + 1)$$$ and $$$(x, y - 1)$$$ in one step (if a cell with those coordinates exists).Riley is wondering where he should throw these two yo-yos so that the distance travelled by Anton is maximized. But because he is very busy, he asked you to tell him.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of each test case contains four integers $$$n$$$, $$$m$$$, $$$i$$$, $$$j$$$ ($$$1 \leq n, m \leq 10^9$$$, $$$1\le i\le n$$$, $$$1\le j\le m$$$) — the dimensions of the room, and the cell at which Anton is currently standing.

For each test case, print four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \leq x_1, x_2 \leq n$$$, $$$1\le y_1, y_2\le m$$$) — the coordinates of where the two yo-yos should be thrown. They will be thrown at coordinates $$$(x_1,y_1)$$$ and $$$(x_2,y_2)$$$. If there are multiple answers, you may print any.

NoteHere is a visualization of the first test case.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m, i, j) = readLine().split(" ").map(_.toInt)

    println(s"1 1 $n $m")
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m, i, j) = readLine().split(" ").map(_.toInt)

    val (x1, y1) = (if (i - 1 < n - i) n else 1, if (j - 1 < m - j) m else 1)
    val (x2, y2) = (if (x1 == n) 1 else n, if (y1 == m) 1 else m)

    println(s"$x1 $y1 $x2 $y2")
  }
}

import java.io.PrintWriter
import java.util.Scanner

object Solution {
  def solve(n: Int, m: Int, i: Int, j: Int): (Int, Int, Int, Int) = {
    // he goes to one, then to second, and then come back
    // |x1-x2| + |y1-y2| <- anyway between yoyos
    // either
    //   |x1-i| + |y1-j| + |x2-i| + |y2-j|
    // or
    //   |x2-i| + |y2-j| + |x1-i| + |y1-j|
    // so no difference. i.e. it's always
    // |x1-x2| + |y1-y2| + |x1-i| + |y1-j| + |x2-i| + |y2-j|
    // i.e.
    // |x1-x2| + |x1-i| + |x2-i| +
    // |y1-y2| + |y1-j| + |y2-j| - so it's independent on coordinates
    // so seems like it's always 1 and max
    (1, 1, n, m)
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    val (x1, y1, x2, y2) = solve(input.nextInt(), input.nextInt(), input.nextInt(), input.nextInt())
    output.println(s"$x1 $y1 $x2 $y2")
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m, i, j) = readLine().split(" ").map(_.toInt)

    println("1 1 n m")
  }
}


You are given the array $$$a$$$ consisting of $$$n$$$ positive (greater than zero) integers.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) such that the absolute difference between $$$a_i$$$ and $$$a_j$$$ is no more than one ($$$|a_i - a_j| \le 1$$$) and remove the smallest of these two elements. If two elements are equal, you can remove any of them (but exactly one).Your task is to find if it is possible to obtain the array consisting of only one element using several (possibly, zero) such moves or not.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

For each test case, print the answer: "YES" if it is possible to obtain the array consisting of only one element using several (possibly, zero) moves described in the problem statement, or "NO" otherwise.

NoteIn the first test case of the example, we can perform the following sequence of moves:  choose $$$i=1$$$ and $$$j=3$$$ and remove $$$a_i$$$ (so $$$a$$$ becomes $$$[2; 2]$$$);  choose $$$i=1$$$ and $$$j=2$$$ and remove $$$a_j$$$ (so $$$a$$$ becomes $$$[2]$$$). In the second test case of the example, we can choose any possible $$$i$$$ and $$$j$$$ any move and it doesn't matter which element we remove.In the third test case of the example, there is no way to get rid of $$$2$$$ and $$$4$$$.

import scala.io.Source
// http://codeforces.com/problemset/problem/1399/A
object RemoveSmallest1399A extends App {
  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//  val lines: Iterator[String] =
//    Source.fromString("5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100").getLines
  val ntc: Int = lines.next.toInt
  0 until ntc map { _ =>
    handleTC()
  } foreach println

  def handleTC() = {
    if (lines.next.toInt == 1) {
      lines.next
      "YES"
    } else {
      val ints = lines.next.split(" ").map(_.toInt)
      if (solve(ints)) "YES" else "NO"
    }
  }

  def solve(inAr: Array[Int]) = {
    val s = inAr.sorted
    s.zip(s.tail).forall { case (i, j) =>
      j - i <= 1
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val arr = StdIn.readLine().split(" ").map(_.toInt).toList.sorted
      val flag = (arr.head :: arr).zip(arr).forall(p => math.abs(p._1 - p._2) <= 1)
      if (flag) println("YES") else println("NO")
    }
  }
}

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

import scala.collection.mutable

object A {

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

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

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

  def nextInt: Int = Integer.parseInt(next)

  def nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

  def nextDouble: Double = java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      map.getOrDefault(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = map.firstKey()

    def last(): T = map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Unit = {
    val t = nextInt
    for (_ <- 0 until t) {
      val n = nextInt
      val arr = new Array[Int](n)
      for (i <- 0 until n) {
        arr(i) = nextInt

      }
      val sorted = arr.sorted
      var flag = true
      for (i <- 1 until n) {
        if (sorted(i) - sorted(i - 1) > 1)
          flag = false
      }
      if (flag) {
        out.println("YES")
      } else {
        out.println("NO")
      }

    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val as = io.read[Seq[Int]].sorted
    val ans = as.sliding(2) forall {
      case Seq(a, b) => (b - a) <= 1
      case _ => true
    }
    io.write(ans.toEnglish.toUpperCase)
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[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")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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

//package codeforces.contests._1399

object RemoveSmallest {

  def main(args: Array[String]): Unit = {
    for (t <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()
      val arr = io.StdIn.readLine.split(" ").map(_.toInt).sorted

      val doFollow = arr.foldLeft((true, arr.head)) { case ((acc, prev), e) => if (acc) (e - prev <= 1, e) else (false, e) }._1

      if (doFollow) println("YES") else println("NO")
    }
  }

}

import scala.concurrent.duration.DurationInt
import scala.concurrent._
import scala.io.Source
// http://codeforces.com/problemset/problem/1399/A
object RemoveSmallest1399A extends App {
  val lines: Iterator[String] = Source.fromInputStream(System.in).getLines
//  val lines: Iterator[String] =
//    Source.fromString("5\n3\n1 2 2\n4\n5 5 5 5\n3\n1 2 4\n4\n1 3 4 4\n1\n100").getLines
  val ntc: Int = lines.next.toInt
  implicit val global: ExecutionContextExecutor = ExecutionContext.global
  val resSeq: Seq[Future[String]] = 0 until ntc map { _ =>
    handleTC()
  }
  Await.result(Future.sequence(resSeq), 100.second).foreach(println)

  def handleTC(): Future[String] = {
    val al = lines.next.toInt
    val ints = lines.next.split(" ").map(_.toInt)
    Future {
      if (ints.length == 1) ("YES")
      else {
        if (solve(ints).isDefined) ("YES") else ("NO")
      }
    }
  }

  def solve(inAr: Array[Int]): Option[Array[Int]] = {
    if (inAr.length == 1) Some(inAr)
    else children(inAr).flatMap(solve).headOption
  }

  def children(inAr: Array[Int]): Stream[Array[Int]] = {
    def removeElementAt(arr: Array[Int], ind: Int) =
      arr.zipWithIndex.filterNot { case (_, in) => in == ind }.map(_._1)

    (0 until inAr.length - 1).toStream
      .zip((1 until inAr.length).toStream).flatMap { case (i, j: Int) =>
      println(s"$i, $j")
      if (inAr(i) - inAr(j) == 1) Array(removeElementAt(inAr, j))
      else if (inAr(i) - inAr(j) == -1) Array(removeElementAt(inAr, i))
      else if (inAr(i) - inAr(j) == 0) Array(
        removeElementAt(inAr, i),
        removeElementAt(inAr, j)
      )
      else Array[Array[Int]]()
    }
  }

}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    for (_ <- 1 to t) {
      val _ = StdIn.readLine().trim.toInt
      val arr = StdIn.readLine().split(" ").map(_.toInt).toList
      val flag = (arr.head :: arr).zip(arr).forall(p => math.abs(p._1 - p._2) <= 1)
      if (flag) println("YES") else println("NO")
    }
  }
}


In the Main Berland Bank n people stand in a queue at the cashier, everyone knows his/her height hi, and the heights of the other people in the queue. Each of them keeps in mind number ai — how many people who are taller than him/her and stand in queue in front of him.After a while the cashier has a lunch break and the people in the queue seat on the chairs in the waiting room in a random order.When the lunch break was over, it turned out that nobody can remember the exact order of the people in the queue, but everyone remembers his number ai.Your task is to restore the order in which the people stood in the queue if it is possible. There may be several acceptable orders, but you need to find any of them. Also, you need to print a possible set of numbers hi — the heights of people in the queue, so that the numbers ai are correct.

The first input line contains integer n — the number of people in the queue (1 ≤ n ≤ 3000). Then n lines contain descriptions of the people as "namei ai" (one description on one line), where namei is a non-empty string consisting of lowercase Latin letters whose length does not exceed 10 characters (the i-th person's name), ai is an integer (0 ≤ ai ≤ n - 1), that represents the number of people who are higher and stand in the queue in front of person i. It is guaranteed that all names are different.

If there's no acceptable order of the people in the queue, print the single line containing "-1" without the quotes. Otherwise, print in n lines the people as "namei hi", where hi is the integer from 1 to 109 (inclusive), the possible height of a man whose name is namei. Print the people in the order in which they stand in the queue, starting from the head of the queue and moving to its tail. Numbers hi are not necessarily unique.

import collection.mutable.ArrayBuffer

object Main {

    def deal() = {
        val tmp = readLine split ' '
        (tmp(1).toInt, tmp(0))
    }

    def main(args: Array[String]) {
        val n = readInt()
        val data = (for (i <- 0 until n) yield deal()).sorted
        val order = new ArrayBuffer[String]()
        try {
            for (item <- data)
                order.insert(item _1, item _2)
            val map = new collection.mutable.HashMap[String, Int]
            for (i <- 0 until n)
                map += (order(i) -> (n - i))
            for (item <- data)
                println(item._2 + ' ' + map(item._2))
        }
        catch {
            case ex : Exception => println("-1")
        }
    }

}


You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis.

The first line contains a single positive integer n (2 ≤ n ≤ 105). The following n lines contain coordinates of the points. The i-th of these lines contains two single integers xi and yi (|xi|, |yi| ≤ 109, xi ≠ 0). No two points coincide.

Print "Yes" if there is such a point, "No" — otherwise. You can print every letter in any case (upper or lower).

NoteIn the first example the second point can be removed.In the second example there is no suitable for the condition point.In the third example any point can be removed.

object a900 {
  def main(args: Array[String]): Unit = {
    val (a, b) = scala.io.Source.stdin.getLines() drop 1 map (_ split (" ") map (_.toInt)) partition (_ (0) < 0)
    println(
      (a.length, b.length) match {
        case (0, _) | (_, 0) | (1, _) | (_, 1) => "Yes"
        case _ => "No"
      }
    )
  }
}

import java.util.Scanner

object FindExtraOne {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val xs = for (i <- 0.until(N); (x, y) = (sc.nextInt(), sc.nextInt())) yield x

    val xsPartitions = xs.partition(_ > 0)
    val exists = xsPartitions._1.length <= 1 || xsPartitions._2.length <= 1

    println(if (exists) "Yes" else "No")
  }
}

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

  override def apply(io: IO): io.type = {
    val points = io.read[Vector[(Int, Int)]]
    val (left, right) = points.partition({case (x, y) => x < 0})
    val ans = (left.size <= 1) || (right.size <= 1)
    io.write(ans.toEnglish)
  }
}
/****************************[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()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int = 0, until: Int = a.length)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def getBit(i: Int): Int = (x >> i) & 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def getBit(i: Int): Long = (x >> i) & 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative.getOrElse(f)   //e.g. students.indexOf("Greg").whenNegative(Int.MaxValue)
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of 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 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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    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
      }
    }
  }
}


It turns out that the meaning of life is a permutation $$$p_1, p_2, \ldots, p_n$$$ of the integers $$$1, 2, \ldots, n$$$ ($$$2 \leq n \leq 100$$$). Omkar, having created all life, knows this permutation, and will allow you to figure it out using some queries.A query consists of an array $$$a_1, a_2, \ldots, a_n$$$ of integers between $$$1$$$ and $$$n$$$. $$$a$$$ is not required to be a permutation. Omkar will first compute the pairwise sum of $$$a$$$ and $$$p$$$, meaning that he will compute an array $$$s$$$ where $$$s_j = p_j + a_j$$$ for all $$$j = 1, 2, \ldots, n$$$. Then, he will find the smallest index $$$k$$$ such that $$$s_k$$$ occurs more than once in $$$s$$$, and answer with $$$k$$$. If there is no such index $$$k$$$, then he will answer with $$$0$$$.You can perform at most $$$2n$$$ queries. Figure out the meaning of life $$$p$$$.

NoteIn the sample, the hidden permutation $$$p$$$ is $$$[3, 2, 1, 5, 4]$$$. Three queries were made.The first query is $$$a = [4, 4, 2, 3, 2]$$$. This yields $$$s = [3 + 4, 2 + 4, 1 + 2, 5 + 3, 4 + 2] = [7, 6, 3, 8, 6]$$$. $$$6$$$ is the only number that appears more than once, and it appears first at index $$$2$$$, making the answer to the query $$$2$$$.The second query is $$$a = [3, 5, 1, 5, 5]$$$. This yields $$$s = [3 + 3, 2 + 5, 1 + 1, 5 + 5, 4 + 5] = [6, 7, 2, 10, 9]$$$. There are no numbers that appear more than once here, so the answer to the query is $$$0$$$.The third query is $$$a = [5, 2, 4, 3, 1]$$$. This yields $$$s = [3 + 5, 2 + 2, 1 + 4, 5 + 3, 4 + 1] = [8, 4, 5, 8, 5]$$$. $$$5$$$ and $$$8$$$ both occur more than once here. $$$5$$$ first appears at index $$$3$$$, while $$$8$$$ first appears at index $$$1$$$, and $$$1 < 3$$$, making the answer to the query $$$1$$$.Note that the sample is only meant to provide an example of how the interaction works; it is not guaranteed that the above queries represent a correct strategy with which to determine the answer.

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = 1// readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val d = new Array[Int](n+1)
        var k = 0
        for (i <- 2 to n) {
            writer.print('?')
            for (j <- 2 to n)
                writer.print(" " + i)
            writer.println(" " + 1)
            writer.flush()
            d(readInt()) = 1 - i
        }
        for (i <- 1 until n) {
            writer.print('?')
            for (j <- 2 to n)
                writer.print(" " +i)
            writer.println(" " + n)
            writer.flush()
            d(readInt()) = n - i
        }
        var diff = 0
        for (i <- 1 to n)
            diff = min(diff, d(i))
        writer.print('!')
        for (i <- 1 to n) {
            writer.print(" " + (d(i) - diff + 1))
        }
        writer.println()
    }
    writer.flush()
}


You are given two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 100$$$). Represent the number $$$n$$$ as the sum of $$$k$$$ positive integers of the same parity (have the same remainder when divided by $$$2$$$).In other words, find $$$a_1, a_2, \ldots, a_k$$$ such that all $$$a_i>0$$$, $$$n = a_1 + a_2 + \ldots + a_k$$$ and either all $$$a_i$$$ are even or all $$$a_i$$$ are odd at the same time.If such a representation does not exist, then report it.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the input. Next, $$$t$$$ test cases are given, one per line. Each test case is two positive integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$k$$$ ($$$1 \le k \le 100$$$).

For each test case print:   YES and the required values $$$a_i$$$, if the answer exists (if there are several answers, print any of them);  NO if the answer does not exist.  The letters in the words YES and NO can be printed in any case.

import scala.io.StdIn

object B {

   def solution(n: Int, k: Int): Option[Seq[Int]] = {
     lazy val with1 = Some((n - 1 * (k - 1)) +: Seq.fill(k - 1)(1))
       .filter(_.head > 0)
       .filter(_.head % 2 == 1)
     lazy val with2 = Some((n - 2 * (k - 1)) +: Seq.fill(k - 1)(2))
       .filter(_.head > 0)
       .filter(_.head % 2 == 0)
     with1.orElse(with2)
   }

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine.toInt)) {
         val Seq(n, k) = StdIn.readLine.split(" ").toSeq.map(_.toInt)
         solution(n, k) match {
            case Some(seq) =>
             println("YES")
             println(seq.mkString(" "))
            case None =>
             println("NO")
         }
      }
   }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C640B(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class C640B(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val k = ni()

      if(n % 2 == 0) {
        if(k % 2 != 0) {
          val x = 2 * (k - 1)
          if(x >= n) {
            out.println("NO")
          } else {
            out.println("YES")
            0 until (k-1) foreach (_ => out.print("2 "))
            out.println(n-x)
          }
        } else {
          val x = k-1
          if(x >= n) {
            out.println("NO")
          } else {
            out.println("YES")
            0 until (k-1) foreach (_ => out.print("1 "))
            out.println(n-x)
          }
        }
      } else {
        if(k % 2 == 0) {
          out.println("NO")
        } else {
          val x = k - 1
          if(x >= n) {
            out.println("NO")
          } else {
            out.println("YES")
            0 until (k-1) foreach (_ => out.print("1 "))
            out.println(n-x)
          }
        }
      }
    }
  }
}

object B extends App {

  private def summands(n: Int, k: Int): List[List[Int]] =
    List(1, 2)
      .map(r => (r, n - r * (k - 1)))
      .collect {
        case (r, d) if d > 0 && d % 2 == r % 2 => d :: List.fill(k - 1)(r)
      }

  val t = scala.io.StdIn.readInt()

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

    val ak = summands(n, k)

    if (ak.isEmpty) println("NO")
    else {
      println("YES")
      println(ak.head.mkString(" "))
    }
  }
}

object B extends App {
  private def summands(n: Int, k: Int): List[List[Int]] =
    List(1, 2).map(r => (r, n - r * (k - 1))).collect {
      case (r, d) if d > 0 && d % 2 == r % 2 => d :: List.fill(k - 1)(r)
    }

  val t = scala.io.StdIn.readInt()

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

    val ak = summands(n, k)

    if (ak.isEmpty) println("NO")
    else {
      println("YES")
      println(ak.head.mkString(" "))
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val n, k = io.read[Int]

    val ans = for {
      member <- Seq(1, 2)
      residue = n - member*(k - 1)
      if residue > 0 && residue%2 == member%2
    } yield Seq.fill(k-1)(member) :+ residue

    ans.headOption match {
      case Some(seq) => io.writeLine("YES").writeAll(seq)
      case _ => io.writeLine("NO")
    }
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[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")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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 ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val n = in.nextInt()

  def solve(n: Integer, k: Integer): Unit = {
    val result: List[Int] = {
      if (n % 2 == 0 && k % 2 == 1) {
        (n - (k - 1) * 2) :: (1 until k).map(_ => 2).toList
      } else if ((n % 2 == 1 && k % 2 == 1) || (n % 2 == 0)) {
        (n - (k - 1)) :: ((1 until k).map(_ => 1)).toList
      } else {
        List(-1)
      }
    }

    if (result.head <= 0) {
      println("NO")
    } else {
      println("YES")
      println(result.mkString(" "))
    }
  }

  for (i <- 1 to n) {
    val n = in.nextInt()
    val k = in.nextInt()

    solve(n, k)
  }

}

object B extends App {

  private def summands(n: Int, k: Int): List[List[Int]] =
    List(1, 2)
      .map(r => (r, n - r * (k - 1)))
      .collect {
        case (r, d) if d % 2 == r % 2 => d :: List.fill(k - 1)(r)
      }

  val t = scala.io.StdIn.readInt()

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

    val ak = summands(n, k)

    if (ak.isEmpty) println("NO")
    else {
      println("YES")
      println(ak.head.mkString(" "))
    }
  }
}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val n = in.nextInt()

  def solve(n: Integer, k: Integer): Unit = {
    val result: List[Int] = {
      if (n % 2 == 0 && k % 2 == 1) {
        (n - (k - 1) * 2) :: (1 until k).map(_ => 2).toList
      } else if ((n % 2 == 1 && k % 2 == 1) || (n % 2 == 0)) {
        (n - (k - 1)) :: ((1 until k).map(_ => 1)).toList
      } else {
        List(-1)
      }
    }

    if (result.head < 0) {
      println("NO")
    } else {
      println("YES")
      println(result.mkString(" "))
    }
  }

  for (i <- 1 to n) {
    val n = in.nextInt()
    val k = in.nextInt()

    solve(n, k)
  }

}


Vasya has the sequence consisting of n integers. Vasya consider the pair of integers x and y k-interesting, if their binary representation differs from each other exactly in k bits. For example, if k = 2, the pair of integers x = 5 and y = 3 is k-interesting, because their binary representation x=101 and y=011 differs exactly in two bits.Vasya wants to know how many pairs of indexes (i, j) are in his sequence so that i < j and the pair of integers ai and aj is k-interesting. Your task is to help Vasya and determine this number.

The first line contains two integers n and k (2 ≤ n ≤ 105, 0 ≤ k ≤ 14) — the number of integers in Vasya's sequence and the number of bits in which integers in k-interesting pair should differ. The second line contains the sequence a1, a2, ..., an (0 ≤ ai ≤ 104), which Vasya has.

Print the number of pairs (i, j) so that i < j and the pair of integers ai and aj is k-interesting.

NoteIn the first test there are 4 k-interesting pairs:  (1, 3),  (1, 4),  (2, 3),  (2, 4). In the second test k = 0. Consequently, integers in any k-interesting pair should be equal to themselves. Thus, for the second test there are 6 k-interesting pairs:  (1, 5),  (1, 6),  (2, 3),  (2, 4),  (3, 4),  (5, 6).

import scala.collection.mutable.ListBuffer
import scala.util.Random

/**
  * Created by netman on 3/4/17.
  */
object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.fromInputStream(System.in).getLines().toArray
    val Array(n, k) = lines(0).split(" ").map(_.toInt)
    val MaxValue = 1 << 14
    val cntBits = Array.ofDim[Int](MaxValue)
    for (i <- 1 until MaxValue) {
      cntBits(i) = cntBits(i >> 1) + (i & 1)
    }
    val rnd = new Random
    val arr = lines(1).split(" ").map(_.toInt)
    val cnt = Array.ofDim[Int](MaxValue)
    arr.foreach(cnt(_) += 1)
    if (k == 0) {
      var res = 0L
      for (i <- cnt.indices) {
        res += (cnt(i).toLong * (cnt(i) - 1).toLong) / 2
      }
      println(res)
    } else {
      val tmp = ListBuffer.empty[Int]
      for (mask <- cntBits.indices) {
        if (cntBits(mask) == k) tmp += mask
      }
      val lst = tmp.toArray
      var res = 0L
      for (mask <- cnt.indices) {
        if (cnt(mask) != 0) {
          for (other <- lst) {
            res += cnt(mask ^ other).toLong * cnt(mask).toLong
          }
        }
      }
      println(res / 2)
    }
  }
}

import scala.io.StdIn

/**
  * Created by Aleksei Latyshev on 04.03.2017.
  */
object D extends App {
  val Array(n, k) = StdIn.readLine().split(" ").map(_.toInt)
  val a = Array.ofDim[Int](1 << 14 + 1)
  StdIn.readLine().split(" ").map(_.toInt).foreach(x => a(x) += 1)
  if (k != 0) {
    val b: Seq[Int] = (1 until (1 << 14)).filter(x => Integer.bitCount(x) == k)
    println(a.take(10001).zipWithIndex.map {
      case (c, x) => b.map(y => a(y ^ x)).sum.toLong * c
    }.sum / 2)
  } else {
    println(a.map(x => x.toLong * (x - 1) / 2).sum)
  }
}

import scala.collection.mutable.ListBuffer

/**
  * Created by netman on 3/4/17.
  */
object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.fromInputStream(System.in).getLines().toArray
    val Array(n, k) = lines(0).split(" ").map(_.toInt)
    val MaxValue = 1 << 14
    val cntBits = Array.ofDim[Int](MaxValue)
    for (i <- 1 until MaxValue) {
      cntBits(i) = cntBits(i >> 1) + (i & 1)
    }
    val arr = lines(1).split(" ").map(_.toInt)
    val cnt = Array.ofDim[Int](MaxValue)
    arr.foreach(cnt(_) += 1)
    if (k == 0) {
      var res = 0L
      for (i <- cnt.indices) {
        res += (cnt(i).toLong * (cnt(i) - 1)) / 2
      }
      println(res)
    } else {
      val tmp = ListBuffer.empty[Int]
      for (mask <- cntBits.indices) {
        if (cntBits(mask) == k) tmp += mask
      }
      val lst = tmp.toArray
      var res = 0L
      for (mask <- cnt.indices) {
        if (cnt(mask) != 0) {
          for (other <- lst) {
            res += cnt(mask ^ other)
          }
        }
      }
      println(res / 2)
    }
  }
}


Polycarp doesn't like integers that are divisible by $$$3$$$ or end with the digit $$$3$$$ in their decimal representation. Integers that meet both conditions are disliked by Polycarp, too.Polycarp starts to write out the positive (greater than $$$0$$$) integers which he likes: $$$1, 2, 4, 5, 7, 8, 10, 11, 14, 16, \dots$$$. Output the $$$k$$$-th element of this sequence (the elements are numbered from $$$1$$$).

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 1000$$$).

For each test case, output in a separate line one integer $$$x$$$ — the $$$k$$$-th element of the sequence that was written out by Polycarp.

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

  lazy val xn: Stream[Int] = Stream.iterate(1)(_ + 1).filterNot(x => x % 3 == 0 || (x % 10) == 3)

  val t = readInt()

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

    val ans = xn(k - 1)

    println(ans)
  }
}

import java.io._
import java.util.Scanner
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = new Scanner(System.in)
    val writer =  new PrintWriter(System.out)

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val n = reader.nextInt()
        var i = 0
        var k = 1L
        while (true) {
            if (k % 3 != 0 && k % 10 != 3) {
                i += 1
                if (i == n) {
                    writer.println(k)
                    return
                }
            }
            k += 1
        }
    }

    def multiTest(f: Int => Unit): Unit = {
        val t = reader.nextInt()
        for (i <- 1 to t) f(i)
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
        writer.flush()
    }
}


Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems — the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is string slsl + 1... sr.String x = x1x2... xp is lexicographically smaller than string y = y1y2... yq, if either p < q and x1 = y1, x2 = y2, ... , xp = yp, or there exists such number r (r < p, r < q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1. The string characters are compared by their ASCII codes.

The first line contains integer n (1 ≤ n ≤ 30) — the number of titles you've got to consider. Then follow n problem titles, one per line. Each title only consists of lowercase English letters (specifically, it doesn't contain any spaces) and has the length from 1 to 20, inclusive.

Print a string, consisting of lowercase English letters — the lexicographically minimum shortest original title.

5
threehorses
goodsubstrings
secret
primematrix
beautifulyear

NoteIn the first sample the first 9 letters of the English alphabet (a, b, c, d, e, f, g, h, i) occur in the problem titles, so the answer is letter j.In the second sample the titles contain 26 English letters, so the shortest original title cannot have length 1. Title aa occurs as a substring in the first title.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val names = (1 to n).map(_ => in.next())

  def next(str: String) = {
    if (str.forall(_ == 'z'))
      "a" * (str.length + 1)
    else {
      val postfix = str.reverse.takeWhile(_ == 'z').reverse
      val increment = str(str.length - postfix.length - 1)
      str.take(str.length - 1 - postfix.length) + (increment + 1).toChar + "a" * postfix.length
    }
  }

  def isNew(str: String) = {
    !names.exists(_.contains(str))
  }
  var candidate = "a"

  while (!isNew(candidate)) candidate = next(candidate)
  println(candidate)
}

object Main {
  val chars = "abcdefghijklmnopqrstuvwxyz".map(_.toString)

  def main(args: Array[String]) {
    val n = readInt()
    val a = for(_ <- 1 to n) yield { readLine() }
    val str = (chars ++ chars.flatMap(c => chars.map(c + _))).find(s => a.find(_.contains(s)).isEmpty)
    println(str.get)
  }
}


These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts $$$1$$$ minute.He was asked to insert one takeoff in the schedule. The takeoff takes $$$1$$$ minute itself, but for safety reasons there should be a time space between the takeoff and any landing of at least $$$s$$$ minutes from both sides.Find the earliest time when Arkady can insert the takeoff.

The first line of input contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 100$$$, $$$1 \le s \le 60$$$) — the number of landings on the schedule and the minimum allowed time (in minutes) between a landing and a takeoff. Each of next $$$n$$$ lines contains two integers $$$h$$$ and $$$m$$$ ($$$0 \le h \le 23$$$, $$$0 \le m \le 59$$$) — the time, in hours and minutes, when a plane will land, starting from current moment (i. e. the current time is $$$0$$$ $$$0$$$). These times are given in increasing order.

Print two integers $$$h$$$ and $$$m$$$ — the hour and the minute from the current moment of the earliest time Arkady can insert the takeoff.

NoteIn the first example note that there is not enough time between 1:20 and 3:21, because each landing and the takeoff take one minute.In the second example there is no gaps in the schedule, so Arkady can only add takeoff after all landings. Note that it is possible that one should wait more than $$$24$$$ hours to insert the takeoff.In the third example Arkady can insert the takeoff even between the first landing.

object CF967A extends App {
  import scala.io.Source

  //val src = Source.fromFile("data.txt")
  val src = Source.stdin
  val lines = src.getLines

  def readInts(): Array[Int] =  {
    val line = if (lines.hasNext) lines.next else null
    if (line == null) throw new RuntimeException("Premature end of source encountered")
    line.split(" ").map(x => x.toInt)
  }

  val Array(nLandingTimes, gap) = readInts()
  val landingTimesMins = (0 until nLandingTimes).map(x => readInts()).map {ar => 60 * ar(0) + ar(1) }
  val interval = landingTimesMins.zip(landingTimesMins.tail).find { case (m,n) => n - m >= 2 * gap + 2}

  val takeOffTime = {
    if (gap + 1 <= landingTimesMins(0)) 0
    else interval match {
      case Some((m, n)) => m + gap + 1
      case None => landingTimesMins.last + gap + 1
    }
  }
  println(takeOffTime/60 + " " + takeOffTime % 60)

}

object CF967A extends App {
  import scala.io.Source

  //val src = Source.fromFile("data.txt")
  val src = Source.stdin
  val lines = src.getLines

  def readInts(): Array[Int] =  {
    val line = if (lines.hasNext) lines.next else null
    if (line == null) throw new RuntimeException("Premature end of source encountered")
    line.split(" ").map(x => x.toInt)
  }

  val Array(nLandingTimes, gap) = readInts()
  val landingTimesMins = (0 until nLandingTimes).map(x => readInts()).map {ar => 60 * ar(0) + ar(1) }
  val interval = landingTimesMins.zip(landingTimesMins.tail).find { case (m,n) => n - m > 2 * gap + 2}

  val takeOffTime = {
    if (gap + 1 <= landingTimesMins(0)) 0
    else interval match {
      case Some((m, n)) => m + gap + 1
      case None => landingTimesMins.last + gap + 1
    }
  }
  println(takeOffTime/60 + " " + takeOffTime % 60)

}


You are given a keyboard that consists of $$$26$$$ keys. The keys are arranged sequentially in one row in a certain order. Each key corresponds to a unique lowercase Latin letter.You have to type the word $$$s$$$ on this keyboard. It also consists only of lowercase Latin letters.To type a word, you need to type all its letters consecutively one by one. To type each letter you must position your hand exactly over the corresponding key and press it.Moving the hand between the keys takes time which is equal to the absolute value of the difference between positions of these keys (the keys are numbered from left to right). No time is spent on pressing the keys and on placing your hand over the first letter of the word.For example, consider a keyboard where the letters from 'a' to 'z' are arranged in consecutive alphabetical order. The letters 'h', 'e', 'l' and 'o' then are on the positions $$$8$$$, $$$5$$$, $$$12$$$ and $$$15$$$, respectively. Therefore, it will take $$$|5 - 8| + |12 - 5| + |12 - 12| + |15 - 12| = 13$$$ units of time to type the word "hello". Determine how long it will take to print the word $$$s$$$.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The next $$$2t$$$ lines contain descriptions of the test cases. The first line of a description contains a keyboard — a string of length $$$26$$$, which consists only of lowercase Latin letters. Each of the letters from 'a' to 'z' appears exactly once on the keyboard. The second line of the description contains the word $$$s$$$. The word has a length from $$$1$$$ to $$$50$$$ letters inclusive and consists of lowercase Latin letters.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to the test case is the minimal time it takes to type the word $$$s$$$ on the given keyboard.

5
abcdefghijklmnopqrstuvwxyz
hello
abcdefghijklmnopqrstuvwxyz
i
abcdefghijklmnopqrstuvwxyz
codeforces
qwertyuiopasdfghjklzxcvbnm
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq
qwertyuiopasdfghjklzxcvbnm
abacaba

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var value: Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return value.compareTo(that.value)
        }
    }

    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val keys = readString()
        val ind = mutable.Map[Char, Int]()
        val s = readString()
        for (i <- keys.indices) {
            ind(keys(i)) = i
        }
        var ans = 0
        for (i <- 1 until s.length) {
            ans += abs(ind(s(i)) - ind(s(i-1)))
        }
        writer.println(ans)
    }
    writer.flush()
}

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

  override def solve(io: IO) = {
    val inputs = io.read[Seq[(String, String)]]
    inputs foreach { case (_keyboard, target) =>
      val keyboard = _keyboard.toVector
      val ans = target.map(keyboard.indexOf(_))
        .sliding(2)
        .map({
          case Seq(a, b) => (a - b).abs
          case _ => 0
        })
        .sum
      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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[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")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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