You are given a table consisting of n rows and m columns.Numbers in each row form a permutation of integers from 1 to m.You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are allowed to pick two columns and swap them. Thus, you are allowed to perform from 0 to n + 1 actions in total. Operations can be performed in any order.You have to check whether it's possible to obtain the identity permutation 1, 2, ..., m in each row. In other words, check if one can perform some of the operation following the given rules and make each row sorted in increasing order.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 20) — the number of rows and the number of columns in the given table.  Each of next n lines contains m integers — elements of the table. It's guaranteed that numbers in each line form a permutation of integers from 1 to m.

If there is a way to obtain the identity permutation in each row by following the given rules, print "YES" (without quotes) in the only line of the output. Otherwise, print "NO" (without quotes).

NoteIn the first sample, one can act in the following way:   Swap second and third columns. Now the table is 1 2 3 4 1 4 3 2  In the second row, swap the second and the fourth elements. Now the table is 1 2 3 4 1 2 3 4

import java.io._

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

  def processStdInOut(): Unit = {
    val src = io.Source.fromInputStream(System.in)
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
        bw.close()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {

    val line = lines.next()
    val strings = line.split(' ')
    val n = strings(0).toInt
    val m = strings(1).toInt
    val table = Array.ofDim[Int](n, m)
    for (r <- 0 until n) {
      val row = lines.next()
      val entries = row.split(' ').map(_.toInt - 1)  // i.e. make zero-based
      table(r) = entries
    }

    val hasSolution = solve(n, m, table)
    if (hasSolution) { bw.write("YES") } else {bw.write("NO") }
    bw.newLine()
  }

  def solve(n: Int, m: Int, table: Array[Array[Int]]): Boolean = {
    val indexCombinations = (1 until m).flatMap { col => (0 until col).map( (_, col)) }

    def isRowSorted(row: Array[Int]): Boolean = row.zipWithIndex.forall(p => p._1 == p._2)

    def swapEntriesInPlace(row: Array[Int], swap: (Int, Int)): Unit = {
      val (col1, col2) = swap
      val firstEntry = row(col1)
      row(col1) = row(col2)
      row(col2) = firstEntry
    }

    def isSortedAfterSwaps(row: Array[Int], swaps: (Int, Int)* ): Boolean = {
      val newRow = row.clone()
      swaps.foreach(swapEntriesInPlace(newRow, _))
      isRowSorted(newRow)
    }

    def columnSwapHasSolution(colSwap: (Int, Int)): Boolean = {
      def rowCanBeOrdered(rowIndex: Int): Boolean = {
        val rowPrior = table(rowIndex)
        def entriesCanBeSwapped(entrySwap: (Int, Int)): Boolean = {
          // Either do the column swap before or after:
          isSortedAfterSwaps(rowPrior, colSwap, entrySwap) ||
            isSortedAfterSwaps(rowPrior, entrySwap, colSwap)
        }
        // See if column swap is sufficient to reorder, else try swapping each combination of entries...
        val rowHasSolution = isSortedAfterSwaps(rowPrior, colSwap) ||
          indexCombinations.exists(entriesCanBeSwapped(_))
        rowHasSolution
      }
      val hasSolution = (0 until n).forall(rowCanBeOrdered)
      hasSolution
    }

    def isThereASolutionWithNoColumnSwap(): Boolean = {
      def rowCanBeOrdered(rowIndex: Int): Boolean = {
        val rowPrior = table(rowIndex)
        // See if row is already sorted, else try swapping each combination of entries...
        val rowHasSolution = isRowSorted(rowPrior) || indexCombinations.exists(isSortedAfterSwaps(rowPrior, _))
        rowHasSolution
      }
      val hasSolution = (0 until n).forall(rowCanBeOrdered)
      hasSolution
    }

    isThereASolutionWithNoColumnSwap() || indexCombinations.exists(columnSwapHasSolution)
  }
}

object B extends App {

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

  val Array(n, m) = readInts(2)
  val as = Array.fill(n){ readInts(m) }
  var can = false

  for (i <- 0 until m) {
    for (j <- i + 1 until m) {
      var ok = true
      for (row <- as) {
        var cntWrong1, cntWrong2 = 0
        for (c <- 0 until m) {
          if (c != i && c != j && row(c) != c + 1) cntWrong1 += 1
          if (row(c) != c + 1) cntWrong2 += 1
        }
        if (!((cntWrong1 == 0 && cntWrong2 == 2) ||
          (cntWrong1 == 0 && cntWrong2 == 0) ||
          (cntWrong1 == 2 && cntWrong2 == 4 && row(i) == j + 1 && row(j) == i + 1) ||
          (cntWrong1 == 1 && cntWrong2 == 3))) ok = false
        //if (ok) println(i, j, row.mkString(" "), cntWrong1, cntWrong2)
      }
      if (ok) {
        can = true
        //println(i, j)
      }
    }
  }

  var ok = true
  for (row <- as) {
    var cntWrong = 0
    for (c <- 0 until m) {
      if (row(c) != c + 1) cntWrong += 1
    }
    if (cntWrong != 0 && cntWrong != 2) ok = false
  }
  if (ok) can = true

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

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

object _724B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, m = read[Int]
    val table = Vector.fill(n)(read[Array, Int](m))
    val idealRow = (1 to m).toIndexedSeq

