You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar!An array $$$a$$$ of length $$$n$$$ is called complete if all elements are positive and don't exceed $$$1000$$$, and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$), $$$a_{x}+a_{y} \neq a_{z}$$$ (not necessarily distinct).You are given one integer $$$n$$$. Please find any complete array of length $$$n$$$. It is guaranteed that under given constraints such array exists.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 1000$$$)  — the number of test cases. Description of the test cases follows. The only line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, print a complete array on a single line. All elements have to be integers between $$$1$$$ and $$$1000$$$ and for all indices $$$x$$$,$$$y$$$,$$$z$$$ ($$$1 \leq x,y,z \leq n$$$) (not necessarily distinct), $$$a_{x}+a_{y} \neq a_{z}$$$ must hold. If multiple solutions exist, you may print any.

NoteIt can be shown that the outputs above are valid for each test case. For example, $$$44+44 \neq 384$$$.Below are some examples of arrays that are NOT complete for the 1st test case:$$$[1,2,3,4,5]$$$ Notice that $$$a_{1}+a_{2} = a_{3}$$$.$$$[1,3000,1,300,1]$$$ Notice that $$$a_{2} = 3000 > 1000$$$.

object CodeforcesRound655a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val n = rl_int
    writer.println(Array.fill(n)(1).mkString(" "))
  }

  def sqr(a: Long): Long = a * a

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

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

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int]
    val ans = Seq.fill(n)(1)
    io.writeAll(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
      }
    }
  }
}

import scala.io.StdIn._

object A extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val n = readInt()
    println((1 to n map (_ => 1)).mkString(" "))
  }

}

import scala.io.StdIn._

object A {

	def main(args: Array[String]) {
		val t = readInt()
		1 to t foreach { _ =>
			val n = readInt()
			println((1 to n map (_ => 1)).mkString(" "))
		}
	}
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  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 t = in.nextInt()
  for (_ <- 1 to t) {
    val n = in.nextInt()
    val res = (1 to n).map(_ => 1).mkString(" ")
    println(res)
  }
}

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

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int]
    val ans = Seq.tabulate(n)(i => 2*i + 1)
    io.writeAll(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
      }
    }
  }
}


The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could have accidentally changed array a, only if array a can be sorted in no more than one operation of swapping elements (not necessarily adjacent). That is, the Little Elephant could have accidentally swapped some two elements.Help the Little Elephant, determine if he could have accidentally changed the array a, sorted by non-decreasing, himself.

The first line contains a single integer n (2 ≤ n ≤ 105) — the size of array a. The next line contains n positive integers, separated by single spaces and not exceeding 109, — array a. Note that the elements of the array are not necessarily distinct numbers.

In a single line print "YES" (without the quotes) if the Little Elephant could have accidentally changed the array himself, and "NO" (without the quotes) otherwise.

NoteIn the first sample the array has already been sorted, so to sort it, we need 0 swap operations, that is not more than 1. Thus, the answer is "YES".In the second sample we can sort the array if we swap elements 1 and 3, so we need 1 swap operation to sort the array. Thus, the answer is "YES".In the third sample we can't sort the array in more than one swap operation, so the answer is "NO".

//package tasks

import java.util.Scanner
import java.io.InputStreamReader
import java.io.BufferedReader

object Krke {
  def main(args: Array[String]) {
    val in = new Scanner(new BufferedReader(new InputStreamReader(System.in)))
    val n = in.nextInt()
    val b = Array.fill(n)(in.nextInt())
    val c = b sortWith (_ < _)
    var cnt = 0
    for (i <- 0 until n)
      if (c(i) != b(i))
        cnt += 1
    if (cnt <= 2)
      print("YES")
    else
      print("NO")
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next()
  val data = in.next().split(' ').map(_.toInt)
  val sorted = data.sorted
  val left = data.indices.find(i => data(i) != sorted(i))
  val right = data.indices.reverse.find(i => data(i) != sorted(i))
  if (left.isEmpty)
    println("YES")
  else {
    val tmp = sorted(left.get)
    sorted(left.get) = sorted(right.get)
    sorted(right.get) = tmp
//    println(sorted.mkString(" "))
//    println(data.mkString(" "))
    if (sorted sameElements data)
      println("YES")
    else
      println("NO")
  }
}

object A220 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val count = in.sorted.zip(in).count{case (a, b) => a != b}
    if(count <=2)
      println("YES")
    else
      println("NO")
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object A220 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val count = in.clone().sorted.zip(in).count{case (a, b) => a != b}
    if(count <=2)
      println("YES")
    else
      println("NO")
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next()
  val data = in.next().split(' ').map(_.toInt)
  val sorted = data.sorted
  val left = data.indices.find(i => data(i) != sorted(i))
  val right = data.indices.reverse.find(i => data(i) != sorted(i))
  if (left.isEmpty)
    println("YES")
  else {
    val tmp = sorted(left.get)
    sorted(left.get) = right.get
    sorted(right.get) = tmp
    if (sorted sameElements data)
      println("YES")
    else
      println("NO")
  }
}


Pig is visiting a friend.Pig's house is located at point 0, and his friend's house is located at point m on an axis.Pig can use teleports to move along the axis.To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost point it can move Pig to, this point is known as the limit of the teleport.Formally, a teleport located at point x with limit y can move Pig from point x to any point within the segment [x; y], including the bounds.  Determine if Pig can visit the friend using teleports only, or he should use his car.

