PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?

The first line contains single integer n (1 ≤ n ≤ 104) — the number of Balls living in the forest. The second line contains a sequence p1, p2, ..., pn of length n, where (1 ≤ pi ≤ n) holds and pi denotes the most distant from Ball i relative living on the same tree. If there are several most distant relatives living on the same tree, pi is the id of one with the smallest id. It's guaranteed that the sequence p corresponds to some valid forest. Hacking: To hack someone, you should provide a correct forest as a test. The sequence p will be calculated according to the forest and given to the solution you try to hack as input. Use the following format: In the first line, output the integer n (1 ≤ n ≤ 104) — the number of Balls and the integer m (0 ≤ m < n) — the total number of edges in the forest. Then m lines should follow. The i-th of them should contain two integers ai and bi and represent an edge between vertices in which relatives ai and bi live. For example, the first sample is written as follows: 5 31 23 44 5

You should output the number of trees in the forest where PolandBall lives.

NoteIn the first sample testcase, possible forest is: 1-2 3-4-5. There are 2 trees overall.In the second sample testcase, the only possible graph is one vertex and no edges. Therefore, there is only one tree.

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

object _755C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val input = read[Vector[Int]]
    val ds = new UnionFind[Int]
    (1 to input.length).foreach(i => ds += i)

    input.zipWithIndex foreach {
      case (i, j) => ds.union(i, j + 1)
    }

    write(ds.sets.size)
  }

  class UnionFind[A] extends PartialFunction[A, A] with collection.generic.Growable[A] {
    private[this] val parent = mutable.Map.empty[A, A]

    private[this] def find(x: A): A = parent(x) match {
      case `x` => x
      case y =>
        parent(x) = find(y)
        parent(x)
    }

    override def isDefinedAt(x: A) = parent contains x

    override def apply(x: A) = find(x)

    override def +=(x: A) = {
      parent(x) = x
      this
    }

    override def clear() = parent.clear()

    def sets: Map[A, Iterable[A]] = parent.keys.groupBy(find)

    def union(x: A, y: A) = {
      // Randomized linking is O(an) too: http://www.cis.upenn.edu/~sanjeev/papers/soda14_disjoint_set_union.pdf
      // If input is randomized we don't need randomization anyway: http://codeforces.com/blog/entry/21476
      // Without any linking heuristics but only path compression, it is O(log n) too: http://stackoverflow.com/questions/2323351/
      if (scala.util.Random.nextBoolean()) parent(find(x)) = find(y) else parent(find(y)) = find(x)
    }
  }
}
/****************************[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, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def 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 testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def 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")

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

import java.io.PrintWriter

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

object C {

  def main(args: Array[String]): Unit = {
    val in = io.Source.fromInputStream(System.in).getLines()
    //    val in = io.Source.fromFile("in.txt").getLines()
    val out = new PrintWriter(System.out)
    //    val out = new PrintWriter(new File("out.txt"))
    val n = in.next().toInt
    val a = in.next().split(" ").map(_.toInt).map(_ - 1)

    val g = ArrayBuffer.fill(n)(new ArrayBuffer[Int]())
    for (i<- 0 until n)
      g(i) = new ArrayBuffer[Int]()
    for (i <- 0 until n) {
      g(i) += a(i)
      g(a(i)) += i
    }

    val res = find_comps(n, g)
    out.println(res)

    out.flush()
    out.close()
  }

  def find_comps(n:Int, g: ArrayBuffer[ArrayBuffer[Int]]):Int = {
    val used = ArrayBuffer.fill(n)(false)
    var res = 0

    for (i<-0 until n) {
      if (!used(i)) {
        dfs(i,used, g)
        res+=1
      }
    }

    res
  }

  def dfs(v: Int, used: ArrayBuffer[Boolean], g: ArrayBuffer[ArrayBuffer[Int]]): Unit = {
    used(v) = true

    for (i <- g(v).indices) {
      if (!used(g(v)(i))) {
        dfs(g(v)(i), used, g)
      }
    }
  }
}


It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.

The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.

In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form. If there are multiple possible answers, you can print any of them.

NoteIn the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.

object a extends App {
    val n = readLine.toInt
    var ps = readLine.split(" ").map(_.toInt).zipWithIndex.sorted.toArray

    var eqct = 0
    var prev = (-20, -20)
    for (p <- ps) {
        if (prev._1==p._1) eqct += 1
        prev = p
    }
    if (eqct < 2) {
        println("NO")
        System.exit(0)
    }
    println("YES")
    for (i <- 1 to 3) {
        for (p <- ps) print((p._2+1) + " ")
        var br = 0
        for (j <- 0 to n-2) {
            val (a, b) = (ps(j)._2, ps(j+1)._2)
            if (br== 0 && ps(j)._1==ps(j+1)._1 && a<b) {
                ps(j) = ps(j).copy(_2=b)
                ps(j+1)=ps(j+1).copy(_2=a)
                br = 1
            }
        }
        println()
    }
}

object a extends App {
    val n = readLine.toInt
    val ar = readLine.split(" ").map(_.toInt)
    var ps = Array(ar, (1 to n).toArray).transpose.sortBy(x => (x(0), x(1)))

    var eqct = 0
    for (i <- 0 to n-2)
        if (ps(i)(0) == ps(i+1)(0)) eqct += 1
    if (eqct < 2) {
        println("NO")
        System.exit(0)
    }
    println("YES")
    for (i <- 1 to 3) {
        for (p <- ps) print(p(1) + " ")
        var br = 0
        for (j <- 0 to n-2) {
            val (a, b) = (ps(j)(1), ps(j+1)(1))
            if (br== 0 && ps(j)(0)==ps(j+1)(0) && a<b) {
                ps(j)(1) = b
                ps(j+1)(1) = a
                br = 1
            }
        }
        println()
    }
}

import scala.collection.mutable.ArrayBuffer

object Main {

	def main(args: Array[String]): Unit = {
		val cin = new java.util.Scanner(System.in)

		val n = cin.nextInt
		val arr = new Array[(Int, Int)](n)
		val swaps = new ArrayBuffer[(Int, Int)]()

		var i = 0
		while (i < n) {
			arr(i) = (cin.nextInt, i + 1)
			i += 1
		}
		scala.util.Sorting.quickSort(arr)

		i = 1
		while (i < n && swaps.size < 2) {
			if (arr(i)._1 == arr(i - 1)._1)
				swaps.append((i - 1, i))
			i += 1
		}

		if (swaps.size < 2) println("NO")
		else {
			println("YES")

			val swap = (tp: (Int, Int)) => {
				val tmp = arr(tp._1)
				arr(tp._1) = arr(tp._2)
				arr(tp._2) = tmp
			}

			println(arr.map(_._2).mkString(" "))
			swap(swaps(0))
			println(arr.map(_._2).mkString(" "))
			swap(swaps(1))
			println(arr.map(_._2).mkString(" "))
		}
	}

}

import java.util.Scanner

object Things extends App {

	val scanner = new Scanner( System.in )

	val n = scanner.nextInt
	val tasks = Array.ofDim[Int]( n )
	for( i <- tasks.indices )
		tasks( i ) = scanner.nextInt

	// check if there are at least two tasks with the same priorities like others
	val same = tasks.length - tasks.distinct.length
	if( same >= 2 ) {
		println( "YES" )
		val sorted = tasks.zipWithIndex.sortBy( _._1 )	// merge with indexes and sort by priority

		val seq = sorted.map( _._2 + 1 )				// sequenced tasks numbers, counted from 1
		println( seq.mkString( " " ))

		val idx = swap( 1, sorted, seq )				// swap first tasks with equal priority
		println( seq.mkString( " " ))

		swap( idx + 1, sorted, seq )					// swap next tasks with equal priority
		println( seq.mkString( " " ))
	}
	else
		println( "NO" )

	// find tasks with the same priority in indexed array (pairs), starting from start
	//  and swap them in final sequence (tasks)
	def swap( start: Int, pairs: Array[(Int,Int)], tasks: Array[Int] ) = {
		var i = start
		while( pairs( i )._1 != pairs( i - 1 )._1 )
			i += 1
		val t = tasks( i )
		tasks( i ) = tasks( i - 1 )
		tasks( i - 1 ) = t
		i
	}
}

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

/**
 * Created by arseny on 26.09.14.
 */