    def isOkay(i: Int, j: Int) = table forall { row =>
      row.swap(i, j)
      val ans = row.indices.count(k => row(k) != idealRow(k)) <= 2
      row.swap(j, i)
      ans
    }

    val f = Function.tupled(isOkay _)
    val ans = (m X m).exists(f)

    write(ans.toEnglish)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, 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)
    def swap(i: Int, j: Int): Unit = {
      val t = a(i)
      a(i) = a(j)
      a(j) = t
    }
  }
  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)
  }
  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
  }
  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 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 = "\n"): 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 B extends App {

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

  val Array(n, m) = readInts(2)
  val as = Array.fill(n){ readInts(m) }
  var can = false

  for (i <- 0 until m) {
    for (j <- i + 1 until m) {
      var ok = true
      for (row <- as) {
        var cntWrong = 0
        for (c <- 0 until m) {
          if (c != i && c != j && row(c) != c + 1) cntWrong += 1
        }
        if (cntWrong != 0 && cntWrong != 2 &&
          (cntWrong != 1 || row(i) == i + 1 || row(j) == j + 1)) ok = false
      }
      if (ok) can = true
    }
  }

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


There are $$$n$$$ blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white. You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa). You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed $$$3 \cdot n$$$. If it is impossible to find such a sequence of operations, you need to report it.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 200$$$) — the number of blocks. The second line contains one string $$$s$$$ consisting of $$$n$$$ characters, each character is either "W" or "B". If the $$$i$$$-th character is "W", then the $$$i$$$-th block is white. If the $$$i$$$-th character is "B", then the $$$i$$$-th block is black.

If it is impossible to make all the blocks having the same color, print $$$-1$$$. Otherwise, print an integer $$$k$$$ ($$$0 \le k \le 3 \cdot n$$$) — the number of operations. Then print $$$k$$$ integers $$$p_1, p_2, \dots, p_k$$$ $$$(1 \le p_j \le n - 1)$$$, where $$$p_j$$$ is the position of the left block in the pair of blocks that should be affected by the $$$j$$$-th operation. If there are multiple answers, print any of them.

NoteIn the first example, it is possible to make all blocks black in $$$3$$$ operations. Start with changing blocks $$$6$$$ and $$$7$$$, so the sequence is "BWWWWBBB". Then change blocks $$$2$$$ and $$$3$$$, so the sequence is "BBBWWBB". And finally, change blocks $$$4$$$ and $$$5$$$, so all blocks are black.It is impossible to make all colors equal in the second example.All blocks are already white in the third example.In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks $$$2$$$ and $$$3$$$ (so the sequence is "BBW"), and then change blocks $$$1$$$ and $$$2$$$ (so all blocks are white).

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[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._
}

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val S = ns(N)
    val cntB = S.count(_ == 'B')
    val cntW = N - cntB
    val target = N % 2

    def invert(i: Int): Unit = {
      val c = if (S(i) == 'B') 'W' else 'B'
      S(i) = c
    }

    def paint(c: Char): ArrayBuffer[Int] = {
      val ans = ArrayBuffer[Int]()
      REP(N - 1) { i =>
        if (S(i) != c) {
          ans += i + 1
          invert(i)
          invert(i + 1)
        }
      }
      ans
    }

    if (cntB % 2 != target && cntW % 2 != target) {
      out.println(-1)
      return
    }

    val ans = if (cntB % 2 == target) {
      paint('B')
    } else {
      paint('W')
    }

    out.println(ans.length)
    out.println(ans.mkString(" "))
  }
}


Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100.She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.

The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.

Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if  for all coordinates.

NoteThe final positions of the disks will look as follows:  In particular, note the position of the last disk.

object C extends App {

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

  val Array(n, r) = readInts(2)
  val xs = readInts(n)

  val ys = Array.fill(n){ r.toDouble }

  def intersects(x1: Int, x2: Int): Boolean = {
    Math.abs(x1 - x2) <= 2 * r
  }

  def sqr(a: Double) = a * a

  def stopsAt(x1: Int, j: Int): Double = {
    val y0 = ys(j)
    val dY = Math.sqrt(sqr(2 * r) - sqr(x1 - xs(j)))
    y0 + dY
  }

  for (i <- 1 until n) {

    val stopYs = for {
      j <- 0 until i
      if intersects(xs(i), xs(j))
    } yield stopsAt(xs(i), j)

    ys(i) = if (stopYs.isEmpty) r.toDouble else stopYs.max
  }

  println(ys.mkString(" "))
}

object C extends App {
  val e = scala.math.pow(10, -6)

  val Array(n, r) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val x = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val R = 2.0 * r

  def y2(x1: Int, y1: Double, x2: Int): Double = {
    val t = scala.math.sqrt((R - x1 + x2) * (R + x1 - x2))
    (y1 - t) max (y1 + t)
  }

  def r(x: Int, a: Array[(Int, Double)]): Array[(Int, Double)] =
    a.filter(t => scala.math.abs(t._1 - x) <= R)