The first line contains two integers n and m (1 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of teleports and the location of the friend's house. The next n lines contain information about teleports. The i-th of these lines contains two integers ai and bi (0 ≤ ai ≤ bi ≤ m), where ai is the location of the i-th teleport, and bi is its limit. It is guaranteed that ai ≥ ai - 1 for every i (2 ≤ i ≤ n).

Print "YES" if there is a path from Pig's house to his friend's house that uses only teleports, and "NO" otherwise. You can print each letter in arbitrary case (upper or lower).

NoteThe first example is shown on the picture below:  Pig can use the first teleport from his house (point 0) to reach point 2, then using the second teleport go from point 2 to point 3, then using the third teleport go from point 3 to point 5, where his friend lives.The second example is shown on the picture below:  You can see that there is no path from Pig's house to his friend's house that uses only teleports.

import java.util

import scala.collection.mutable
import scala.io.StdIn

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  class UF(var size : Int){
    var parents = Array.ofDim[Int](size)
    var sizes = Array.ofDim[Int](size)

    for (i <- 0 until size) {
      parents(i) = i
      sizes(i) = 1
    }

    def findParent(node : Int): Int = {
      var p = node
      while (parents(p) != p) {
        p = parents(p)
      }
      parents(node) = p
      p
    }

    def merge(a : Int, b : Int): Unit = {
      var pA = findParent(a)
      var pB = findParent(b)

      if (pA == pB) {
        return
      }

      if (sizes(pA) < sizes(pB)) {
        parents(pB) = pA
        sizes(pA) += sizes(pB)
      } else {
        parents(pA) = pB
        sizes(pB) += sizes(pA)
      }
    }
  }

  def doCase(): Unit = {
    val Array(n, m) = readIntLine()
    val teleports = (0 until n).map(_ => readIntLine())

    val uf = new UF(m + 1)

    for (t <- teleports) {
      for (i <- t(0) until t(1)) {
        uf.merge(i, t(1))
      }
    }

    if (uf.findParent(0) == uf.findParent(m)) {
      println("YES")
    } else {
      println("NO")
    }
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

}

object A extends App {
  val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  def check(l: List[(Int, Int)], i: Int = 0, j: Int = 0): Boolean =
    if (j >= m) true
    else if (l.isEmpty || l.head._1 < i || l.head._1 > j) false
    else check(l.tail, i min l.head._1, j max l.head._2)

  val l = (0 until n).foldLeft(List.empty[(Int, Int)]) {(l, _) => {
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    (a, b) :: l
  }}.reverse

  if (check(l)) println("YES")
  else println("NO")
}

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

  override def apply(io: IO): io.type = {
    val n, m = io.read[Int]

    val routes = io.read[Set, (Int, Int)](n)

    val table = mutable.Set.empty[(Int, Int)]

    for {
      (i, j) <- routes
      Seq(u, v) <- (i to j).sliding(2) if v <= m
    } table += (u -> v)

    val ans = table.size == m
    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 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]).withDefaultValue(b.apply().result())
    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
      }
    }
  }
}


In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of $$$n$$$ students doing yet another trick. Let's assume that all these students are numbered from $$$1$$$ to $$$n$$$. The teacher came to student $$$a$$$ and put a hole in his badge. The student, however, claimed that the main culprit is some other student $$$p_a$$$.After that, the teacher came to student $$$p_a$$$ and made a hole in his badge as well. The student in reply said that the main culprit was student $$$p_{p_a}$$$.This process went on for a while, but, since the number of students was finite, eventually the teacher came to the student, who already had a hole in his badge.After that, the teacher put a second hole in the student's badge and decided that he is done with this process, and went to the sauna.You don't know the first student who was caught by the teacher. However, you know all the numbers $$$p_i$$$. Your task is to find out for every student $$$a$$$, who would be the student with two holes in the badge if the first caught student was $$$a$$$.

The first line of the input contains the only integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of the naughty students. The second line contains $$$n$$$ integers $$$p_1$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ indicates the student who was reported to the teacher by student $$$i$$$.

For every student $$$a$$$ from $$$1$$$ to $$$n$$$ print which student would receive two holes in the badge, if $$$a$$$ was the first student caught by the teacher.

NoteThe picture corresponds to the first example test case.  When $$$a = 1$$$, the teacher comes to students $$$1$$$, $$$2$$$, $$$3$$$, $$$2$$$, in this order, and the student $$$2$$$ is the one who receives a second hole in his badge.When $$$a = 2$$$, the teacher comes to students $$$2$$$, $$$3$$$, $$$2$$$, and the student $$$2$$$ gets a second hole in his badge. When $$$a = 3$$$, the teacher will visit students $$$3$$$, $$$2$$$, $$$3$$$ with student $$$3$$$ getting a second hole in his badge.For the second example test case it's clear that no matter with whom the teacher starts, that student would be the one who gets the second hole in his badge.

object Badge {
  def main(args: Array[String]): Unit = {
    val in =scala.io.StdIn
    var n=in.readInt()
    val arr=in.readLine().split(" ").map(_.toInt-1)
    for(i<- 0 until n){
      val vis=Array.fill[Boolean](n)(false)
      var j=i
      while (!vis(j)){
        vis(j)=true
        j=arr(j)
      }
      print((j+1)+" ")
    }
    println()
  }
}

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 = ni()
    val P = na(N, -1)

    val cnt = Array.ofDim[Int](N)
    val ans = ArrayBuffer[Int]()
    REP(N) { i =>
      import java.util
      util.Arrays.fill(cnt, 0)
      var p = i
      cnt(p) += 1
      while(cnt(p) < 2) {
        p = P(p)
        cnt(p) += 1
      }
      ans += p
    }

    out.println(ans.map(_+1).mkString(" "))
  }

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

import scala.io.StdIn

object CF503B extends App {
  val n = StdIn.readInt
  val ps = StdIn.readLine.split(' ').map(_.toInt - 1) // 0 index

  def findStudent(student: Int): Int = {
    val holes = Array.fill(n)(false)
    var found = false
    var current = student
    while (!found) {
      if (holes(current)) {
        found = true
        return current
      } else {
        holes(current) = true
        current = ps(current)
      }
    }
    return current
  }