object B extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val hs = (for (i <- 0 until n) yield nextInt).toArray.zipWithIndex.sortBy(_._1)
    val ss = hs.groupBy(x => x._1).map(x => x._1 -> x._2.size)
    val ss3 = ss.filter(_._2 >= 3)
    val ss2 = ss.filter(_._2 >= 2)
    if (ss3.size >= 1) {
      out.println("YES")
      val h = ss3.head._1
      val first = hs.map(_._2 + 1)
      out.println(first.mkString(" "))
      val es = hs.unzip._1
      val i1 = es.indexOf(h)
      val tmp = i1
      val i2 = es.indexOf(h, i1 + 1)
      val i3 = es.indexOf(h, i2 + 1)
      val second = first.updated(i1, first(i2)).updated(i2, first(tmp))
      out.println(second.mkString(" "))
      val third = first.updated(i1, first(i3)).updated(i3, first(tmp))
      out.println(third.mkString(" "))
    } else if (ss2.size >= 2) {
      out.println("YES")
      val h1 = ss2.head._1
      val first = hs.map(_._2 + 1)
      out.println(first.mkString(" "))
      val es = hs.unzip._1
      val i1 = es.indexOf(h1)
      val tmp1 = i1
      val i2 = es.indexOf(h1, i1 + 1)
      val second = first.updated(i1, first(i2)).updated(i2, first(tmp1))
      out.println(second.mkString(" "))
      val h2 = ss2.last._1
      val i3 = es.indexOf(h2)
      val tmp2 = i3
      val i4 = es.indexOf(h2, i3 + 1)
      val third = first.updated(i3, first(i4)).updated(i4, first(tmp2))
      out.println(third.mkString(" "))
    } else {
      out.print("NO")
    }
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexed = data.zipWithIndex.sorted
  val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {
    case((count, soFar, prev), el) if count >= 3 =>
      (count, soFar, el._1)
    case((count, soFar, prev), el) if prev == el._1 =>
      (count, soFar + 1, el._1)
    case((count, soFar, prev), el) => (count * soFar, 1l, el._1)
  }
  val dup_count = if (duplicates._1 < 3) duplicates._1 * duplicates._2 else duplicates._1
  if (dup_count < 3)
    println("NO")
  else {
    println("YES")
    println(indexed.map(_._2 + 1).mkString(" "))
    val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get
    val tmp = indexed(i1)
    indexed(i1) = indexed(i1 + 1)
    indexed(i1 + 1) = tmp
    println(indexed.map(_._2 + 1).mkString(" "))
    val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get
    val tmp2 = indexed(i2)
    indexed(i2) = indexed(i2 - 1)
    indexed(i2 - 1) = tmp2
    println(indexed.map(_._2 + 1).mkString(" "))
  }
}