  def g(x: Array[Int], a: Array[(Int, Double)] = Array.empty): Array[Double] =
    if (x.isEmpty) a.map(_._2).reverse
    else {
      val y = r(x.head, a).map(t => y2(t._1, t._2, x.head))
      if (y.isEmpty) g(x.tail, (x.head, r.toDouble) +: a)
      else g(x.tail, (x.head, y.max) +: a)
    }

  println(g(x).mkString(" "))
}

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

object Main {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  def main (args: Array[String]){
    val n, r = in.next().toInt
    val x = new Array[Int](n+1)
    for (i <- 1 to n)
      x(i) = in.next().toInt

    //
    def calcY(x: Int, p: (Double, Double)): Double = { // retrun y
      val dia = 2 * r
      val (px, py) = p
      val hoge = x.toDouble - px
      sqrt(dia*dia - hoge*hoge) + py
    }

    val ans = new Array[Double](n+1)

    val centers = new Array[(Double, Double)](n+1)
    val axisX = new Array[Int](1000 + r + 1) // has Graph-number

    for(graphNum <- 1 to n) {
      val nowX: Int = x(graphNum)
      val xrange = (0 max (nowX - r)) to (nowX + r)

      var pos: (Double, Double) = (nowX, r)
      for (x <- xrange) {
        if (axisX(x) > 0){
          val viewGraph = axisX(x)
          val viewPos = centers(viewGraph)

          val nowY: Double = calcY(nowX, viewPos)
          if(nowY > pos._2)
            pos = (nowX, nowY)
        }
      }

      // post-process
      centers(graphNum) = pos
      for (x <- xrange) {
        axisX(x) = graphNum
      }
      ans(graphNum) = pos._2
    }

    for (i <- 1 to n-1) {
      pw.print(ans(i) + " ")
    }
    pw.println(ans(n))
    pw.flush()
  }
}

class InputReader(stream: InputStream) {
  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

object CF908C extends App {

  val sc = new java.util.Scanner(System.in)
  val discs, radius = sc.nextInt

  val result = append(0, Nil)

  println(result map (c => c._2) mkString " ")

  def append(i: Int, circles: List[(Int, Double)]):  List[(Int, Double)] = {

    if (i == discs) return circles
    val cs = append(i+1, circles)
    val nx = sc.nextInt
    if (cs.isEmpty) cs :+ (nx, radius.toDouble)  else cs :+ (nx, findCircle(nx, cs))
  }

  def findCircle(x: Int, circles: List[(Int, Double)]): Double = {
    var result = radius.toDouble
    //println("X: " + x)
    for (c <- circles.sortWith(_._2 > _._2)) {
      //println("X: %d Y:%f".format(c._1, c._2))
      val xdiff = Math.abs(x - c._1)
      //println("XD: " + xdiff)
      if (xdiff <= radius * 2){
        val ydiff = Math.sqrt(Math.pow(radius * 2, 2) - Math.pow(xdiff, 2))
        //println("YD: " +ydiff)
        result = Math.max(result, c._2 + ydiff)
      }
    }
    return result
  }
}

object CF908C extends App {

  val sc = new java.util.Scanner(System.in)
  val discs, radius = sc.nextInt

  val result = append(0, Nil)

  println(result map (c => c._2) mkString " ")

  def append(i: Int, circles: List[(Int, Double)]):  List[(Int, Double)] = {

    if (i == discs) return circles
    val cs = append(i+1, circles)
    val nx = sc.nextInt
    if (cs.isEmpty) cs :+ (nx, radius.toDouble)  else cs :+ (nx, findCircle(nx, cs))
  }

  def findCircle(x: Int, circles: List[(Int, Double)]): Double = {
    //println("X: " + x)
    for (c <- circles.sortWith(_._2 > _._2)) {
      //println("X: %d Y:%f".format(c._1, c._2))
      val xdiff = Math.abs(x - c._1)
      //println("XD: " + xdiff)
      if (xdiff <= radius * 2){
        val ydiff = Math.sqrt(Math.pow(radius * 2, 2) - Math.pow(xdiff, 2))
        //println("YD: " +ydiff)
        return c._2 + ydiff
      }
    }
    0.0 // something wrong
  }
}


You are given a tree consisting of $$$n$$$ vertices. A tree is an undirected connected acyclic graph.    Example of a tree. You have to paint each vertex into one of three colors. For each vertex, you know the cost of painting it in every color.You have to paint the vertices so that any path consisting of exactly three distinct vertices does not contain any vertices with equal colors. In other words, let's consider all triples $$$(x, y, z)$$$ such that $$$x \neq y, y \neq z, x \neq z$$$, $$$x$$$ is connected by an edge with $$$y$$$, and $$$y$$$ is connected by an edge with $$$z$$$. The colours of $$$x$$$, $$$y$$$ and $$$z$$$ should be pairwise distinct. Let's call a painting which meets this condition good.You have to calculate the minimum cost of a good painting and find one of the optimal paintings. If there is no good painting, report about it.

The first line contains one integer $$$n$$$ $$$(3 \le n \le 100\,000)$$$ — the number of vertices. The second line contains a sequence of integers $$$c_{1, 1}, c_{1, 2}, \dots, c_{1, n}$$$ $$$(1 \le c_{1, i} \le 10^{9})$$$, where $$$c_{1, i}$$$ is the cost of painting the $$$i$$$-th vertex into the first color. The third line contains a sequence of integers $$$c_{2, 1}, c_{2, 2}, \dots, c_{2, n}$$$ $$$(1 \le c_{2, i} \le 10^{9})$$$, where $$$c_{2, i}$$$ is the cost of painting the $$$i$$$-th vertex into the second color. The fourth line contains a sequence of integers $$$c_{3, 1}, c_{3, 2}, \dots, c_{3, n}$$$ $$$(1 \le c_{3, i} \le 10^{9})$$$, where $$$c_{3, i}$$$ is the cost of painting the $$$i$$$-th vertex into the third color. Then $$$(n - 1)$$$ lines follow, each containing two integers $$$u_j$$$ and $$$v_j$$$ $$$(1 \le u_j, v_j \le n, u_j \neq v_j)$$$ — the numbers of vertices connected by the $$$j$$$-th undirected edge. It is guaranteed that these edges denote a tree.

If there is no good painting, print $$$-1$$$. Otherwise, print the minimum cost of a good painting in the first line. In the second line print $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ $$$(1 \le b_i \le 3)$$$, where the $$$i$$$-th integer should denote the color of the $$$i$$$-th vertex. If there are multiple good paintings with minimum cost, print any of them.

NoteAll vertices should be painted in different colors in the first example. The optimal way to do it is to paint the first vertex into color $$$1$$$, the second vertex — into color $$$3$$$, and the third vertex — into color $$$2$$$. The cost of this painting is $$$3 + 2 + 1 = 6$$$.

//package codeforces.contest1244

object PaintTheTree {