  println((0 until n).map(findStudent(_)+1).mkString(" "))
}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_503_B {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa2)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    val ps = readLine
    val arr = new Array[Int](n+1)
    (1 to n).foreach(arr(_) = ps.int)
//    debug("n = " + n)

    //---------------------------- parameters reading :end
    var res = ""
    for(c <- 1 to n) {
      val marks = new Array[Boolean](n+1)
      var found = false
      var cur = c
      while (!found) {
        if (marks(cur)) {
          found = true
          res += (cur + " ")
        }
        marks(cur) = true
        cur = arr(cur)
      }
    }

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
3
2 3 2
"""

val sa2 = """
3
1 2 3
"""

val sa3 = """
"""
}

}


This is an interactive problem.Ayush devised a new scheme to set the password of his lock. The lock has $$$k$$$ slots where each slot can hold integers from $$$1$$$ to $$$n$$$. The password $$$P$$$ is a sequence of $$$k$$$ integers each in the range $$$[1, n]$$$, $$$i$$$-th element of which goes into the $$$i$$$-th slot of the lock.To set the password of his lock, Ayush comes up with an array $$$A$$$ of $$$n$$$ integers each in the range $$$[1, n]$$$ (not necessarily distinct). He then picks $$$k$$$ non-empty mutually disjoint subsets of indices $$$S_1, S_2, ..., S_k$$$ $$$(S_i \underset{i \neq j} \cap S_j = \emptyset)$$$ and sets his password as $$$P_i = \max\limits_{j \notin S_i} A[j]$$$. In other words, the $$$i$$$-th integer in the password is equal to the maximum over all elements of $$$A$$$ whose indices do not belong to $$$S_i$$$.You are given the subsets of indices chosen by Ayush. You need to guess the password. To make a query, you can choose a non-empty subset of indices of the array and ask the maximum of all elements of the array with index in this subset. You can ask no more than 12 queries.

The first line of the input contains a single integer $$$t$$$ $$$(1 \leq t \leq 10)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ $$$(2 \leq n \leq 1000, 1 \leq k \leq n)$$$ — the size of the array and the number of subsets. $$$k$$$ lines follow. The $$$i$$$-th line contains an integer $$$c$$$ $$$(1 \leq c \lt n)$$$ — the size of subset $$$S_i$$$, followed by $$$c$$$ distinct integers in the range $$$[1, n]$$$  — indices from the subset $$$S_i$$$. It is guaranteed that the intersection of any two subsets is empty.

NoteThe array $$$A$$$ in the example is $$$[1, 2, 3, 4]$$$. The length of the password is $$$2$$$. The first element of the password is the maximum of $$$A[2]$$$, $$$A[4]$$$ (since the first subset contains indices $$$1$$$ and $$$3$$$, we take maximum over remaining indices). The second element of the password is the maximum of $$$A[1]$$$, $$$A[3]$$$ (since the second subset contains indices $$$2$$$, $$$4$$$).Do not forget to read the string "Correct" / "Incorrect" after guessing the password.

//package codeforces.contests._1363

object GuessTheMaximums {

  def ask(seq: Traversable[Int]): Int = {
    val c = seq.size

    println(s"? $c ${seq.mkString(" ")}")
    System.out.flush()

    io.StdIn.readInt()
  }

  def findIndexOfMaximumElement(n: Int): (Int, Int) = {
    val maxValue = ask(1 to n)

    @scala.annotation.tailrec
    def binarySearch(start: Int, end: Int): Int = {
      if (start == end) start
      else {
        val mid = (start + end) / 2

        val key = ask(start to mid)

        if (key == maxValue) binarySearch(start, mid) else binarySearch(mid + 1, end)
      }
    }

    (binarySearch(1, n), maxValue)
  }

  def solve: Boolean = {
    val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
    val subsets = {
      val arr = new Array[Set[Int]](k)
      for (i <- 0 until k) {
        val indices = io.StdIn.readLine.split(" ").map(_.toInt)
        arr(i) = indices.view.tail.toSet
      }
      arr
    }

    val (idx, max) = findIndexOfMaximumElement(n)

    println {
      s"! ${subsets.map(set => if (set(idx)) ask((1 to n).toSet -- set) else max).mkString(" ")}"
    }

    io.StdIn.readLine == "Correct"
  }

  def main(args: Array[String]): Unit = {
    val t = io.StdIn.readInt()
    (1 to t).takeWhile(_ => solve)
  }
}

//package codeforces.contests._1363

object GuessTheMaximums {

  def ask(seq: Traversable[Int]): Int = {
    val c = seq.size

    println(s"? $c ${seq.mkString(" ")}")
    System.out.flush()

    io.StdIn.readInt()
  }

  def findIndexOfMaximumElement(n: Int): (Int, Int) = {
    val maxValue = ask(1 to n)

    @scala.annotation.tailrec
    def binarySearch(start: Int, end: Int): Int = {
      if (start == end) start
      else {
        val mid = (start + end) / 2

        val key = ask(start to mid)

        if (key == maxValue) binarySearch(start, mid) else binarySearch(mid + 1, end)
      }
    }

    (binarySearch(1, n), maxValue)
  }

  def solve: Boolean = {
    val Array(n, k) = io.StdIn.readLine.split(" ").map(_.toInt)
    val subsets = {
      val arr = new Array[Set[Int]](k)
      for (i <- 0 until k) {
        val indices = io.StdIn.readLine.split(" ").map(_.toInt)
        arr(i) = indices.view.tail.toSet
      }
      arr
    }

    val (idx, max) = findIndexOfMaximumElement(n)

    println {
      s"! ${subsets.map(set => if (set(idx)) ask((1 to n).toSet -- set) else max).mkString(" ")}"
    }

    io.StdIn.readLine == "CORRECT"
  }

  def main(args: Array[String]): Unit = {
    val t = io.StdIn.readInt()
    (1 to t).takeWhile(_ => solve)
  }
}


Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow!

The first line contains an odd positive integer n — the exchange rate of currency you all know for today. The length of number n's representation is within range from 2 to 105, inclusive. The representation of n doesn't contain any leading zeroes.

If the information about tomorrow's exchange rate is inconsistent, that is, there is no integer that meets the condition, print  - 1. Otherwise, print the exchange rate of currency you all know against the burle for tomorrow. This should be the maximum possible number of those that are even and that are obtained from today's exchange rate by swapping exactly two digits. Exchange rate representation should not contain leading zeroes.

/**
 * Created by helfper on 27/01/2015.
 */
object AntonAndCurrency {
  def main(args: Array[String]) {
    val n = io.StdIn.readLine.toArray
    println(solve(n))
  }

  def solve(n: Array[Char]): String = {
    val odd = n.last
    val even = n.indexWhere(c => c % 2 == 0 && c < odd)
    val even2 = if (even != -1) even else n.lastIndexWhere(c => c % 2 == 0)
    if (even2 == -1) "-1"
    else {
      n(n.length - 1) = n(even2)
      n(even2) = odd
      n.mkString
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str: Array[Int] = in.next().map(_.asDigit).toArray
  val change = str.last
  var less = str.indexWhere(t => t % 2 == 0 && t < change)
  if (less == -1)
    less = str.lastIndexWhere(_ % 2 == 0)
  if (less == -1) println("-1")
  else {
    str(str.length - 1) = str(less)
    str(less) = change
    println(str.mkString)
  }

}

object B508 {

  import IO._

  def main(args: Array[String]): Unit = {
    val num = read.toCharArray
    val evens = ('0' to '8' by 2).flatMap{x =>
      val first = num.indexWhere(_ == x)
      val last = num.lastIndexWhere(_ == x)
      val set = collection.mutable.Set.empty[Int]
      if(first != -1) set.add(first)
      if(last != -1) set.add(last)
      set
    }

    if(evens.isEmpty) {
      println("-1")
    } else {
      var res = "0"
      for(i <- evens) {
        val n = num
        var temp = n(i)
        n(i) = n(n.length-1)
        n(n.length-1) = temp

        val curr = new String(n)
        if(curr.compareTo(res) > 0)
          res = curr

        temp = n(i)
        n(i) = n(n.length-1)
        n(n.length-1) = temp
      }
      println(res)
    }
  }

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

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

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

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

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

}

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

object B {

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

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

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

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

  def solve: Int = {
    val dollar: Array[Char] = next.toCharArray
    val n = dollar.length
    var ans = false
    var max = ""
    var pos = -1
    var value = '0'
    for (i <- 0 until n) {
      if ((dollar(i) - '0') % 2 == 0 && !ans) {
        val even = dollar(i)
        val end = dollar(n - 1)
        if (end > even) {
          dollar(n - 1) = even
          dollar(i) = end
          max = new String(dollar)
          ans = true
        } else {
          pos = i
          value = even
        }
      }
    }
    if (max == "" && pos != -1) {
      val swap = dollar(n - 1)
      dollar(n - 1) = value
      dollar(pos) = swap
      ans = true
      max = new String(dollar)
    }
    if (ans) {
      out.println(max)
    } else {
      out.println(-1)
    }
    return 1
  }

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object Main {
  def swap(a: mutable.Buffer[Int], i: Int, j: Int): Unit = {
    val tmp = a(i)
    a(i) = a(j)
    a(j) = tmp
  }

  def main(args: Array[String]) {
    val s = io.StdIn.readLine().map(_.toInt - '0').toBuffer
    if (s.count(_ % 2 == 0) == 0)
      println(-1)
    else {
      val index1 = s.indexWhere(x => x % 2 == 0 && x < s.last)
      val index2 = s.lastIndexWhere(x => x % 2 == 0 && x > s.last)
      if (index1 != -1)
        swap(s, index1, s.length - 1)
      else
        swap(s, index2, s.length - 1)
      println(s.mkString(""))
    }
  }
}

object Main extends App {
  val n = readLine.split("").filterNot(_ == "").map(_.toInt).toList
  val last = n.last
  val init = (0, 0)
  val d = n.dropRight(1).zipWithIndex.filter({ case (v, i) => v % 2 == 0 })
  val ni = n.dropRight(1).toArray
  if(d.isEmpty) {
    println("-1")
  } else {
    val (v, pos) = d.filter({ case (v, i) => v < last }).headOption match {
      case Some((v, pos)) => (v, pos)
      case None =>
        d.filter({ case (v, i) => v > last }).last
    }
    ni(pos) = last
    println("%s%d".format(ni.mkString, v))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str: Array[Int] = in.next().map(_.asDigit).toArray
  val change = str.last
  var less = str.indexWhere(t => t % 2 == 0 && t > change)
  if (less == -1)
    less = str.lastIndexWhere(_ % 2 == 0)
  if (less == -1) println("-1")
  else {
    str(str.length - 1) = str(less)
    str(less) = change
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str: Array[Int] = in.next().map(_.asDigit).toArray
  val change = str.last
  var less = str.indexWhere(t => t % 2 == 0 && t > change)
  if (less == -1)
    less = str.lastIndexWhere(_ % 2 == 0)
  if (less == -1) println("-1")
  else {
    str(str.length - 1) = str(less)
    str(less) = change
    println(str.mkString)
  }

}

object B508 {

  import IO._

  def main(args: Array[String]): Unit = {
    val num = read.toCharArray
    val evens = num.zipWithIndex
      .filter{case (x, i) => (x-'0')%2 == 0}
      .map{_._2}

    if(evens.length == 0) {
      println("-1")
    } else {
      var res = BigInt("0")
      for(i <- evens) {
        val n = num
        val temp = n(i)
        n(i) = n.last
        n(n.length-1) = temp

        if(BigInt(n.mkString("")) > res)
          res = BigInt(num.mkString(""))
      }
      println(res.toString)
    }
  }

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

}

object B508 {

  import IO._

  def main(args: Array[String]): Unit = {
    val num = read.toCharArray
    var lastEven = -1
    for(i <- num.length - 1 to 0 by -1 if lastEven == -1) {
      if((num(i)-'0') % 2 == 0)
        lastEven = i
    }
    if(lastEven == -1) {
      println("-1")
    } else if(lastEven != num.length-1){
      val res = num

      val temp = res(lastEven)
      res(lastEven) = res(res.length-1)
      res(res.length-1) = temp

      println(res.mkString(""))
    } else {

      var secondEven = -1
      for(i <- num.length - 2 to 0 by -1 if secondEven == -1) {
        if((num(i)-'0') % 2 == 0 && num(i) != num.last)
          secondEven = i
      }
      if(secondEven == -1) {
        println("-1")
      } else {
        val res = num
        val temp = res(secondEven)
        res(secondEven) = res(res.length-1)
        res(res.length-1) = temp

        println(res.mkString(""))
      }
    }
  }

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

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

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

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

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

}

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

object B {

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

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

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

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

  def solve: Int = {
    val dollar: Array[Char] = next.toCharArray
    val n = dollar.length
    var ans = false
    for (i <- 0 until n) {
      if ((dollar(i) - '0') % 2 == 0) {
        ans = true
        val swap = dollar(n - 1)
        dollar(n - 1) = dollar(i)
        dollar(i) = swap
      }
    }
    if (ans) {
      (0 until n).foreach(i => out.print(dollar(i)))
    } else {
      out.println(-1)
    }
    return 1
  }

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

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

object B {

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

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

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

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

  def solve: Int = {
    val dollar: Array[Char] = next.toCharArray
    val n = dollar.length
    var ans = false
    for (i <- 0 until n ) {
      if ((dollar(i) - '0') % 2 == 0 && !ans) {
        ans = true
        val even = dollar(i)
        val end = dollar(n - 1)
        dollar(n - 1) = even
        dollar(i) = end
      }
    }
    if (ans) {
      (0 until n).foreach(i => out.print(dollar(i)))
    } else {
      out.println(-1)
    }
    return 1
  }

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object Main {
  def swap(a: mutable.Buffer[Int], i: Int, j: Int): Unit = {
    val tmp = a(i)
    a(i) = a(j)
    a(j) = tmp
  }

  def main(args: Array[String]) {
    val s = io.StdIn.readLine().map(_.toInt - '0').toBuffer
    if (s.count(_ % 2 == 0) == 0)
      println(-1)
    else {
      val index1 = s.indexWhere(x => x % 2 == 0 && x > s.last)
      val index2 = s.lastIndexWhere(x => x % 2 == 0 && x < s.last)
      if (index1 != -1)
        swap(s, index1, s.length - 1)
      else
        swap(s, index2, s.length - 1)
      println(s.mkString(""))
    }
  }
}

object Main extends App {
  val n = readLine.split("").filterNot(_ == "").map(_.toInt).toList
  val last = n.last
  val init = (0, 0)
  val d = n.dropRight(1).zipWithIndex.filter({ case (v, i) => v % 2 == 0 })
  val ni = n.dropRight(1).toArray
  if(d.isEmpty) {
    println("-1")
  } else {
    val (v, pos) = d.filter({ case (v, i) => v > last }).headOption match {
      case Some((v, pos)) => (v, pos)
      case None =>
        d.filter({ case (v, i) => v < last }).last
    }
    ni(pos) = last
    println("%s%d".format(ni.mkString, v))
  }
}


You are given two strings $$$s$$$ and $$$t$$$, both of length $$$n$$$. Each character in both string is 'a', 'b' or 'c'.In one move, you can perform one of the following actions:   choose an occurrence of "ab" in $$$s$$$ and replace it with "ba";  choose an occurrence of "bc" in $$$s$$$ and replace it with "cb". You are allowed to perform an arbitrary amount of moves (possibly, zero). Can you change string $$$s$$$ to make it equal to string $$$t$$$?

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of strings $$$s$$$ and $$$t$$$. The second line contains string $$$s$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The third line contains string $$$t$$$ of length $$$n$$$. Each character is 'a', 'b' or 'c'. The sum of $$$n$$$ over all testcases doesn't exceed $$$10^5$$$.

For each testcase, print "YES" if you can change string $$$s$$$ to make it equal to string $$$t$$$ by performing an arbitrary amount of moves (possibly, zero). Otherwise, print "NO".

5

3

cab

cab

1

a

b

6

abbabc

bbaacb

10

bcaabababc

cbbababaac

2

ba

ab

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.max
  import scala.List

  val n = readInt()

  def reread(s: String): String = {
    val s1 = for (l <- s if l != "b"(0)) yield {
      l
    }
    s1
  }

  for (i <- 1 to n) {
    val k = readInt()
    val s = readLine()
    val t = readLine()
    var a = 0
    var c = 0
    var ac = 1
    for (j <- 0 until k) {
      if (s(j) == "a"(0)) {
        a = a + 1
      }
      if (t(j) == "a"(0)) {
        a = a - 1
      }
      if (s(j) == "c"(0)) {
        c = c - 1
      }
      if (t(j) == "c"(0)) {
        c = c + 1
      }
      if ((a < 0) || (c < 0) || (a * c != 0) || (j == k - 1 && a * a + c * c != 0) )
        ac = 0
    }
    if (reread(s) != reread(t)) {
      ac = 0
    }

    if (ac == 0) println("NO")
    else println("YES")
  }
}

object prob1 extends App {

  import scala.io.StdIn
  import scala.math.max
  import scala.List

  val n = readInt()

  def reread(s: String): String = {
    val s1 = for (l <- s if l != "b"(0)) yield {
      l
    }
    s1
  }

  for (i <- 1 to n) {
    val k = readInt()
    val s = readLine()
    val t = readLine()
    var a = 0
    var c = 0
    var ac = 1
    for (j <- 0 to k - 1) {
      if (s(j) == "a"(0)) {
        a = a + 1
      }
      if (t(j) == "a"(0)) {
        a = a - 1
      }
      if (s(j) == "c"(0)) {
        c = c - 1
      }
      if (t(j) == "c"(0)) {
        c = c + 1
      }
      if ((a < 0) || (a > 1) || (c < 0) || (c > 1) || (a * c != 0) || (j == k - 1 && a * a + c * c != 0) )
        ac = 0
    }
    if (reread(s) != reread(t)) {
      ac = 0
    }

    if (ac == 0) println("NO")
    else println("YES")
  }
}

object prob1 extends App {
  import scala.io.StdIn
  import scala.math.max
  import scala.List
  val n = readInt()
  for (i <- 1 to n) {
    val k = readInt()
    val s= readLine()
    val t = readLine()
    var a = 0
    var c = 0
    var ac = 1
    for (j <- 0 to k-1) {
      if (s(j) == "a"(0)) {
        a = a + 1
      }
      if (t(j) == "a"(0)) {
        a = a - 1
      }
      if (s(j) == "c"(0)) {
        c = c - 1
      }
      if (t(j) == "c"(0)) {
        c = c + 1
      }
      if ((a < 0) || (a > 1) || (c < 0) || (c > 1) || (a*c != 0) || (j == k-1 && a*a + c*c !=0))
        ac = 0
    }
    if (ac == 0)
    println("NO")

    else println("YES")
  }
}


Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes exactly one liter per unit distance traveled. Moreover, there are m gas stations located at various points along the way to the district center. The i-th station is located at the point xi on the number line and sells an unlimited amount of fuel at a price of pi dollars per liter. Find the minimum cost Johnny must pay for fuel to successfully complete the delivery.

The first line of input contains three space separated integers d, n, and m (1 ≤ n ≤ d ≤ 109, 1 ≤ m ≤ 200 000) — the total distance to the district center, the volume of the gas tank, and the number of gas stations, respectively. Each of the next m lines contains two integers xi, pi (1 ≤ xi ≤ d - 1, 1 ≤ pi ≤ 106) — the position and cost of gas at the i-th gas station. It is guaranteed that the positions of the gas stations are distinct.

Print a single integer — the minimum cost to complete the delivery. If there is no way to complete the delivery, print -1.

NoteIn the first sample, Johnny's truck holds 4 liters. He can drive 3 units to the first gas station, buy 2 liters of gas there (bringing the tank to 3 liters total), drive 3 more units to the third gas station, buy 4 liters there to fill up his tank, and then drive straight to the district center. His total cost is 2·5 + 4·3 = 22 dollars.In the second sample, there is no way for Johnny to make it to the district center, as his tank cannot hold enough gas to take him from the latest gas station to the district center.

import scala.collection.mutable

object E 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(d, n, m) = readInts(3)

  case class Station(x: Int, p: Int)
  val _stations = Array.ofDim[Station](m + 1)
  for (i <- 0 until m) {
    val Array(x, p) = readInts(2)
    _stations(i) = Station(x, p)
  }
  _stations(m) = Station(d, 0)
  val stations = _stations.sortBy(_.x)

  var price = Array(0)
  var amount = Array(n)
  var pos = 0
  var res = 0L

  for (i <- 0 to m) {
    var consumed = stations(i).x - pos
    var j = 0
    val price1b, amount1b = new mutable.ArrayBuilder.ofInt
//    println(consumed)
//    println(price.mkString(" "))
//    println(amount.mkString(" "))
    while (j < price.length) {
      if (consumed == 0) {
        price1b += price(j)
        amount1b += amount(j)
      } else if (amount(j) > consumed) {
        price1b += price(j)
        amount1b += amount(j) - consumed
        res += consumed.toLong * price(j)
        //println(-i, consumed.toLong, price(j))
        consumed = 0
      } else {
        consumed -= amount(j)
        res += amount(j).toLong * price(j)
        //println(i, amount(j), price(j))
      }
      j += 1
    }
    if (consumed > 0) {
      println(-1)
      System.exit(0)
    }
    j = 0
    val price1 = price1b.result
    val amount1 = amount1b.result
//    println(price1.mkString(" "))
//    println(amount1.mkString(" "))
    val price2b, amount2b = new mutable.ArrayBuilder.ofInt
    var totalAmount = 0
    while (j < price1.length && price1(j) < stations(i).p) {
      price2b += price1(j)
      amount2b += amount1(j)
      totalAmount += amount1(j)
      j += 1
    }
    if (totalAmount < n) {
      price2b += stations(i).p
      amount2b += n - totalAmount
    }
    amount = amount2b.result
    price = price2b.result
    pos = stations(i).x
  }

  println(res)
}

import java.util

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

  case class Station(x: Int, price: Int)
  case class Fuel(price: Int, amount: Int)

  val d, n, m = nextInt
  val stations = Array.fill(m) {
    val x, price = nextInt
    Station(x, price)
  }.sortBy(_.x) :+ Station(d, 0)

  val que = new util.ArrayDeque[Fuel]
  que.addFirst(Fuel(0, n))
  var prevX = 0
  var totalCost = 0L
  var failed = false

  for (station <- stations) {

    var mustConsume = station.x - prevX
    var remainingInTank = n
    while (!que.isEmpty && mustConsume > 0) {
      val f = que.pollFirst()
      val consumed = mustConsume min f.amount
      totalCost += consumed.toLong * f.price
      mustConsume -= consumed
      remainingInTank -= consumed
      if (consumed < f.amount) que.addFirst(Fuel(f.price, f.amount - consumed))
    }
    if (mustConsume > 0) failed = true

    while (!que.isEmpty && que.peekLast.price >= station.price) {
      remainingInTank -= que.pollLast().amount
    }

    que.addLast(Fuel(station.price, n - remainingInTank))

    prevX = station.x
  }

  println(if (failed) -1 else totalCost)

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


The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessary information. Therefore, before the competition started, each computer had its maximum possible data transfer speed measured. On the i-th computer it was ai kilobits per second.There will be k participants competing in the championship, each should get a separate computer. The organizing company does not want any of the participants to have an advantage over the others, so they want to provide the same data transfer speed to each participant's computer. Also, the organizers want to create the most comfortable conditions for the participants, so the data transfer speed on the participants' computers should be as large as possible.The network settings of the R1 company has a special option that lets you to cut the initial maximum data transfer speed of any computer to any lower speed. How should the R1 company configure the network using the described option so that at least k of n computers had the same data transfer speed and the data transfer speed on these computers was as large as possible?

The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 100) — the number of computers and the number of participants, respectively. In the second line you have a space-separated sequence consisting of n integers: a1, a2, ..., an (16 ≤ ai ≤ 32768); number ai denotes the maximum data transfer speed on the i-th computer.

Print a single integer — the maximum Internet speed value. It is guaranteed that the answer to the problem is always an integer.

NoteIn the first test case the organizers can cut the first computer's speed to 30 kilobits. Then two computers (the first and the third one) will have the same speed of 30 kilobits. They should be used as the participants' computers. This answer is optimal.

/**
 * infm, 4/25/14.
 * enjoy ;)
 */
object B {
  val in = {
    val lines = {
      scala.io.Source.stdin.getLines.buffered
      //val bf = new BufferedReader(new InputStreamReader(System.in))
      //Iterator.continually(readLine)
      //Iterator.continually(bf.readLine)
    }
    lines map (_ split ' ') filter (_.nonEmpty) flatten
  }

  //val out = new PrintWriter(System.out)

  def nextInt = in.next().toInt
  def nextLong = in.next().toLong
  def readIntList(n: Int) = Array.fill(n)(nextInt)

  def main(args: Array[String]) {
    val Array(n, k) = readIntList(2)
    val lol = readIntList(n).sorted
    println(lol(n - k))
  }
}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
object B extends App {

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

  val Array(n, k) = readInts(2)
  val as = readInts(n).sorted.reverse

  println(as(k - 1))
}


You are given a tree consisting of $$$n$$$ nodes. You want to write some labels on the tree's edges such that the following conditions hold:  Every label is an integer between $$$0$$$ and $$$n-2$$$ inclusive.  All the written labels are distinct.  The largest value among $$$MEX(u,v)$$$ over all pairs of nodes $$$(u,v)$$$ is as small as possible. Here, $$$MEX(u,v)$$$ denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node $$$u$$$ to node $$$v$$$.

The first line contains the integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — the number of nodes in the tree. Each of the next $$$n-1$$$ lines contains two space-separated integers $$$u$$$ and $$$v$$$ ($$$1 \le u,v \le n$$$) that mean there's an edge between nodes $$$u$$$ and $$$v$$$. It's guaranteed that the given graph is a tree.

Output $$$n-1$$$ integers. The $$$i^{th}$$$ of them will be the number written on the $$$i^{th}$$$ edge (in the input order).

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

import scala.collection.mutable.ListBuffer
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 C628C(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 C628C(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val adj = Array.ofDim[ListBuffer[Int]](n)
    REP(n) { i => adj(i) = new ListBuffer[Int]}
    REP(n-1) { i =>
      val u = ni() - 1
      val v = ni() - 1
      adj(u) += i
      adj(v) += i
    }

    var mxsz = -1
    var vert = -1

    REP(n) { i =>
      if(adj(i).length > mxsz) {
        vert = i
        mxsz = adj(i).length
      }
    }

    val ret = Array.fill[Int](n-1)(-1)
    var id = 0
    adj(vert).foreach{f => ret(f) = id; id +=1}
    REP(n-1) { i =>
      if(ret(i) == -1) {
        ret(i) = id
        id += 1
      }
    }
    ret.foreach(out.println)
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val count = Array.fill(n)(0)
    val edges = ListBuffer.empty[Edge]
    val g = Array.fill(n)(ListBuffer.empty[Edge])
    (1 until n).foreach{ _ =>
      val a = in.nextInt()-1
      val b = in.nextInt()-1
      val e = new Edge(a,b)
      edges.append(e)
      count(a) += 1
      count(b) += 1
      g(a).append(e)
      g(b).append(e)
    }

    val maxNode = count.max
    val i = count.indexWhere(_ == maxNode)

    var label = 0
    g(i).foreach(e => {
      e.label = label
      label += 1
    })
    edges.foreach(e => if(e.label == -1) {
      e.label = label
      label += 1
    })

    val res = edges.map(_.label).mkString(System.lineSeparator())

    out.println(res)

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


Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are $$$n$$$ players arranged in a circle, so that for all $$$j$$$ such that $$$2 \leq j \leq n$$$, player $$$j - 1$$$ is to the left of the player $$$j$$$, and player $$$j$$$ is to the right of player $$$j - 1$$$. Additionally, player $$$n$$$ is to the left of player $$$1$$$, and player $$$1$$$ is to the right of player $$$n$$$.Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either $$$0$$$, $$$1$$$, or $$$2$$$ other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly $$$1$$$ other player, then they should logically attack that player in response. If instead a player is being attacked by $$$0$$$ or $$$2$$$ other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players.Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the $$$n$$$ players in the game to make them instead attack another player  — i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The descriptions of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$3 \leq n \leq 2 \cdot 10^5$$$)  — the amount of players (and therefore beds) in this game of Bed Wars. The second line of each test case contains a string $$$s$$$ of length $$$n$$$. The $$$j$$$-th character of $$$s$$$ is equal to L if the $$$j$$$-th player is attacking the player to their left, and R if the $$$j$$$-th player is attacking the player to their right. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy. It can be proven that it is always possible for Omkar to achieve this under the given constraints.

5
4
RLRL
6
LRRRRL
8
RLLRRRLL
12
LLLLRRLRRRLL
5
RRRRR

NoteIn the first test case, players $$$1$$$ and $$$2$$$ are attacking each other, and players $$$3$$$ and $$$4$$$ are attacking each other. Each player is being attacked by exactly $$$1$$$ other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer $$$0$$$.In the second test case, not every player acts logically: for example, player $$$3$$$ is attacked only by player $$$2$$$, but doesn't attack him in response. Omkar can talk to player $$$3$$$ to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer $$$1$$$.

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      var s = nextLine
      var res = 0

      if (s.distinct.size == 1) {
        if (n > 2) {
          res = (n + 2) / 3
        }
      } else {
        val sl = s.takeWhile(_ == s.last)
        val sr = s.dropWhile(_ == s.last)
        s = sr + sl

        var prev = s(0)
        var cnt = 1
        for (i <- 1 until n) {
          if (s(i) == prev) {
            cnt += 1
          } else {
            res += cnt / 3
            prev = s(i)
            cnt = 1
          }
        }
        res += cnt / 3
      }

      out.println(res)
      out.flush()
    }

  }

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

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val s = nextLine

      var prev = s.last
      var cnt = 1
      var res = 0
      for (i <- 0 until n) {
        if (s(i) == prev) {
          cnt += 1
        } else {
          res += (cnt - 1) / 2
          prev = s(i)
          cnt = 1
        }
      }
      res += (cnt - 1) / 2

      out.println(res)
    }

    out.flush()
  }

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

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      var s = nextLine
      var res = 0

      if (s.distinct.size == 1) {
        if (n > 2) {
          res = n / 2
        }
      } else {
        val sl = s.takeWhile(_ == s.last)
        val sr = s.dropWhile(_ == s.last)
        s = sr + sl

        var prev = s(0)
        var cnt = 1
        for (i <- 1 until n) {
          if (s(i) == prev) {
            cnt += 1
          } else {
            res += cnt / 3
            prev = s(i)
            cnt = 1
          }
        }
        res += cnt / 3
      }

      out.println(res)
    }

    out.flush()
  }

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

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      var s = nextLine
      val sl = s.takeWhile(_ == s.last)
      val sr = s.dropWhile(_ == s.last)
      s = sr + sl

      var prev = s.last
      var cnt = 1
      var res = 0
      for (i <- 0 until n) {
        if (s(i) == prev) {
          cnt += 1
        } else {
          res += cnt / 3
          prev = s(i)
          cnt = 1
        }
      }
      res += cnt / 3

      out.println(res)
    }

    out.flush()
  }

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


Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button.Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connected to it by a wire, increase by one.Valera and Ignat started having a dispute, the dispute is as follows. Ignat thought of a sequence of n integers a1, a2, ..., an. Valera should choose some set of distinct counters and press buttons on each of them exactly once (on other counters the buttons won't be pressed). If after that there is a counter with the number i, which has value ai, then Valera loses the dispute, otherwise he wins the dispute.Help Valera to determine on which counters he needs to press a button to win the dispute.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105), that denote the number of counters Valera has and the number of pairs of counters connected by wires. Each of the following m lines contains two space-separated integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that mean that counters with numbers ui and vi are connected by a wire. It is guaranteed that each pair of connected counters occurs exactly once in the input. The last line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 105), where ai is the value that Ignat choose for the i-th counter.

If Valera can't win the dispute print in the first line -1. Otherwise, print in the first line integer k (0 ≤ k ≤ n). In the second line print k distinct space-separated integers — the numbers of the counters, where Valera should push buttons to win the dispute, in arbitrary order. If there exists multiple answers, you are allowed to print any of them.

object D{
  import scala.collection.mutable.{Queue=>Mqueue}

  def main(args: Array[String]){

    val (n,m)={
      val sp=readLine.split(" ")
      (sp(0).toInt,sp(1).toInt)
    }

    val g={
      val gg= Array.fill(n)(List[Int]())

      for(_<- 1 to m){
        val sp=readLine.split(" ")
        val (u,v)=(sp(0).toInt-1,sp(1).toInt-1)
        gg(u)::=v
        gg(v)::=u
      }
      gg
    }

    val a=readLine.split(" ").map(_.toInt)

    val list={
      var list=List[Int]()
      val now=Array.fill(n)(0)
      val q=new Mqueue[Int]()
      for(i<- 0 until n if(a(i)==0)){
        q.enqueue(i)
      }
      while(q.size>0){
        val idx=q.dequeue
        if(now(idx)==a(idx)){
          list::=idx
          now(idx)+=1
          g(idx).foreach{ii=>
            now(ii)+=1
            if(now(ii)==a(ii)){
              q.enqueue(ii)
            }
          }
        }
      }
      list
    }

    println(list.size)
    println(list.map(_+1).mkString(" "))
  }
}