import java.util

/**
 * @author pvasilyev
 * @since 18 Jun 2016
 */
object B471 extends App {

  def hasMoreThanThree(c: Array[util.ArrayList[Int]]): Boolean = {
    c.foreach((list: util.ArrayList[Int]) => {
      if (list != null) {
        if (list.size() > 2) {
          return true
        }
      }
    })
    false
  }

  def checkItIsPossible(c: Array[util.ArrayList[Int]]): Boolean = {
    var doubles = 0
    c.foreach((list: util.ArrayList[Int]) => {
      if (list != null) {
        if (list.size() > 2) {
          return true
        } else if (list.size() == 2) {
          doubles += 1
        }
      }
    })
    doubles > 1
  }

  def solve() = {
    val n: Int = scala.io.StdIn.readInt()
    val count: Array[util.ArrayList[Int]] = Array.ofDim(2001)
    scala.io.StdIn.readLine().split(" ").map(_.toInt).foldLeft(1)((x, h) => {
      if (count(h) == null) {
        count(h) = new util.ArrayList[Int]()
      }
      count(h).add(x)
      x+1
    })

    if (!checkItIsPossible(count)) {
      println("NO")
    } else {
      val a = new util.ArrayList[Int]()
      val b = new util.ArrayList[Int]()
      val c = new util.ArrayList[Int]()
      if (hasMoreThanThree(count)) {
        for (i <- 1 to 2000) {
          if (count(i) != null) {
            if (count(i).size() > 2) {
              val first = count(i).get(0)
              val second = count(i).get(1)
              val third = count(i).get(2)
              a.add(first)
              a.add(second)
              a.add(third)
              b.add(second)
              b.add(third)
              b.add(first)
              c.add(third)
              c.add(first)
              c.add(second)
              for (j <- 3 until count(i).size) {
                a.add(count(i).get(j))
                b.add(count(i).get(j))
                c.add(count(i).get(j))
              }
            } else {
              for (j <- 0 until count(i).size()) {
                a.add(count(i).get(j))
                b.add(count(i).get(j))
                c.add(count(i).get(j))
              }
            }
          }
        }
      } else {
        var firstIndex = -1
        var secondIndex = -1
        for (i <- 1 to 2000) {
          if (count(i) != null) {
            if (count(i).size() > 1) {
              if (firstIndex < 0) {
                firstIndex = i
                a.add(count(i).get(0))
                a.add(count(i).get(1))
                b.add(count(i).get(1))
                b.add(count(i).get(0))
                c.add(count(i).get(1))
                c.add(count(i).get(0))
              } else if (secondIndex < 0) {
                secondIndex = i
                a.add(count(i).get(0))
                a.add(count(i).get(1))
                b.add(count(i).get(0))
                b.add(count(i).get(1))
                c.add(count(i).get(1))
                c.add(count(i).get(0))
              } else {
                a.add(count(i).get(0))
                a.add(count(i).get(1))
                b.add(count(i).get(0))
                b.add(count(i).get(1))
                c.add(count(i).get(0))
                c.add(count(i).get(1))
              }
            } else {
              a.add(count(i).get(0))
              b.add(count(i).get(0))
              c.add(count(i).get(0))
            }
          }
        }
      }
      println("YES")
      println(a.toArray.mkString(" "))
      println(b.toArray.mkString(" "))
      println(c.toArray.mkString(" "))
    }
  }

  solve()

}