  type Graph = Map[Int, Set[Int]]

  def update(graph: Graph, x: Int, y: Int): Graph = {
    val setX: Set[Int] = graph.withDefaultValue(Set.empty)(x)
    val setY: Set[Int] = graph.withDefaultValue(Set.empty)(y)
    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def linearize(graph: Graph): List[Int] = {

    @scala.annotation.tailrec
    def loop(node: Int, acc: List[Int]): List[Int] = {

      acc match {
        case Nil => loop(graph(node).head, node :: acc)
        case h :: _ =>
          graph(node).find(_ != h) match {
            case Some(next) => loop(next, node :: acc)
            case None       => node :: acc
          }
      }
    }

    loop(graph.find(_._2.size == 1).get._1, Nil)
  }

  def expandListToSize(n: Int, ls: List[Int]): List[Int] = {
    val size = ls.length
    (1 to n / size + 1).toList.flatMap(_ => ls).take(n)
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val colorA, colorB, colorC = io.StdIn.readLine.split(" ").map(_.toInt)

    val getColor = Seq(colorA, colorB, colorC)

    val graph: Graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { (acc, _) =>
      val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
      update(acc, x, y)
    }

    def colorToValue(color: Int, node: Int): Long = getColor(color - 1)(node - 1).toLong

    println {
      if (graph.values.forall(_.size <= 2)) {

        val seq = linearize(graph)

        val solutionList = List(
          expandListToSize(n, List(1, 2, 3)),
          expandListToSize(n, List(1, 3, 2)),
          expandListToSize(n, List(2, 1, 3)),
          expandListToSize(n, List(2, 3, 1)),
          expandListToSize(n, List(3, 2, 1)),
          expandListToSize(n, List(3, 1, 2))
        )

        val (min, list) = solutionList
          .map { ls =>
            val zipped = ls.zip(seq)
            (zipped.map((colorToValue _).tupled).sum, zipped.sortBy(_._2).map(_._1))
          }
          .minBy(_._1)

        min + "\n" + list.mkString(" ")
      } else -1
    }

  }
}

import scala.collection.mutable

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

  val n = nextInt
  val cs = Array.fill(3)(nextLongs(n))
  val adjBuilders = Array.fill(n){new mutable.ArrayBuilder.ofInt}
  for (_ <- 2 to n) {
    val u, v = nextInt - 1
    adjBuilders(u) += v
    adjBuilders(v) += u
  }
  val adjs = adjBuilders.map(_.result())
  var bad = false

  val depths = Array.ofDim[Int](n)
  def dfs(u: Int, prev: Int, depth: Int): Unit = {
    depths(u) = depth % 3
    var i = 0
    if (adjs(u).length > 2) bad = true
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (v != prev) dfs(v, u, depth + 1)
      i += 1
    }
  }

  val leaf = adjs.indexWhere(_.length == 1)
  dfs(leaf, -1, 0)

  if (bad) out.println(-1)
  else {
    //println(depths.mkString(" "))
    val colors = Array(0, 1, 2)
    var minCost = Long.MaxValue
    var bestColoring = colors
    for (coloring <- colors.permutations) {
      var cost = 0L
      for (i <- 0 until n) {
        cost += cs(coloring(depths(i)))(i)
      }
      if (cost < minCost) {
        minCost = cost
        bestColoring = coloring
      }
    }

    val res = depths.map(bestColoring(_) + 1)

    out.println(minCost)
    out.println(res.mkString(" "))
  }
  out.flush()

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

//package codeforces.contest1244

object PaintTheTree {

  type Graph = Map[Int, Set[Int]]

