Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 ≤ p < x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of tests Peter is about to make. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), i-th of them stands for the number of vertices in the cycle added before the i-th test.

Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.

NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3.  If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses.  If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt).scanLeft(2) {
    case(a, b) => (a + b + 1) % 2
  }.tail.map(2 - _)
  println(line.toList.mkString("\n"))
}

object B705 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    var player = in(0)%2
    println(player+1)
    for(i <- 1 until n) {
      if(in(i)%2 == 0)
        player = 1 - player
      println(player+1)
    }
  }

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

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

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

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

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

}

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

object _705B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val cycles = read[Vector[Int]]

    var last: Int = 0
    cycles foreach {c =>
      val ans = (last, c%2) match {
        case (0, 0) => 1
        case (0, 1) => 2

        case (1, 0) => 2
        case (1, 1) => 1

        case (2, 0) => 1
        case (2, 1) => 2
      }
      io.writeOnNextLine(ans)
      last = ans
    }

    io
  }
}
/****************************[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 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, until: Int)(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, until: Int)(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
  }
  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
  }
  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 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 testBit(i: Int): Boolean = ((x >> i) & 1) == 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 testBit(i: Int): Boolean = ((x >> i) & 1) == 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 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")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

object Cycles extends App {

  def iter(seq: List[Int], results: List[Int]): List[Int] = seq match {
    case Nil => results
    case x :: xs => iter(xs, (results.headOption.getOrElse(0) + x - 1) % 2 :: results)
  }

  val n: Int = readLine.toInt
  val a: List[Int] = readLine.split(' ').map(_.toInt).toList
  val results = iter(a, Nil)

  results.reverse.map {
    case 0 => 2
    case x => x.abs
  }.foreach(println)

}


Daniel is organizing a football tournament. He has come up with the following tournament format:   In the first several (possibly zero) stages, while the number of teams is even, they split in pairs and play one game for each pair. At each stage the loser of each pair is eliminated (there are no draws). Such stages are held while the number of teams is even.  Eventually there will be an odd number of teams remaining. If there is one team remaining, it will be declared the winner, and the tournament ends. Otherwise each of the remaining teams will play with each other remaining team once in round robin tournament (if there are x teams, there will be  games), and the tournament ends. For example, if there were 20 teams initially, they would begin by playing 10 games. So, 10 teams would be eliminated, and the remaining 10 would play 5 games. Then the remaining 5 teams would play 10 games in a round robin tournament. In total there would be 10+5+10=25 games.Daniel has already booked the stadium for n games. Help him to determine how many teams he should invite so that the tournament needs exactly n games. You should print all possible numbers of teams that will yield exactly n games in ascending order, or -1 if there are no such numbers.

The first line contains a single integer n (1 ≤ n ≤ 1018), the number of games that should be played. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print all possible numbers of invited teams in ascending order, one per line. If exactly n games cannot be played, output one number: -1.

object B extends App {

  def sqrt(number: BigInt) = {
    def next(n: BigInt, i: BigInt): BigInt = (n + i / n) >> 1

    val one = BigInt(1)

    var n = one
    var n1 = next(n, number)

    while ((n1 - n).abs > one) {
      n = n1
      n1 = next(n, number)
    }

    while (n1 * n1 > number) {
      n1 -= one
    }

    n1
  }

  def readString = Console.readLine

  val n = BigInt(readString)

  var T = BigInt(0)
  var found = false

  while (T <= n) {
    val TT = 2 * T - 1
    val D = TT * TT + 8 * n
    val root = sqrt(D)
    if (D.equals(root * root) && (root - TT) % 2 == 0) {
      val i = (root - TT) / 2
      if (i % 2 != 0) {
    	  println(i * (T + 1))
    	  found = true
      }
    }
    T = 2 * T + 1
  }

  if (!found) println(-1)
}


In fact, the problems E1 and E2 do not have much in common. You should probably think of them as two separate problems.A permutation $$$p$$$ of size $$$n$$$ is given. A permutation of size $$$n$$$ is an array of size $$$n$$$ in which each integer from $$$1$$$ to $$$n$$$ occurs exactly once. For example, $$$[1, 4, 3, 2]$$$ and $$$[4, 2, 1, 3]$$$ are correct permutations while $$$[1, 2, 4]$$$ and $$$[1, 2, 2]$$$ are not.Let us consider an empty deque (double-ended queue). A deque is a data structure that supports adding elements to both the beginning and the end. So, if there are elements $$$[1, 5, 2]$$$ currently in the deque, adding an element $$$4$$$ to the beginning will produce the sequence $$$[\color{red}{4}, 1, 5, 2]$$$, and adding same element to the end will produce $$$[1, 5, 2, \color{red}{4}]$$$.The elements of the permutation are sequentially added to the initially empty deque, starting with $$$p_1$$$ and finishing with $$$p_n$$$. Before adding each element to the deque, you may choose whether to add it to the beginning or the end.For example, if we consider a permutation $$$p = [3, 1, 2, 4]$$$, one of the possible sequences of actions looks like this: $$$\quad$$$ 1.add $$$3$$$ to the end of the deque:deque has a sequence $$$[\color{red}{3}]$$$ in it;$$$\quad$$$ 2.add $$$1$$$ to the beginning of the deque:deque has a sequence $$$[\color{red}{1}, 3]$$$ in it;$$$\quad$$$ 3.add $$$2$$$ to the end of the deque:deque has a sequence $$$[1, 3, \color{red}{2}]$$$ in it;$$$\quad$$$ 4.add $$$4$$$ to the end of the deque:deque has a sequence $$$[1, 3, 2, \color{red}{4}]$$$ in it;Find the lexicographically smallest possible sequence of elements in the deque after the entire permutation has been processed. A sequence $$$[x_1, x_2, \ldots, x_n]$$$ is lexicographically smaller than the sequence $$$[y_1, y_2, \ldots, y_n]$$$ if there exists such $$$i \leq n$$$ that $$$x_1 = y_1$$$, $$$x_2 = y_2$$$, $$$\ldots$$$, $$$x_{i - 1} = y_{i - 1}$$$ and $$$x_i < y_i$$$. In other words, if the sequences $$$x$$$ and $$$y$$$ have some (possibly empty) matching prefix, and the next element of the sequence $$$x$$$ is strictly smaller than the corresponding element of the sequence $$$y$$$. For example, the sequence $$$[1, 3, 2, 4]$$$ is smaller than the sequence $$$[1, 3, 4, 2]$$$ because after the two matching elements $$$[1, 3]$$$ in the start the first sequence has an element $$$2$$$ which is smaller than the corresponding element $$$4$$$ in the second sequence.

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 each test case description contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — permutation size. The second line of the description contains $$$n$$$ space-separated integers $$$p_i$$$ ($$$1 \le p_i \le n$$$; all $$$p_i$$$ are all unique) — elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print $$$t$$$ lines, each line containing the answer to the corresponding test case. The answer to a test case should contain $$$n$$$ space-separated integer numbers — the elements of the lexicographically smallest permutation that is possible to find in the deque after executing the described algorithm.

NoteOne of the ways to get a lexicographically smallest permutation $$$[1, 3, 2, 4]$$$ from the permutation $$$[3, 1, 2, 4]$$$ (the first sample test case) is described in the problem statement.

object E1 extends App {

  def permutationMinimizationByDeque(an: List[Int]): List[Int] = {
    require(an.length > 0, "The size of an permutation should be at least 1")

    val (left, right) = an.drop(1).foldLeft((List(an.head), List.empty[Int])) {
      case ((xs @ x :: _, ys), a) if a < x => (a :: xs, ys)
      case ((xs, ys), a)                   => (xs, a :: ys)
    }

    left ++ right.reverse
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n).toList

    val bn = permutationMinimizationByDeque(an)

    out.println(bn.mkString(" "))
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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

object E1 extends App {

  def permutationMinimizationByDeque(an: List[Int]): List[Int] = {
    val (left, right) = an.foldLeft((List.empty[Int], List.empty[Int])) {
      case ((Nil, ys), a)                  => (a :: Nil, ys)
      case ((xs @ x :: _, ys), a) if a < x => (a :: xs, ys)
      case ((xs, ys), a)                   => (xs, a :: ys)
    }

    left ++ right.reverse
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n  = nextInt()
    val an = nextInts(n).toList

    val bn = permutationMinimizationByDeque(an)

    out.println(bn.mkString(" "))
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable._
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(left: Int, right: Int, index: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (left < that.left || (left == that.left && right < that.right))
                return -1
            else if (left == that.left && right == that.right)
                return 0
            else
                return 1
        }
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val left = new ArrayBuffer[Int]()
        val right = new ArrayBuffer[Int]()
        var tmp = 0
        for (i <- 1 to n) {
            tmp = readInt()
            if (left.isEmpty || tmp <= left(left.length-1))
                left.append(tmp)
            else
                right.append(tmp)
        }
        for (i <- left.indices.reverse)
            writer.print(left(i) + " ")
        for (i <- right.indices)
            writer.print(right(i) + " ")
        writer.println()
    }
    writer.flush()
}


New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.

The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.

If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".

NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.

object ProblemA extends App {
    case class Node(
        offset: Int
    )

    def BFS(nodes: Array[Node], startIndex: Int, dstIndex: Int): Boolean = {
        if (startIndex == dstIndex) {
            true
        } else if (nodes(startIndex).offset == -1) {
            false
        } else {
            BFS(nodes, startIndex + nodes(startIndex).offset, dstIndex)
        }
    }

    val line1: String = scala.io.StdIn.readLine
    val line2: String = scala.io.StdIn.readLine

    val total :: dstIndex :: _  = line1.split(" ").map(_.toInt).toList
    val nodes = line2.split(" ").map { x =>
        Node(offset = x.toInt)
    }

    val msg: String = BFS(nodes ++ Array(Node(-1)), 0, dstIndex - 1) match {
        case true => "YES"
        case false => "NO"
    }
    println(msg)
}

import java.util.Scanner

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

var next = 0
for(i <- 0 to (n - 2)) {
val jump = scanner.nextInt()
if(i == next) {
next += jump
if(next == t - 1) {
println("YES")
return
}
}
}

println("NO")
}
}

object NewYearTransportation {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var line=in.readLine()
    val n=line.split(" ")(0).toInt
    val t=line.split(" ")(1).toInt
    line=in.readLine()
    val a:Array[Int]=line.split(" ").map(_.toInt)
    var flag = false
    var i = 1
    while (i <= n - 1 && !flag){
      if(i==t){
        flag=true
      }
      i=i+a(i-1)
    }
    if(i==t){
      flag=true
    }
    println(if(flag) "YES" else "NO")
  }
}

import scala.io.StdIn

object Task500A {
	def main(args: Array[String]) {
		val t = StdIn.readLine().split(" ").map(_.toInt).apply(1)
		val numbers = StdIn.readLine().split(" ").map(_.toInt)
		var position = 1
		while (position < t) position += numbers(position - 1)
		if (position == t) println("YES") else println("NO")
	}
}

import scala.io.StdIn

object NewYearTransport {
  // https://codeforces.com/problemset/problem/500/A
  def main(args: Array[String]): Unit = {
    val (n, t) = StdIn.readLine().split(" ") match {
      case Array(n, t) => (n.toInt, t.toInt)
    }

    val arrA = StdIn.readLine().split(" ").map(_.toInt)

    val res = if (canReach(1, arrA, t)) "YES" else "NO"
    println(res)
  }

  def canReach(i: Int, arr: Array[Int], t: Int): Boolean = {
    if (i == t) true
    else if (i > t) false
    else canReach(i + arr.head, arr.slice(arr.head, arr.length), t)
  }

}

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util.Sorting._
import scala.math._
import scala.collection._
import java.util._

object HelloWorld {
  def main(args: Array[String]): Unit = {
    val Array(n, t) = readLine.split(" ").map(_.toInt)
    val portals = readLine.split(" ").map(_.toInt)

    var current_index = 0
    var possible_to_escape = false
    while (current_index < t - 1 && !possible_to_escape) {
      if ((current_index + 1) + portals(current_index) == t){
        possible_to_escape = true
      }

      current_index += portals(current_index)
    }

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

object A500 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.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))
  }

  def main(args: Array[String]): Unit = {
    var Array(n, t) = readInts(2)
    val input = readInts(n-1)
    var curr = 1

    while(curr-1 < n-1 && curr != t) {
      curr = curr + input(curr-1)
    }
    if(curr == t) println("YES") else println("NO")
  }
}

import scala.collection._

object A extends App {

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

  val Array(n, t) = readInts(2)
  val as = Array(0) ++ readInts(n - 1)

  val q = mutable.Queue(1)
  var can = false

  while (!q.isEmpty) {
    val u = q.dequeue
    if (u == t) can = true
    if (u < n) q.enqueue(u + as(u))
  }

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

import collection.mutable.SortedSet;

object NewYearTransportation {
	def main (args: Array[String]) {
		// Parsing the input
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
		val t = scanner.nextInt() - 1;
		var map = new Array[Int](n);
		for (i <- 0 to n - 2) {
			map(i) = scanner.nextInt();
		}
		map(n-1) = 0;
		// Computation
		var visited = SortedSet[Int]();
		var toVisit = SortedSet[Int](0);
		while (toVisit != SortedSet.empty && !(visited contains t)){
			val elt = toVisit.head;
			toVisit -= elt;
			visited += elt;
			val next = map(elt)+elt;
			if (! (visited contains next))
				toVisit += next
		}
		if (visited contains t)
			println("YES")
			else
				println("NO")
	}
}

object P500A {
	def readInts() : Array[Int] = {
		scala.io.StdIn.readLine.split(" ").map(_.toInt)
	}

	def solve(t: Int, as: Iterable[Int]) : Unit = {
		if (t < 0)
			println("NO")
		else if (t == 0)
			println("YES")
		else
			solve(t - as.head, as.drop(as.head))
	}

	def main(args: Array[String]) {
		val Array(n, t) = readInts()
		val as = readInts().toList
		solve(t - 1, as)
	}
}

object P500A {
	@inline def parseInts(n: Int, line: String) : Array[Int] = {
		val tokenizer = new java.util.StringTokenizer(line)
		Array.fill(n)(tokenizer.nextToken.toInt)
	}

	def solve(t: Int, as: Iterable[Int]) : Unit = {
		if (t > 0)
			solve(t - as.head, as.drop(as.head))
		else if (t == 0)
			println("YES")
		else
			println("NO")
	}

	def main(args: Array[String]) {
		val Array(n, t) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
		val as = parseInts(n - 1, scala.io.StdIn.readLine).toList
		solve(t - 1, as)
	}
}

import Array._
import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
    var cnt = 1
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val a = readLine.split(" ").map(_.toInt)
    while(cnt < m) cnt += a(cnt - 1)
    if(cnt == m){
      println("YES")
    }else println("NO")
  }
}

import java.util.Scanner
import scala.io.StdIn
import Array._
import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
  val cin = new Scanner(System.in)
    val n = cin.nextInt()
    val m = cin.nextInt()
  var cnt = 0
    for( i <- 0 to (n - 2)){
      val s = cin.nextInt()
      if(cnt == i){
      cnt += s
        if(cnt == m - 1){
          println("YES"); return
        }
      }
  }
    println("NO")
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object NewYearTransportation {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def reachable(current: Int, goal: Int, portal: IndexedSeq[Int]) : Boolean = {
     if (current == goal) true
     else if (current > goal) false else reachable(current + portal(current), goal, portal)
   }

   def main(args: Array[String]) {
     val nt = readInts
     val n = nt(0)
     val t = nt(1)  - 1
     val portals = readInts
     if (reachable(0,t,portals)) println("YES") else println("NO")
   }

}

import scala.collection.immutable.IndexedSeq

object Main extends App
{
  def dfs(g:Array[List[Int]], v: Int, used: Set[Int], need:Int): Set[Int] = {
    if(v>need)
      {
        println("NO")
        Set.empty[Int]
      } // печатаем или куда-то сохраняем
    else if(v == need)
      {
        println("YES")
        Set.empty[Int]
      } else
    (for(u <- g(v)) yield u).foldLeft(used){
      (usd, h) =>
        if (!usd.contains(h))
          usd ++ dfs(g, h, usd + h, need) + h
        else usd
    }
  }

def next_dfs(g:Array[List[Int]], v: Int, need:Int):Unit={
    if(v>need)
    {
      println("NO")
      Set.empty[Int]
    } // печатаем или куда-то сохраняем
    else if(v == need)
    {
      println("YES")
      Set.empty[Int]
    } else next_dfs(g, g(v)(0), need)
  }

  override def main(args: Array[String])
  {
    //dfs(input(), 0, Set(0), 4)
    //println(unique_substring(scala.io.StdIn.readLine()).toString())
    val t=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val a=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    //println(a.mkString(","))
    var i=0; // переменная по масиву а
    var con =0;
    var g = new Array[List[Int]](t(0))
    for(v <- 0 to g.length-2)// заполнение графа
    {
        g(v)=List(a(i)+v)
        con=a(i)-1
        i=i+1
    }
    //println(g.mkString(","))
    next_dfs(g, 0, t(1)-1)
  }
}

import scala.io.StdIn._

object Main2 extends App {
  val Array(cellNumber, destination) = readLine().split(" ").map(_.toInt)
  val portals = readLine().split(" ").map(_.toInt)
  val answers = Array.fill(cellNumber + 3)(false)
  answers(0) = true
  for ( i <- 0 until cellNumber-1) {
    if (answers(i)) answers(i + portals(i)) = true
  }
  println(if (answers(destination - 1)) "YES" else "NO")
}

import java.util.Scanner;

object Main extends App {
  var input = new Scanner(System.in)

  var N = input.nextInt()
  var T = input.nextInt()

  var X = new Array[Int](N + 1)

  for (i <- 1 to (N - 1)) {
    X(i) = input.nextInt()
  }

  var pos = 1
  var reach = false

  while (pos <= T) {
    if (pos == T) {
      reach = true
      pos = N + 1;
    } else {
      pos = pos + X(pos)
    }
  }

  if (reach) {
    println("YES")
  } else {
    println("NO")
  }
}

object Solution extends App {
  val Array(n, t) = readLine.split(" ").map(_.toInt)
  val as = readLine.split(" ").map(_.toInt)

  //as.zipWithIndex.map(_._1 + _._2)

  def can(i:Int):Boolean = {
    if(i==t-1)
      true
    else if(i>t-1)
      false
    else
      can(as(i) + i)
  }

  if(can(0))
    println("YES")
  else
    println("NO")
}

import scala.collection.immutable.IndexedSeq

object Main extends App
{
   def input() = {
    val n=scala.io.StdIn.readInt
    for(i <- 1 to n) yield {
          scala.io.StdIn.readLine.split(" ").map(_.toInt)
        }
  }

  def dfs(g:Array[List[Int]], v: Int, used: Set[Int], need:Int): Set[Int] = {
    if(v>need)
      {
        println("NO")
        Set.empty[Int]
      } // печатаем или куда-то сохраняем
    else if(v == need)
      {
        println("YES")
        Set.empty[Int]
      } else
    (for(u <- g(v)) yield u).foldLeft(used){
      (usd, h) =>
        if (!usd.contains(h))
          usd ++ dfs(g, h, usd + h, need) + h
        else usd
    }
  }

  def unique_substring(str:String): List[String] =
  {
    var ret=List.empty[String]
    for(i <- 1 to str.length-1)
      for(j <- 0 to str.length-i)
      {
        val substr=str.substring(j, j+i)
        if (str.indexOf(substr) == j && str.indexOf(substr, j+1) == -1)
          ret=ret.+:(substr)
      }
    ret
  }

  override def main(args: Array[String])
  {
    //dfs(input(), 0, Set(0), 4)
    //println(unique_substring(scala.io.StdIn.readLine()).toString())
    val t=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val a=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    //println(a.mkString(","))
    var i=0; // переменная по масиву а
    var con =0;
    var g = new Array[List[Int]](t(0))
    for(v <- 0 to g.length-1)// заполнение графа
    {
      if(con == 0)
      {
        g(v)=List(a(i)+v)
       //  g(v).+:(a(i)+v)
        con=a(i)-1
        i=i+1
      }
      else con=con-1
    }
    dfs(g, 0, Set(0), t(1))
  }
}

 import java.util.Scanner

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

    var next = 0
    for(i <- 1 to (n - 2)) {
      val jump = scanner.nextInt()
      if(i == next) {
        next += jump
        if(next == t - 1) {
          println("YES")
          return
        }
      }
    }

    println("NO")
  }
}

 import java.util.Scanner

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

    var next = 0
    for(i <- 0 to (n - 5)) {
      val jump = scanner.nextInt()
      if(i == next) {
        next += jump
        if(next == t - 1) {
          println("YES")
          return
        }
      }
    }

    println("NO")
  }
}

object P500A {
	def readInts() : Array[Int] = {
		scala.io.StdIn.readLine.split(" ").map(_.toInt)
	}

	def solve(t: Int, as: Iterable[Int]) : Unit = {
		if (t < 0)
			println("NO")
		else if (t == 0)
			println("YES")
		else
			solve(t - as.head, as.drop(as.head))
	}

	def main(args: Array[String]) {
		val Array(a, t) = readInts()
		val as = readInts()
		solve(t, as)
	}
}

import scala.collection.immutable.IndexedSeq

object Main extends App
{
   def dfs(g:Array[List[Int]], v: Int, used: Set[Int], need:Int): Set[Int] = {
    if(v>need)
      {
        println("NO")
        Set.empty[Int]
      } // печатаем или куда-то сохраняем
    else if(v == need)
      {
        println("YES")
        Set.empty[Int]
      } else
    (for(u <- g(v)) yield u).foldLeft(used){
      (usd, h) =>
        if (!usd.contains(h))
          usd ++ dfs(g, h, usd + h, need) + h
        else usd
    }
  }

  override def main(args: Array[String])
  {
    //dfs(input(), 0, Set(0), 4)
    //println(unique_substring(scala.io.StdIn.readLine()).toString())
    val t=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val a=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    //println(a.mkString(","))
    var i=0; // переменная по масиву а
    var con =0;
    var g = new Array[List[Int]](t(0))
    for(v <- 0 to g.length-1)// заполнение графа
    {
      if(con == 0)
      {
        if(v < t(0)-1)
          g(v)=List(a(i)+v)
        con=a(i)-1
        i=i+1
      }
      else con=con-1
    }
    dfs(g, 0, Set(0), t(1))
  }
}

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

object Main extends App {
  var input = new Scanner(System.in)

  var N = input.nextInt()
  var T = input.nextInt()

  var X = new Array[Int](N)

  for (i <- 1 to (N - 1)) {
    X(i) = input.nextInt()
  }

  var pos = 1
  var reach = false

  while (pos < N - 1) {
    if (pos == T) {
      reach = true
    }
    pos = pos + X(pos)
  }

  if (reach) {
    println("YES")
  } else {
    println("NO")
  }
}

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

object Main extends App {
  var input = new Scanner(System.in)

  var N = input.nextInt()
  var T = input.nextInt()

  var X = new Array[Int](N - 1)

  for (i <- 0 to (N - 2)) {
    X(i) = input.nextInt()
  }

  var pos = 0
  var reach = false

  while (pos < N - 1) {
    if (pos == T - 1) {
      reach = true
    }
    pos = pos + X(pos)
  }

  if (reach) {
    println("YES")
  } else {
    println("NO")
  }
}


The king of Berland organizes a ball! $$$n$$$ pair are invited to the ball, they are numbered from $$$1$$$ to $$$n$$$. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from $$$1$$$ to $$$k$$$, inclusive.Let $$$b_i$$$ be the color of the man's costume and $$$g_i$$$ be the color of the woman's costume in the $$$i$$$-th pair. You have to choose a color for each dancer's costume (i.e. values $$$b_1, b_2, \dots, b_n$$$ and $$$g_1, g_2, \dots g_n$$$) in such a way that:  for every $$$i$$$: $$$b_i$$$ and $$$g_i$$$ are integers between $$$1$$$ and $$$k$$$, inclusive;  there are no two completely identical pairs, i.e. no two indices $$$i, j$$$ ($$$i \ne j$$$) such that $$$b_i = b_j$$$ and $$$g_i = g_j$$$ at the same time;  there is no pair such that the color of the man's costume is the same as the color of the woman's costume in this pair, i.e. $$$b_i \ne g_i$$$ for every $$$i$$$;  for each two consecutive (adjacent) pairs both man's costume colors and woman's costume colors differ, i.e. for every $$$i$$$ from $$$1$$$ to $$$n-1$$$ the conditions $$$b_i \ne b_{i + 1}$$$ and $$$g_i \ne g_{i + 1}$$$ hold. Let's take a look at the examples of bad and good color choosing (for $$$n=4$$$ and $$$k=3$$$, man is the first in a pair and woman is the second):Bad color choosing:   $$$(1, 2)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$, $$$(1, 2)$$$ — contradiction with the second rule (there are equal pairs);  $$$(2, 3)$$$, $$$(1, 1)$$$, $$$(3, 2)$$$, $$$(1, 3)$$$ — contradiction with the third rule (there is a pair with costumes of the same color);  $$$(1, 2)$$$, $$$(2, 3)$$$, $$$(1, 3)$$$, $$$(2, 1)$$$ — contradiction with the fourth rule (there are two consecutive pairs such that colors of costumes of men/women are the same). Good color choosing:   $$$(1, 2)$$$, $$$(2, 1)$$$, $$$(1, 3)$$$, $$$(3, 1)$$$;  $$$(1, 2)$$$, $$$(3, 1)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$;  $$$(3, 1)$$$, $$$(1, 2)$$$, $$$(2, 3)$$$, $$$(3, 2)$$$. You have to find any suitable color choosing or say that no suitable choosing exists.

The only line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n, k \le 2 \cdot 10^5$$$) — the number of pairs and the number of colors.

If it is impossible to find any suitable colors choosing, print "NO". Otherwise print "YES" and then the colors of the costumes of pairs in the next $$$n$$$ lines. The $$$i$$$-th line should contain two integers $$$b_i$$$ and $$$g_i$$$ — colors of costumes of man and woman in the $$$i$$$-th pair, respectively. You can print each letter in any case (upper or lower). For example, "YeS", "no" and "yES" are all acceptable.

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    if (N > M.toLong * (M - 1)) out.println("NO")
    else {
      out.println("YES")
      var cnt = 0
      REP(M - 1, 1) { i =>
        i + 1 to M foreach { j =>
          if (cnt == N) return
          out.println(s"$i $j")
          cnt += 1

          if (cnt == N) return
          out.println(s"$j $i")
          cnt += 1
        }
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

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