import java.util._
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 comp(a: (Int, Int), b: (Int, Int)): Boolean = {
    if (a._1 == b._1) {
      a._2 < b._2
    } else {
      a._1 < b._1
    }
  }

  def solve: Int = {
    val n = nextInt
    val tasks = new Array[(Int, Int)](n)
    val m = new Array[Int](3000)
    for (i <- 0 until n) {
      val a = nextInt
      tasks(i) = (a, i + 1)
      m(a) += 1
    }
    var could = false
    val list = new util.ArrayList[Int]()
    var x2 = false
    var x2el = -1
    for (i <- 0 until m.length) {
      if (!could) {
        if (m(i) >= 3) {
          could = true
          list.add(i)
        } else if (m(i) == 2 && !x2) {
          x2 = true
          x2el = i
        } else if (m(i) == 2 && x2) {
          could = true
          list.add(i)
          list.add(x2el)
        }
      }
    }
    val sorted = tasks.sortWith(comp)
    if (could) {
      out.println("YES")
      if (list.size() == 1) {
        val el = list.get(0)
        for (i <- 0 until 3) {
          var j = 0
          var flag = false
          while (j < n) {
            if (sorted(j)._1 != el || flag) {
              out.print(sorted(j)._2 + " ")
              j += 1
            } else {
              flag = true
              i match {
                case 0 => {
                  out.print(sorted(j + 0)._2 + " ")
                  out.print(sorted(j + 1)._2 + " ")
                  out.print(sorted(j + 2)._2 + " ")
                }
                case 1 => {
                  out.print(sorted(j + 1)._2 + " ")
                  out.print(sorted(j + 0)._2 + " ")
                  out.print(sorted(j + 2)._2 + " ")
                }
                case 2 => {
                  out.print(sorted(j + 2)._2 + " ")
                  out.print(sorted(j + 0)._2 + " ")
                  out.print(sorted(j + 1)._2 + " ")
                }
                case _ => {}
              }
              j += 3
            }

          }

          out.println()
        }
      } else {
        val el1 = list.get(0)
        val el2 = list.get(1)
        for (i <- 0 until 3) {
          var j = 0
          while (j < n) {
            if (sorted(j)._1 != el1 && sorted(j)._1 != el2) {
              out.print(sorted(j)._2 + " ")
              j += 1
            } else {
              if (sorted(j)._1 == el1) {
                i match {
                  case 0 => {
                    out.print(sorted(j + 0)._2 + " ")
                    out.print(sorted(j + 1)._2 + " ")
                  }
                  case 1 => {
                    out.print(sorted(j + 1)._2 + " ")
                    out.print(sorted(j + 0)._2 + " ")
                  }
                  case 2 => {
                    out.print(sorted(j + 0)._2 + " ")
                    out.print(sorted(j + 1)._2 + " ")
                  }
                  case _ => {}
                }
              } else if (sorted(j)._1 == el2) {
                i match {
                  case 0 => {
                    out.print(sorted(j + 0)._2 + " ")
                    out.print(sorted(j + 1)._2 + " ")
                  }
                  case 1 => {
                    out.print(sorted(j + 0)._2 + " ")
                    out.print(sorted(j + 1)._2 + " ")
                  }
                  case 2 => {
                    out.print(sorted(j + 1)._2 + " ")
                    out.print(sorted(j + 0)._2 + " ")
                  }
                  case _ => {}
                }
              }
              j += 2
            }
          }
          out.println()
        }
      }
    } else {
      out.println("NO")
    }

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

object a extends App {
    val n = readLine.toInt
    var ps = readLine.split(" ").map(_.toInt).zipWithIndex.sorted.toArray

    var eqct = 0
    var prev = (-20, -20)
    for (p <- ps) {
        if (prev._1==p._1) eqct += 1
        prev = p
    }
    if (eqct < 2) {
        println("NO")
        System.exit(0)
    }
    println("YES")
    for (i <- 1 to 3) {
        for (p <- ps) print(p._2 + " ")
        var br = 0
        for (j <- 0 to n-2) {
            val (a, b) = (ps(j)._2, ps(j+1)._2)
            if (br== 0 && ps(j)._1==ps(j+1)._1 && a<b) {
                ps(j) = ps(j).copy(_2=b)
                ps(j+1)=ps(j+1).copy(_2=a)
                br = 1
            }
        }
        println()
    }
}

import scala.collection.mutable.ArrayBuffer

object Main {

	def main(args: Array[String]): Unit = {
		val cin = new java.util.Scanner(System.in)

		val n = cin.nextInt
		val arr = new Array[(Int, Int)](n)
		val swaps = new ArrayBuffer[(Int, Int)]()

		var i = 0
		while (i < n) {
			arr(i) = (cin.nextInt, i + 1)
			i += 1
		}
		scala.util.Sorting.quickSort(arr)

		i = 1
		while (i < n && swaps.size < 2) {
			if (arr(i)._1 == arr(i - 1)._1)
				swaps.append((i - 1, i))
			i += 1
		}

		println(swaps.size)

		if (swaps.size < 2) println("NO")
		else {
			println("YES")

			val swap = (tp: (Int, Int)) => {
				val tmp = arr(tp._1)
				arr(tp._1) = arr(tp._2)
				arr(tp._2) = tmp
			}

			println(arr.map(_._2).mkString(" "))
			swap(swaps(0))
			println(arr.map(_._2).mkString(" "))
			swap(swaps(1))
			println(arr.map(_._2).mkString(" "))
		}
	}

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexed = data.zipWithIndex.sorted
  val duplicates = indexed.tail.foldLeft(1, 1, indexed.head._1) {
    case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)
    case((count, soFar, prev), el) => (count * soFar, 1, el._1)
  }
  val dup_count = duplicates._1 * duplicates._2
  if (dup_count < 3)
    println("NO")
  else {
    println("YES")
    println(indexed.map(_._2 + 1).mkString(" "))
    val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get
    val tmp = indexed(i1)
    indexed(i1) = indexed(i1 + 1)
    indexed(i1 + 1) = tmp
    println(indexed.map(_._2 + 1).mkString(" "))
    val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get
    val tmp2 = indexed(i2)
    indexed(i2) = indexed(i2 - 1)
    indexed(i2 - 1) = tmp2
    println(indexed.map(_._2 + 1).mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexed = data.zipWithIndex.sorted
  val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {
    case((count, soFar, prev), el) if count >= 3 =>
      (count, soFar, el._1)
    case((count, soFar, prev), el) if prev == el._1 =>
      (count, soFar + 1, el._1)
    case((count, soFar, prev), el) => (count * soFar, 1l, el._1)
  }
  val dup_count = if (duplicates._1 < 3) duplicates._1 * duplicates._2 else duplicates._1
  if (n == 2000)
    println(dup_count)
  if (dup_count < 3)
    println("NO")
  else {
    println("YES")
    println(indexed.map(_._2 + 1).mkString(" "))
    val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get
    val tmp = indexed(i1)
    indexed(i1) = indexed(i1 + 1)
    indexed(i1 + 1) = tmp
    println(indexed.map(_._2 + 1).mkString(" "))
    val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get
    val tmp2 = indexed(i2)
    indexed(i2) = indexed(i2 - 1)
    indexed(i2 - 1) = tmp2
    println(indexed.map(_._2 + 1).mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexed = data.zipWithIndex.sorted
  val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {
    case((count, soFar, prev), el) if prev == el._1 =>
      if (n == 2000)
        println("same " + el)
      (count, soFar + 1, el._1)
    case((count, soFar, prev), el) => (count * soFar, 1l, el._1)
  }
  val dup_count = duplicates._1 * duplicates._2
  if (n == 2000)
    println(dup_count)
  if (dup_count < 3)
    println("NO")
  else {
    println("YES")
    println(indexed.map(_._2 + 1).mkString(" "))
    val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get
    val tmp = indexed(i1)
    indexed(i1) = indexed(i1 + 1)
    indexed(i1 + 1) = tmp
    println(indexed.map(_._2 + 1).mkString(" "))
    val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get
    val tmp2 = indexed(i2)
    indexed(i2) = indexed(i2 - 1)
    indexed(i2 - 1) = tmp2
    println(indexed.map(_._2 + 1).mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexed = data.zipWithIndex.sorted
  val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {
    case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)
    case((count, soFar, prev), el) => (count * soFar, 1, el._1)
  }
  val dup_count = duplicates._1 * duplicates._2
  if (n == 2000)
    println(dup_count)
  if (dup_count < 3)
    println("NO")
  else {
    println("YES")
    println(indexed.map(_._2 + 1).mkString(" "))
    val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get
    val tmp = indexed(i1)
    indexed(i1) = indexed(i1 + 1)
    indexed(i1 + 1) = tmp
    println(indexed.map(_._2 + 1).mkString(" "))
    val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get
    val tmp2 = indexed(i2)
    indexed(i2) = indexed(i2 - 1)
    indexed(i2 - 1) = tmp2
    println(indexed.map(_._2 + 1).mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexed = data.zipWithIndex.sorted
  val duplicates = indexed.tail.foldLeft(1l, 1l, indexed.head._1) {
    case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)
    case((count, soFar, prev), el) => (count * soFar, 1, el._1)
  }
  val dup_count = duplicates._1 * duplicates._2
  if (dup_count < 3)
    println("NO")
  else {
    println("YES")
    println(indexed.map(_._2 + 1).mkString(" "))
    val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get
    val tmp = indexed(i1)
    indexed(i1) = indexed(i1 + 1)
    indexed(i1 + 1) = tmp
    println(indexed.map(_._2 + 1).mkString(" "))
    val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get
    val tmp2 = indexed(i2)
    indexed(i2) = indexed(i2 - 1)
    indexed(i2 - 1) = tmp2
    println(indexed.map(_._2 + 1).mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexed = data.zipWithIndex.sorted
  val duplicates = indexed.tail.foldLeft(1, 1, indexed.head._1) {
    case((count, soFar, prev), el) if prev == el._1 => (count, soFar + 1, el._1)
    case((count, soFar, prev), el) => (count * soFar, 1, el._1)
  }
  val dup_count = duplicates._1 * duplicates._2
  if (dup_count < 3)
    println("NO")
  else {
    println("YES")
    val i1 = (0 until indexed.length - 1).find(i => indexed(i)._1 == indexed(i + 1)._1).get
    val tmp = indexed(i1)
    indexed(i1) = indexed(i1 + 1)
    indexed(i1 + 1) = tmp
    println(indexed.map(_._2 + 1).mkString(" "))
    val i2 = (indexed.length - 1 until 0 by -1).find(i => indexed(i)._1 == indexed(i - 1)._1).get
    val tmp2 = indexed(i2)
    indexed(i2) = indexed(i2 - 1)
    indexed(i2 - 1) = tmp2
    println(indexed.map(_._2 + 1).mkString(" "))
  }
}


Arkady coordinates rounds on some not really famous competitive programming platform. Each round features $$$n$$$ problems of distinct difficulty, the difficulties are numbered from $$$1$$$ to $$$n$$$.To hold a round Arkady needs $$$n$$$ new (not used previously) problems, one for each difficulty. As for now, Arkady creates all the problems himself, but unfortunately, he can't just create a problem of a desired difficulty. Instead, when he creates a problem, he evaluates its difficulty from $$$1$$$ to $$$n$$$ and puts it into the problems pool.At each moment when Arkady can choose a set of $$$n$$$ new problems of distinct difficulties from the pool, he holds a round with these problems and removes them from the pool. Arkady always creates one problem at a time, so if he can hold a round after creating a problem, he immediately does it.You are given a sequence of problems' difficulties in the order Arkady created them. For each problem, determine whether Arkady held the round right after creating this problem, or not. Initially the problems pool is empty.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^5$$$) — the number of difficulty levels and the number of problems Arkady created. The second line contains $$$m$$$ integers $$$a_1, a_2, \ldots, a_m$$$ ($$$1 \le a_i \le n$$$) — the problems' difficulties in the order Arkady created them.

Print a line containing $$$m$$$ digits. The $$$i$$$-th digit should be $$$1$$$ if Arkady held the round after creation of the $$$i$$$-th problem, and $$$0$$$ otherwise.

NoteIn the first example Arkady held the round after the first three problems, because they are of distinct difficulties, and then only after the last problem.

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 K, N = ni()
    val A = na(N, -1)
    val C = Array.ofDim[Int](K + 10)
    val ans = Array.ofDim[Int](N)
    val CC = Array.ofDim[Int](N + 10) // カウントのカウント
    REP(N) { i =>
      C(A(i)) += 1
      CC(C(A(i))) += 1
      if (CC(C(A(i))) == K) ans(i) = 1
    }

    out.println(ans.mkString)
  }

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

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

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

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

  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.collection.mutable
import scala.io.StdIn

object Codeforces1100B {

  def getRoundString(n: Int, m: Int, a: Seq[Int]): String = {
    val difficultyCountMap = new mutable.HashMap[Int, Int]()
    for (i <- 1 to n) {
      difficultyCountMap.put(i, 0)
    }
    val countMilestoneMap = new mutable.HashMap[Int, Int]()

    var alreadyHeldContest = 0
    val roundString = (1 to m).map(_ => '0').toArray
    for (i <- a.indices) {
      difficultyCountMap(a(i)) += 1
      val count = difficultyCountMap(a(i))
      countMilestoneMap.put(count, countMilestoneMap.getOrElse(count, 0) + 1)
      if (countMilestoneMap(alreadyHeldContest + 1) >= n) {
        roundString(i) = '1'
        alreadyHeldContest += 1
      }
    }

    new String(roundString)
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = StdIn.readLine().trim.split(" ").map(_.toInt)
    val a = StdIn.readLine().trim.split(" ").map(_.toInt)
    val roundString = getRoundString(n, m, a)
    println(roundString)
  }
}


Today, hedgehog Filya went to school for the very first time! Teacher gave him a homework which Filya was unable to complete without your help.Filya is given an array of non-negative integers a1, a2, ..., an. First, he pick an integer x and then he adds x to some elements of the array (no more than once), subtract x from some other elements (also, no more than once) and do no change other elements. He wants all elements of the array to be equal.Now he wonders if it's possible to pick such integer x and change some elements of the array using this x in order to make all elements equal.

The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the number of integers in the Filya's array. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 109) — elements of the array.

If it's impossible to make all elements of the array equal using the process given in the problem statement, then print "NO" (without quotes) in the only line of the output. Otherwise print "YES" (without quotes).

NoteIn the first sample Filya should select x = 1, then add it to the first and the last elements of the array and subtract from the second and the third elements.

//package merofeev.contests.codeforces.rnd371

import java.util.Scanner

/**
  * @author erofeev
  * @since 13.09.16
  */
object BNumbers {

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val count = in.nextLine().toInt
    val ints = in.nextLine().split(" ").map(_.toInt).toSet.toSeq.sorted
    if (ints.size < 3) {
      println("YES")
    } else if (ints.size > 3) {
      println("NO")
    } else if (ints.head + ints(2) == 2 * ints(1)) {
      println("YES")
    } else {
      println("NO")
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toLong)
  val min = line.min
  val max = line.max
  val delta = max - min
  if (min == max)
    println("YES")
  else if ((max - min) % 2 == 1) {
    if (line.exists(x => x != min + delta && x != min))
      println("NO")
    else
      println("YES")
  } else if (line.exists(x => x != min + delta / 2 && x != min && x != min + delta))
    println("NO")
  else
    println("YES")
}

object B714 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readLongs(n).toSet
    if(a.size > 2) {
      val sum = a.min + (a.max - a.min) / 2
      val set = cu.Set.empty[Long]
      a.map(sum - _).filter(_ != 0).foreach { num =>
        set.add(math.abs(num))
      }
      if (set.size <= 1) {
        println("YES")
      } else {
        println("NO")
      }
    } else {
      println("YES")
    }
  }

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

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

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

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

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

}

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

object _714B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val data = read[Set[Int]]

    val ans = data.size match {
      case 1 | 2 => true
      case 3 =>
        val Seq(a, b, c) = data.toSeq.sorted
        (b - a) == c - b
      case _ => false
    }

    write(ans.toEnglish)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def 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")

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

import collection.mutable.Set;

object CF3712B extends App {
  readLine
  val a = readLine.split(" ").map(_.toInt)
  println(Solve(a))

  def Solve(a: Array[Int]) :String = {
    val s = Set(0)
    s -= 0
    for (i <- a) {
      s += i
      if (s.size > 3) return "NO"
    }
    if (s.size <= 2)
      return "YES"
    val b = s.toArray
    scala.util.Sorting.quickSort(b)
    return if (b(0) + b(2) == 2*b(1)) "YES" else "NO"
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val yes = "YES"
    val no = "NO"

    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val arr = new Array[Int](n)
    for(i <- 0 until n)
      arr(i) = sc.nextInt()

    val a = arr.sorted

    val max = a(n-1)
    val min = a(0)
    // a.foreach{println}
    //
//    println(min + " " + max)

    if(min == max)
      println(yes)
    else if ((max - min) % 2 != 0){
      var flag = true
      for(e <- a){
        if(e == max || e == min)
          ()
        else
          flag = false
      }
      if(flag)
        println(yes)
      else
        println(no)
    }
    else{
      val mid = (max+min) / 2

      var flag = true
      for(e <- a){
        if(e == max || e == min || e == mid)
          ()
        else
          flag = false
      }
      if(flag)
        println(yes)
      else
        println(no)
    }
  }
}

//package merofeev.contests.codeforces.rnd371

import java.util.Scanner
import scala.util.control.Breaks._

/**
  * @author erofeev
  * @since 13.09.16
  */
object BNumbers {

  def test(possibleX: Int, ints: Array[Int]): Boolean = {
    for (next <- ints) {
      if (possibleX == next) {
      } else if (possibleX + possibleX == next) {
      } else if (possibleX - possibleX == next) {
      } else if (possibleX == next - possibleX) {
      } else if (possibleX + possibleX == next - possibleX) {
      } else {
        return false
      }
    }
    return true
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val count = in.nextLine().toInt
    val ints = in.nextLine().split(" ").map(_.toInt)
    for (possibleX <- ints) {
      val solved = test(possibleX, ints)
      if (solved) {
        System.out.println("YES")
        return
      }
    }
    System.out.println("NO")
  }
}

//package merofeev.contests.codeforces.rnd371

import java.util.Scanner
import scala.util.control.Breaks._

/**
  * @author erofeev
  * @since 13.09.16
  */
object BNumbers {

  def test(possibleX: Int, ints: Array[Int]): Boolean = {
    for (next <- ints) {
      if (possibleX == next) {
      } else if (possibleX + possibleX == next) {
      } else if (possibleX == next - possibleX) {
      } else if (possibleX + possibleX == next - possibleX) {
      } else {
        return false
      }
    }
    return true
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val count = in.nextLine().toInt
    val ints = in.nextLine().split(" ").map(_.toInt)
    for (possibleX <- ints) {
      val solved = test(possibleX, ints)
      if (solved) {
        System.out.println("YES")
        return
      } else {
        System.out.println("NO")
        return
      }
    }
  }
}

//package merofeev.contests.codeforces.rnd371

import java.util.Scanner

/**
  * @author erofeev
  * @since 13.09.16
  */
object BNumbers {

  def test(possibleX: Long, ints: Array[Long]): Boolean = {
    for (next <- ints) {
      if (possibleX == next) {
      } else if (possibleX + possibleX == next) {
      } else if (possibleX - possibleX == next) {
      } else if (possibleX + possibleX == next - possibleX) {
      } else {
        return false
      }
    }
    return true
  }

  def main(args: Array[String]): Unit = {
    val in = new Scanner(System.in)
    val count = in.nextLine().toInt
    val ints = in.nextLine().split(" ").map(_.toLong)
    for (possibleX <- ints) {
      val solved = test(possibleX, ints)
      if (solved) {
        System.out.println("YES")
        return
      }
    }
    System.out.println("NO")
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val line = in.next().split(' ').map(_.toInt)
  val min = line.min
  val max = line.max
  val delta = max - min
  if (min == max)
    println("YES")
  else if ((max - min) % 2 == 1) {
    if (!line.contains(delta))
      println("NO")
    else if (line.exists(x => x != min + delta && x != min))
      println("NO")
    else
      println("YES")
  } else if (line.exists(x => x != min + delta / 2 && x != min && x != min + delta))
    println("NO")
  else
    println("YES")
}

object B714 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readLongs(n)
    val sum = a.sum
    val set = cu.Set.empty[Long]
    val set2 = cu.Set.empty[Long]
    a.map(sum/n - _).filter(_ != 0).foreach{num =>
      if(set.contains(-num))
        set.remove(-num)
      else
        set.add(num)
      if(num != 0)
        set2.add(math.abs(num))
    }
    if(set.isEmpty && set2.size <= 1) {
      println("YES")
    } else {
      println("NO")
    }
  }

  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 B714 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readLongs(n)
    val sum = a.min+(a.max-a.min)/2
    val set = cu.Set.empty[Long]
    a.map(sum - _).filter(_ != 0).foreach{num =>
      set.add(math.abs(num))
    }
    if(set.size <= 1) {
      println("YES")
    } else {
      println("NO")
    }
  }

  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 B714 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readLongs(n)
    val sum = a.sum
    val set = cu.Set.empty[Long]
    if(sum%n == 0) {
      a.foreach{ x =>
        val num = sum/n - n
        if (num>0) set.add(num)
        else set.remove(num)
      }
      if(set.isEmpty) println("YES")
      else println("NO")
    } else {
      println("NO")
    }
  }

  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 collection.mutable.Set;

object CF3712B extends App {
  readLine
  val a = readLine.split(" ").map(_.toInt)
  println(Solve(a))

  def Solve(a: Array[Int]) :String = {
    val s = Set(0)
    s -= 0
    for (i <- a) {
      s += i
      println("*" + i)
      if (s.size > 3) return "NO"
    }
    if (s.size <= 2)
      return "YES"
    val b = s.toArray
    return if (b(0) + b(2) == 2*b(1)) "YES" else "NO"
  }
}

import collection.mutable.Set;

object CF3712B extends App {
  readLine
  val a = readLine.split(" ").map(_.toInt)
  println(Solve(a))

  def Solve(a: Array[Int]) :String = {
    val s = Set(0)
    s -= 0
    for (i <- a) {
      s += i
      if (s.size > 3) return "NO"
    }
    if (s.size <= 2)
      return "YES"
    val b = s.toArray
    return if (b(0) + b(2) == 2*b(1)) "YES" else "NO"
  }
}

import java.util.Scanner

object Main{
  //
  // val s = sc.nextLine()
  // val str = sc.next()

  def main (args: Array[String]){
    val yes = "YES"
    val no = "NO"

    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val arr = new Array[Int](n)
    for(i <- 0 until n)
      arr(i) = sc.nextInt()

    val a = arr.sorted

    val max = a(n-1)
    val min = a(0)
    // a.foreach{println}
    //
//    println(min + " " + max)

    if(min == max)
      println(yes)
    else if ((max - min) % 2 != 0)
      println(no)
    else{
      val mid = (max+min) / 2

      var flag = true
      for(e <- a){
        if(e == max || e == min || e == mid)
          ()
        else

          flag = false
      }
      if(flag)
        println(yes)
      else
        println(no)
    }
  }
}


You're given an array $$$a$$$ of length $$$n$$$. You can perform the following operation on it as many times as you want:  Pick two integers $$$i$$$ and $$$j$$$ $$$(1 \le i,j \le n)$$$ such that $$$a_i+a_j$$$ is odd, then swap $$$a_i$$$ and $$$a_j$$$. What is lexicographically the smallest array you can obtain?An array $$$x$$$ is lexicographically smaller than an array $$$y$$$ if there exists an index $$$i$$$ such that $$$x_i<y_i$$$, and $$$x_j=y_j$$$ for all $$$1 \le j < i$$$. Less formally, at the first index $$$i$$$ in which they differ, $$$x_i<y_i$$$

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of elements in the array $$$a$$$. The second line contains $$$n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array $$$a$$$.

The only line contains $$$n$$$ space-separated integers, the lexicographically smallest array you can obtain.

NoteIn the first example, we can swap $$$1$$$ and $$$4$$$ since $$$1+4=5$$$, which is odd.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = 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) { i =>
      f(i)
    }
  }
  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 Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    if (A.count(_ % 2 == 0) > 0 && A.count(_ % 2 == 1) > 0) {
      sort(A)
    }
    out.println(A.mkString(" "))
  }

  def sort(a: Array[Int]): Array[Int] = {
    import scala.util.Sorting
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val ans = if (a.exists(x => (x & 0x01) == 1) && a.exists(x => (x & 0x01) == 0)) a.sorted else a
    println(ans.mkString(" "))
  }
}