  def update(graph: Graph, x: Int, y: Int): Graph = {
    val setX: Set[Int] = graph.withDefaultValue(Set.empty)(x)
    val setY: Set[Int] = graph.withDefaultValue(Set.empty)(y)
    graph + (x -> (setX + y)) + (y -> (setY + x))
  }

  def linearize(graph: Graph): List[Int] = {

    @scala.annotation.tailrec
    def loop(node: Int, acc: List[Int]): List[Int] = {

      acc match {
        case Nil => loop(graph(node).head, node :: acc)
        case h :: _ =>
          graph(node).find(_ != h) match {
            case Some(next) => loop(next, node :: acc)
            case None       => node :: acc
          }
      }
    }

    loop(graph.find(_._2.size == 1).get._1, Nil)
  }

  def expandListToSize(n: Int, ls: List[Int]): List[Int] = {
    val size = ls.length
    (1 to n / size + 1).toList.flatMap(_ => ls).take(n)
  }

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val colorA, colorB, colorC = io.StdIn.readLine.split(" ").map(_.toInt)

    val getColor = Seq(colorA, colorB, colorC)

    val graph: Graph = (1 until n).foldLeft(Map[Int, Set[Int]]()) { (acc, _) =>
      val Array(x, y) = io.StdIn.readLine.split(" ").map(_.toInt)
      update(acc, x, y)
    }

    def colorToValue(color: Int, node: Int) = getColor(color - 1)(node - 1)

    println {
      if (graph.values.forall(_.size <= 2)) {

        val seq = linearize(graph)

        val solutionList = List(
          expandListToSize(n, List(1, 2, 3)),
          expandListToSize(n, List(1, 3, 2)),
          expandListToSize(n, List(2, 1, 3)),
          expandListToSize(n, List(2, 3, 1)),
          expandListToSize(n, List(3, 2, 1)),
          expandListToSize(n, List(3, 1, 2))
        )

        val (min, list) = solutionList
          .map { ls =>
            val zipped = ls.zip(seq)
            (zipped.map((colorToValue _).tupled).sum, zipped.sortBy(_._2).map(_._1))
          }
          .minBy(_._1)

        min + "\n" + list.mkString(" ")
      } else -1
    }

  }
}


Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number , in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a non-empty string containing 0's and 1's as digits. The decimal value of expression a0a1...an equals to .Soon Piegirl found out that this system doesn't have same properties that integer base systems do and some operations can not be performed on it. She wasn't able to come up with a fast way of comparing two numbers. She is asking for your help.Given two numbers written in golden system notation, determine which of them has larger decimal value.

Input consists of two lines — one for each number. Each line contains non-empty string consisting of '0' and '1' characters. The length of each string does not exceed 100000.

Print ">" if the first number is larger, "<" if it is smaller and "=" if they are equal.

NoteIn the first example first number equals to , while second number is approximately 1.6180339882 + 1.618033988 + 1 ≈ 5.236, which is clearly a bigger number.In the second example numbers are equal. Each of them is  ≈ 2.618.

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

/**
 * Created by arseny on 10.08.14.
 */
object A 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() = {

    var s = nextString.reverse.toCharArray
    var t = nextString.reverse.toCharArray

    def less(s: Array[Char], t: Array[Char], n: Int, m: Int): Int = {
      var nn = n
      while(nn > 0 && s(nn - 1) == '0') {
        nn -= 1
      }
      var mm = m
      while(mm > 0 && t(mm - 1) == '0') {
        mm -= 1
      }
      if(nn == 0 && mm > 0) {
       -1
      } else if(mm == 0 && nn > 0) {
        1
      } else if (nn + 2 <= mm) {
        -1
      } else if(mm + 2 <= nn) {
        1
      } else if(nn == mm) {
        if(nn == 0) {
          0
        } else {
          less(s, t, nn - 1, mm - 1)
        }
      } else {
        if(nn == mm + 1) {
          if(s(mm - 1) == '1') {
            1
          } else if(nn == 2 && mm == 1) {
            1
          } else if(s(nn - 3) == '0') {
            s(nn - 3) = '1'
            less(s, t, nn - 2, mm - 1)
          } else if(t(mm - 2) == '1') {
            s(nn - 3) = '0'
            t(mm - 2) = '0'
            less(s, t, nn, mm)
          } else {
            1
          }
        } else if(mm == nn + 1) {
          if(t(nn - 1) == '1') {
            -1
          } else if(mm == 2 && nn == 1) {
            -1
          } else if(t(mm - 3) == '0') {
            t(mm - 3) = '1'
            less(s, t, nn - 1, mm - 2)
          } else if(s(nn - 2) == '1') {
            t(mm - 3) = '0'
            s(nn - 2) = '0'
            less(s, t, nn, mm)
          } else {
            -1
          }
        } else {
          0
        }
      }
    }

    val l = less(s, t, s.length, t.length)
    l match {
      case -1 => println('<')
      case 1 => println('>')
      case 0 => println('=')
    }

  }

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


This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.

object cf3D extends App {
  val s = readLine.toArray
  val q = collection.mutable.PriorityQueue[(Int, Int)]()
  def cost(p : Int, d : Int, c : Long) : Long = {
    if (p == s.size) {
      if (d == 0) c else -1
    } else if (s(p) == '(') {
      cost(p + 1, d + 1, c)
    } else {
      val cN = if (s(p) != '?') c else {
        s(p) = ')'
        val Array(c1, c2) = readLine split " " map {_.toInt}
        q enqueue ((c2 - c1, p))
        c + c2
      }
      if (d > 0) cost(p + 1, d - 1, cN) else {
        if (q.isEmpty) return -1
        val (cm, m) = q.dequeue
        s(m) = '('
        cost(p + 1, d + 1, cN - cm)
      }
    }
  }
  val c = cost(0, 0, 0L)
  println(c)
  if (c != -1) println(s.mkString)
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Long) : Long = {
            if (p == s.size) {
                if (d == 0) c else -1
            } else if (s(p) == '(') {
                cost(p + 1, d + 1, c)
            } else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    if (q.isEmpty) return -1
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        val c = cost(0, 0, 0L)
        println(c)
        if (c != -1) println(s.mkString)
    }
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Int) : Int = {
            if (p == s.size) c else {
                s(p) match {
                    case '(' => cost(p + 1, d + 1, c)
                    case ')' => cost(p + 1, d - 1, c)
                    case '?' => {
                        s(p) = ')'
                        val Array(c1, c2) = readLine split " " map {_.toInt}
                        q enqueue ((c2 - c1, p))
                        if (d > 0) cost(p + 1, d - 1, c + c2) else {
                            val (cm, m) = q.dequeue
                            s(m) = '('
                            cost(p + 1, d + 1, c + c2 - cm)
                        }
                    }
                }
            }
        }
        println(cost(0, 0, 0))
        println(s.mkString)
    }
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Long) : Long = {
            if (p == s.size) {
                if (d == 0) c else -1
            } else if (s(p) == '(') {
                cost(p + 1, d + 1, c)
            } else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    if (q.isEmpty) return -1
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        println(cost(0, 0, 0L))
        println(s.mkString)
    }
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Long) : Long = {
            if (p == s.size) c
            else if (s(p) == '(') cost(p + 1, d + 1, c)
            else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        println(cost(0, 0, 0L))
        println(s.mkString)
    }
}

object P3D {
    def main(args : Array[String]) {
        val s = readLine.toArray
        val q = collection.mutable.PriorityQueue[(Int, Int)]()
        def cost(p : Int, d : Int, c : Int) : Int = {
            if (p == s.size) c
            else if (s(p) == '(') cost(p + 1, d + 1, c)
            else {
                val cN = if (s(p) != '?') c else {
                    s(p) = ')'
                    val Array(c1, c2) = readLine split " " map {_.toInt}
                    q enqueue ((c2 - c1, p))
                    c + c2
                }
                if (d > 0) cost(p + 1, d - 1, cN) else {
                    val (cm, m) = q.dequeue
                    s(m) = '('
                    cost(p + 1, d + 1, cN - cm)
                }
            }
        }
        println(cost(0, 0, 0))
        println(s.mkString)
    }
}


The process of mammoth's genome decoding in Berland comes to its end!One of the few remaining tasks is to restore unrecognized nucleotides in a found chain s. Each nucleotide is coded with a capital letter of English alphabet: 'A', 'C', 'G' or 'T'. Unrecognized nucleotides are coded by a question mark '?'. Thus, s is a string consisting of letters 'A', 'C', 'G', 'T' and characters '?'.It is known that the number of nucleotides of each of the four types in the decoded genome of mammoth in Berland should be equal.Your task is to decode the genome and replace each unrecognized nucleotide with one of the four types so that the number of nucleotides of each of the four types becomes equal.

The first line contains the integer n (4 ≤ n ≤ 255) — the length of the genome. The second line contains the string s of length n — the coded genome. It consists of characters 'A', 'C', 'G', 'T' and '?'.

If it is possible to decode the genome, print it. If there are multiple answer, print any of them. If it is not possible, print three equals signs in a row: "===" (without quotes).

NoteIn the first example you can replace the first question mark with the letter 'A', the second question mark with the letter 'G', the third question mark with the letter 'T', then each nucleotide in the genome would be presented twice.In the second example the genome is already decoded correctly and each nucleotide is exactly once in it.In the third and the fourth examples it is impossible to decode the genom.

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