As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers.  Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him.

The first line of input contains two integers n and m (1 ≤ n, m ≤ 1000). The next n lines contain the names and ips of the servers. Each line contains a string name, name of the server and a string ip, ip of the server, separated by space (1 ≤ |name| ≤ 10, name only consists of English lowercase letters). It is guaranteed that all ip are distinct. The next m lines contain the commands in the configuration file. Each line is of form "command ip;" (1 ≤ |command| ≤ 10, command only consists of English lowercase letters). It is guaranteed that ip belongs to one of the n school servers.

Print m lines, the commands in the configuration file after Dustin did his task.

object b918 {
  def main(args: Array[String]): Unit = {
    val lines = scala.io.Source.stdin.getLines().toArray
    val Array(a,_) = lines(0).split(" ").map(_.toInt)
    val (server, ips) = lines.drop(1).splitAt(a)
    val serverMap : Map[String,String] = server.map{ i => val Array (j,k) = i.split( " "); (k,j)}.toMap
    ips.map{i => s"$i #${serverMap(i.split(" ")(1) stripSuffix ";") }"} foreach println
  }
}

import scala.collection.immutable.HashMap

object B extends App {
  val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ips = (0 until n).foldLeft(HashMap.empty[String, String])((ips, _) => {
    val Array(name, ip) = scala.io.StdIn.readLine().split(" ")
    ips + (ip -> name)
  })