object _747B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n = read[Int]
    val s = read[String]
    val nucleotides = "ACGT".toSeq

    val count = s.toSeq.toMultiSet

    val ans = s.toCharArray
    var i = 0

    def fill(c: Char, x: Int): Unit = if(x > 0 && i < n) {
      if (ans(i) == '?') {
        ans(i) = c
        i += 1
        fill(c, x - 1)
      } else {
        i += 1
        fill(c, x)
      }
    }

    val m = nucleotides.map(count).max
    nucleotides.foreach(c => fill(c, m - count(c)))
    nucleotides.foreach(c => fill(c, (n - 4*m)/4))

    val isOkay = {
      val finalCount = ans.toSeq.toMultiSet
      finalCount('?') == 0 && finalCount.size == 4 && finalCount.values.toSet.size == 1
    }

    write(if (isOkay) ans.mkString else "===")
  }
}
/****************************[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 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 = "\n"): 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
      }
    }
  }
}


Boy Dima gave Julian a birthday present — set $$$B$$$ consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two $$$i$$$ and $$$j$$$ with an edge if $$$|i - j|$$$ belongs to $$$B$$$.Unfortunately, Julian doesn't like the graph, that was built using $$$B$$$. Alex decided to rectify the situation, so he wants to erase some numbers from $$$B$$$, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from $$$B$$$ so that graph constructed on the new set is bipartite.Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.

First line contains an integer $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — size of $$$B$$$ Second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n ~ (1 \leqslant b_i \leqslant 10^{18})$$$ — numbers of $$$B$$$, all $$$b_i$$$ are unique

In the first line print single integer $$$k$$$ – the number of erased elements. In the second line print $$$k$$$ integers — values of erased elements. If there are multiple answers, print any of them.

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[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline private final def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    var i = from
    while(i <= to) { 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]): 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にしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val n = ni()
    val b = nal(n)
    val b2 = b.clone()
    val deleted = ArrayBuffer[Int]()
    val best = ArrayBuffer[Int]()
    REP(n) { i =>
      if (b2(i) % 2 == 0) best += i
    }

    def showResult(): Unit = {
      out.println(best.length)
      out.println(best.map(b).mkString(" "))
    }

    def removeOdds(): Unit = {
      var i = 0
      while(i < n) {
        if (b2(i) % 2 == 1) {
          b2(i) = 0
          deleted += i
        }
        i += 1
      }
    }

    def devide(g: Long) = {
      var i = 0
      while(i < n) {
        b2(i) /= g
        i += 1
      }
    }

    def updateAnsAsDelEven(cntOdd: Int, cntEven: Int): Unit = {
      if (deleted.length + cntEven < best.length) {
        best.clear()
        best ++= deleted
        var i = 0
        while(i < n) {
          if (b2(i) != 0 && b2(i) % 2 == 0) {
            best += i
          }
          i += 1
        }
      }
    }

    while(true) {
      val cntOdd = b2.count(_ % 2 == 1)
      val remain = n - deleted.length
      val cntEven = remain - cntOdd
      debug(s"remain:$remain cntOdd$cntOdd cntEven:$cntEven")
      updateAnsAsDelEven(cntOdd, cntEven)

      if (cntEven == 0) {
        showResult()
        return
      }

      removeOdds()

      val g = gcd(b2)
      devide(g)
    }
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a
    else gcd(b, a % b)
  }

  def gcd(as: Array[Long]): Long = {
    var res = as(0)
    var i = 1
    while (i < as.length) {
      res = gcd(res, as(i))
      i += 1
    }
    res
  }
}


Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person.    A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a,b,c \le 10^8$$$).

For each test case output in a separate line a single integer $$$d$$$ — the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.

NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if ((a max b max c) > n) -1
      else d

    println(ans)
  }
}

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

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

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

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

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

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

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

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

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

    def solve(t: Int = 0): Unit = {
        val x = reader.nextLong()
        val y = reader.nextLong()
        val c = reader.nextLong()

        val (a,b) = if (x > y) (x,y) else (y,x)

        val sub = a - b
        if (c > sub * 2 || sub * 2 < a)
            writer.println(-1)
        else if (c > sub)
            writer.println(c - sub)
        else
            writer.println(c + sub)
    }

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

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

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c < l) c + l else c - l

    val ans =
      if ((a max b max c) > n) -1
      else d

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x, y, c) = readLine().split(" ").map(_.toInt)
    val (a, b)         = (x min y, x max y)

    val l = b - a
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans = if (b > n || a > l || n - b != l - a || d > n || d == a || d == b) -1 else d

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x, y, c) = readLine().split(" ").map(_.toInt)
    val (a, b)         = (x min y, x max y)

    val l = b - a
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans = if (b > n || a > l || n - b != l - a || d > n) -1 else d

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (
        a.min(b) <= l + 1 && l + 1 <= a.max(b) && a.max(b) <= n &&
        d <= n && d != a && d != b &&
        c % l == d % l && a % l == b % l
      ) d
      else -1

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (a.min(b) <= l + 1 && l + 1 <= a.max(b) && a.max(b) <= n && d <= n && d != a && d != b) d
      else -1

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (a.min(b) <= l + 1 && a.max(b) <= n && d <= n) d
      else -1

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c) = readLine().split(" ").map(_.toInt)

    val l = math.abs(a - b)
    val n = 2 * l
    val d = if (c <= l) c + l else c - l

    val ans =
      if (a.max(b) > n || d > n || d < 1) -1
      else d

    println(ans)
  }
}


Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n × n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n - 1, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.

The first line contains one integer n (2 ≤ n ≤ 1000), n is even.

Output n lines with n numbers each — the required matrix. Separate numbers with spaces. If there are several solutions, output any.

import java.util.Scanner

object Matrix extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()

  val mat = Array.ofDim[Int](n, n)
  val t = if (n % 2 == 1) n else n - 1

  for {
    i <- 0 until n - 1
    j <- 0 until n
  } {
    mat(i)(j) = 1 + (i + j) % t
    if (j == n - 1) {
      mat(i)(j) = mat(i)(i)
      mat(j)(i) = mat(i)(i)
      mat(i)(i) = 0
    }
  }

  for {
    i <- 0 until n
  } {
    println(mat(i).mkString(" "))
  }

}

import java.util.Scanner

object Matrix extends App {

  val s = new Scanner(System.in)
  val n = s.nextInt()

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

  for {
    i <- 0 until n - 1
    j <- 0 until n
  } {
    mat(i)(j) = 1 + (i + j) % (n)
    if (j == n - 1) {
      mat(i)(j) = mat(i)(i)
      mat(j)(i) = mat(i)(i)
      mat(i)(i) = 0
    }
  }

  for {
    i <- 0 until n
  } {
    println(mat(i).mkString(" "))
  }

}


Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.

The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.

Print a single number — the answer to the problem.

NoteIn the first sample, Vanya needs to find a single card with number -2.In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.

object HelloWorld {
    def main(args: Array[String]) {
        val l = Console.readLine().split(" ").map(i => Integer.parseInt(i))
        val n = l(0)
        val x = l(1)
        var psum = Console.readLine().split(" ").map(i => Integer.parseInt(i)).reduce(_ + _)
        val res = math.abs(psum)/x + (if (psum%x == 0) 0 else 1)

        println(res)
    }
}

object Vanya {
  def process(n: Int, x:Int, cards: Array[Int]): Int = {
    val value:Int = Math.abs(cards.reduce(_+_))
    val div = value/x
    if(value%x == 0 ) div
    else div + 1
  }
  def main(args:Array[String]) = {
    val Inputs:List[Int] = scala.io.Source.stdin.getLines().
      grouped(2).toList.
      map((y:Seq[String]) => {
        val yl = y.toList
        val Array(n:Int, x:Int) = yl(0).split(" ").map(_.toInt);
        val cards:Array[Int] = yl(1).split(" ").map(_.toInt)
        process(n, x, cards);
    })
    Inputs.foreach((x: Int)=> println(x))
  }
}

import scala.collection.mutable
import scala.io._
import scala.math._
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object a6 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().toArray
    val x = lines(0).split(' ')(1).toInt
    var r = lines(1).split(' ').map(_.toInt).sum.abs
    var count=0
    for {i <- (1 to x).reverse} {
      if (r >= i) {
        count += r/i
        r%=i
      }
    }
    println(count)
  }
}

import java.util.StringTokenizer

object _401 extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val x = next.toInt
  val sum = (1 to n).map(i => next.toInt).sum.abs
  println((sum + x - 1) / x)
}

object Solution extends App {
  val Array(n, x) = readLine().split(" ").map(_.toInt)
  val data = Math.abs(readLine().split(" ").map(_.toInt).sum)
  val r = if (data % x > 0) 1 else 0
  println(data / x + r)
}

object A401 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, x) = readInts(2)
    val in = math.abs(readInts(n).sum)
    println((in+x-1)/x)
  }

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

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

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

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

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

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P401A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, X = sc.nextInt

  def solve(): Unit = {
    val balance = List.fill(N)(sc.nextInt).sum.abs
    val answer = if (balance % X > 0) balance / X + 1
                 else balance / X
    out.println(answer)
  }

  solve
  out.close
}

import java.util.Scanner

/**
 * Created by hama_du on 2014/03/11.
 */
object ProblemA extends App {
  val in = new Scanner(System.in)
  val n = in.nextInt
  val x = in.nextInt
  val sum = Math.abs((0 until n).map(_ => in.nextInt).sum)
  println((sum + x - 1) / x)
}

import java.util.Scanner

object CF401A extends App {
    val in = new Scanner(System.in)
    val n = in.nextInt
    val x = in.nextInt
    val sum = Math.abs((0 until n).map(_ => in.nextInt).sum)
    val answer = (sum + x - 1) / x;
    println(answer)
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Kuang.Ru on 14-9-18.
 */
object A401 extends App{
  val sc = new Scanner(System.in)
  val n, x = sc.nextInt()
  val founded = new ArrayBuffer[Int]()
  var i = 0

  while (i < n) {
    founded += sc.nextInt()
    i += 1
  }

  val diff = Math.abs(founded.sum) - 0

  println(if (diff % x == 0){
    diff / x
  } else {
    diff / x + 1
  })
}

object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n, x = sc.nextInt()
  val in = Array.fill(n)(sc.nextInt())
  val sum = in.sum
  println((sum/x).abs + (if (sum%x==0) 0 else 1))
}

object main extends App with fastIO {

  var Array(n, x) = readLine split(" ") map(_.toInt)
  println((readLine.split(" ").map(_.toInt).sum.abs + x - 1) / x)
  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

import scala.collection.mutable
import scala.io._
import scala.math._
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object a6 {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().toArray
    val cards = lines(1).split(' ').map(_.toInt)
    val h = new mutable.HashMap[Int, Int]()
    val s = new mutable.HashSet[Int]()
    (-1000 to 1000).foreach(h(_)=0)
    cards.foreach(a=>{h(a)=h(a)+1;s.add(abs(a))})
    println(s.filter(_>0).map(a=>abs(h(a)-h(-a))).sum)
  }
}

object A extends App {
  val sc = new java.util.Scanner(System.in)
  val n, x = sc.nextInt()
  val in = Array.fill(n)(sc.nextInt())
  val sum = in.sum
  println(sum/x + (if (sum%x==0) 0 else 1))
}