  val cmds = (0 until m).foldLeft(List.empty[String])((cmds, _) => {
    val Array(cmd, ip) = scala.io.StdIn.readLine().split(" |;")
    val name = ips(ip)
    cmds :+ s"$cmd $ip; #$name"
  })

  println(cmds.mkString("\n"))
}

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

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

    val names = io.read[Iterator, String](2*n)
      .grouped(2)
      .map({case Seq(name, ip) => ip -> name})
      .toMap

    val commands = io.read[Iterator, String](2*m)
      .grouped(2)
      .map({case Seq(cmd, ip) => s"$cmd $ip #${names(ip.stripSuffix(";"))}"})

    io.write(commands.mkString("\n"))
  }
}
/****************************[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().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
      }
    }
  }
}

object CF918B extends App{
  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt
  val servers = Seq.fill[(String, String)](n)(sc.next, sc.next).map(s => (s._2, s._1)).toMap
  val commands =  Seq.fill[(String, String)](m)(sc.next, sc.next)
  commands.foreach(c => println(c._1 + " " + c._2 + " #" + servers(c._2.init)))
}

import scala.collection.immutable.HashMap

object B extends App {
  val Array(n, m) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val ips = (0 until n).foldLeft(HashMap.empty[String, String])((ips, _) => {
    val Array(name, ip) = scala.io.StdIn.readLine().split(" ")
    ips + (ip -> name)
  })

  val cmds = (0 until m).foldLeft(List.empty[String])((cmds, _) => {
    val Array(cmd, ip) = scala.io.StdIn.readLine().split(" |;")
    val name = ips(ip)
    cmds :+ s"$cmd $ip; #$name"
  }).reverse

  println(cmds.mkString("\n"))
}

object CF918B extends App{
  val sc = new java.util.Scanner(System.in)
  val n, m = sc.nextInt
  val servers = Seq.fill[(String, String)](n)(sc.next, sc.next).map(s => (s._2, s._1)).toMap
  val commands =  Seq.fill[(String, String)](n)(sc.next, sc.next)
  commands.foreach(c => println(c._1 + " " + c._2 + " #" + servers(c._2.init)))
}