There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru.You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[/<path>], where:  <hostname> — server name (consists of words and maybe some dots separating them),  /<path> — optional part, where <path> consists of words separated by slashes. We consider two <hostname> to correspond to one website if for each query to the first <hostname> there will be exactly the same query to the second one and vice versa — for each query to the second <hostname> there will be the same query to the first one. Take a look at the samples for further clarifications.Your goal is to determine the groups of server names that correspond to one website. Ignore groups consisting of the only server name.Please note, that according to the above definition queries http://<hostname> and http://<hostname>/ are different.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of page queries. Then follow n lines each containing exactly one address. Each address is of the form http://<hostname>[/<path>], where:   <hostname> consists of lowercase English letters and dots, there are no two consecutive dots, <hostname> doesn't start or finish with a dot. The length of <hostname> is positive and doesn't exceed 20.  <path> consists of lowercase English letters, dots and slashes. There are no two consecutive slashes, <path> doesn't start with a slash and its length doesn't exceed 20.  Addresses are not guaranteed to be distinct.

First print k — the number of groups of server names that correspond to one website. You should count only groups of size greater than one. Next k lines should contain the description of groups, one group per line. For each group print all server names separated by a single space. You are allowed to print both groups and names inside any group in arbitrary order.

10
http://abacaba.ru/test
http://abacaba.ru/
http://abacaba.com
http://abacaba.com/test
http://abacaba.de/
http://abacaba.ru/test
http://abacaba.de/test
http://abacaba.com/
http://abacaba.com/t
http://abacaba.com/test

14
http://c
http://ccc.bbbb/aba..b
http://cba.com
http://a.c/aba..b/a
http://abc/
http://a.c/
http://ccc.bbbb
http://ab.ac.bc.aa/
http://a.a.a/
http://ccc.bbbb/
http://cba.com/
http://cba.com/aba..b
http://a.a.a/aba..b/a
http://abc/aba..b/a

2
http://cba.com http://ccc.bbbb
http://a.a.a http://a.c http://abc

object Solution{
  import scala.io.StdIn
  val url = "(http://[\\w\\.]+)(/?.*)".r

  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val groups = Vector.fill(n)(StdIn.readLine() match {
      case url(host, path) => (host, path)
    }).groupBy(_._1)
      .mapValues(_.map(_._2).toSet)
      .toVector
      .map(_.swap)
      .groupBy(_._1)
      .values
      .map(_ map (_._2))
      .filter(_.size > 1)

    println(groups.size)
    groups.foreach(srvs => println(srvs.mkString(" ")))
  }

}

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

  val Array(n) = readInts(1)

  case class Url(host: String, path: String)

  val urls = Array.fill(n) {
    val s = readLine.drop(7)
    val break = s.indexOf('/')
    if (break == -1) Url(s, "") else Url(s.take(break), s.drop(break))
  }.distinct

  val pathsByHosts = urls.groupBy(_.host).map {
    case (host, hotsUrls) => host -> hotsUrls.map(_.path).sorted.mkString(" ")
  }

  val hostsByPathSets = pathsByHosts.groupBy(_._2).map {
    case (paths, pathHosts) => pathHosts.keys
  }.filter(_.size > 1)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(hostsByPathSets.size)
  hostsByPathSets.foreach(hs => println(hs.map("http://" + _).mkString(" ")))
  Console.flush
}

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

object _644C extends CodeForcesApp {
  override def apply(io: IO) = {
    val ans = io[Iterable[String]]
      .map(s => s.splitAt(s.indexOf('/', 7).nonNegative getOrElse s.length))
      .toMultiMap.mapValues(_.toSet).invert.values.filter(_.size > 1).toVector
    (io += ans.size).appendLine()
    ans.foreach(group => (io ++= group).appendLine())
    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates: Traversable[A] = {
      val elems = mutable.Set.empty[A]
      t collect {case i if !elems.add(i) => i}
    }
    def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}
    def mapTo[B](f: 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
  }
  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 IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {
    def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s
  }
  implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))
    def swap: Traversable[(B, A)] = t.map(_.swap)
  }
  implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.swap.toMultiMap.mapValues(_.toSet)
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  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 nonNegative: Option[A] = when(n.gteq(x, n.zero))(x) //e.g. students.indexOf("Greg").nonNegative
  }
  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(n.min(x, y), n.max(x, y), n.one)
  }
  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] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.{Growable, CanBuild}

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with Growable[Any] {
  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

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    if (tokenizers.nonEmpty) Some(tokenizers.head) else None
  }

  def apply[A](implicit parse: IO.Parser[A]): A = parse.apply(this)
  def apply[C[_], A: IO.Parser](n: Int)(implicit builder: CanBuild[A, C[A]]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  override def +=(obj: Any) = {
    if (isNewLine) isNewLine = false else print(separator)
    print(obj)
    this
  }
  def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t

  def appendLine(): this.type = {
    println()
    isNewLine = true
    this
  }

  override def clear() = flush()
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}

object IO {
  class Parser[A](val apply: IO => A) {
    def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
  }
  implicit def collection[C[_], A: Parser](implicit cbf: CanBuild[A, C[A]])  : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}


Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell $$$(0, 0)$$$. Robot can perform the following four kinds of operations:   U — move from $$$(x, y)$$$ to $$$(x, y + 1)$$$;  D — move from $$$(x, y)$$$ to $$$(x, y - 1)$$$;  L — move from $$$(x, y)$$$ to $$$(x - 1, y)$$$;  R — move from $$$(x, y)$$$ to $$$(x + 1, y)$$$. Vasya also has got a sequence of $$$n$$$ operations. Vasya wants to modify this sequence so after performing it the robot will end up in $$$(x, y)$$$.Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: $$$maxID - minID + 1$$$, where $$$maxID$$$ is the maximum index of a changed operation, and $$$minID$$$ is the minimum index of a changed operation. For example, if Vasya changes RRRRRRR to RLRRLRL, then the operations with indices $$$2$$$, $$$5$$$ and $$$7$$$ are changed, so the length of changed subsegment is $$$7 - 2 + 1 = 6$$$. Another example: if Vasya changes DDDD to DDRD, then the length of changed subsegment is $$$1$$$. If there are no changes, then the length of changed subsegment is $$$0$$$. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from $$$(0, 0)$$$ to $$$(x, y)$$$, or tell him that it's impossible.

The first line contains one integer number $$$n~(1 \le n \le 2 \cdot 10^5)$$$ — the number of operations. The second line contains the sequence of operations — a string of $$$n$$$ characters. Each character is either U, D, L or R. The third line contains two integers $$$x, y~(-10^9 \le x, y \le 10^9)$$$ — the coordinates of the cell where the robot should end its path.

Print one integer — the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from $$$(0, 0)$$$ to $$$(x, y)$$$. If this change is impossible, print $$$-1$$$.

NoteIn the first example the sequence can be changed to LULUU. So the length of the changed subsegment is $$$3 - 1 + 1 = 3$$$.In the second example the given sequence already leads the robot to $$$(x, y)$$$, so the length of the changed subsegment is $$$0$$$.In the third example the robot can't end his path in the cell $$$(x, y)$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val D = ns(N)
    val x, y = ni()

    if (N < abs(x) + abs(y)) {
      out.println(-1)
      return
    }

    val cumX, cumY = Array.ofDim[Int](N + 1)
    rep(N) { i =>
      val (dx, dy) = D(i) match {
        case 'R' => (1, 0)
        case 'L' => (-1, 0)
        case 'U' => (0, 1)
        case 'D' => (0, -1)
      }
      cumX(i + 1) = cumX(i) + dx
      cumY(i + 1) = cumY(i) + dy
    }

    def calc(len: Int): Boolean = {
      0 to N - len foreach { iLen =>
        val i = iLen
        val jLen = N - len - iLen
        val j = N - jLen
        val x1 = cumX(i)
        val x2 = cumX(N) - cumX(j)
        val y1 = cumY(i)
        val y2 = cumY(N) - cumY(j)
        val dist = abs(x - x1 - x2) + abs(y - y1 - y2)
        if (dist <= len && (len - dist) % 2 == 0) return true
//        if (dist <= len) return true
      }
      false
    }

    var l = -1
    var r = N + 1
    while(r - l > 1) {
      val mid = (r + l) / 2
      if (calc(mid)) r = mid
      else l = mid
    }

    if (r == 0) out.println(0)
    else if (r == N + 1) out.println(-1)
    else out.println(r)
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val D = ns(N)
    val x, y = ni()
    val cumX, cumY = Array.ofDim[Int](N + 1)
    rep(N) { i =>
      val (dx, dy) = D(i) match {
        case 'R' => (1, 0)
        case 'L' => (-1, 0)
        case 'U' => (0, 1)
        case 'D' => (0, -1)
      }
      cumX(i + 1) = cumX(i) + dx
      cumY(i + 1) = cumY(i) + dy
    }

    def calc(len: Int): Boolean = {
      rep(N - len) { i =>
        val j = i + len
        val x1 = cumX(i)
        val x2 = cumX(N) - cumX(j)
        val y1 = cumY(i)
        val y2 = cumY(N) - cumY(j)
        val dist = abs(x - x1 - x2) + abs(y - y1 - y2)
        if (dist <= len) return true
      }
      false
    }

    var l = -1
    var r = N + 1
    while(r - l > 1) {
      val mid = (r + l) / 2
      if (calc(mid)) r = mid
      else l = mid
    }

    if (r == 0) out.println(0)
    else if (r == N + 1) out.println(-1)
    else out.println(r)
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val D = ns(N)
    val x, y = ni()

    if (N < abs(x) + abs(y)) {
      out.println(-1)
      return
    }

    val cumX, cumY = Array.ofDim[Int](N + 1)
    rep(N) { i =>
      val (dx, dy) = D(i) match {
        case 'R' => (1, 0)
        case 'L' => (-1, 0)
        case 'U' => (0, 1)
        case 'D' => (0, -1)
      }
      cumX(i + 1) = cumX(i) + dx
      cumY(i + 1) = cumY(i) + dy
    }

    def calc(len: Int): Boolean = {
      rep(N - len + 1) { i =>
        val j = i + len
        val x1 = cumX(i)
        val x2 = cumX(N) - cumX(j)
        val y1 = cumY(i)
        val y2 = cumY(N) - cumY(j)
        val dist = abs(x - x1 - x2) + abs(y - y1 - y2)
        if (dist <= len) return true
      }
      false
    }

    var l = -1
    var r = N + 1
    while(r - l > 1) {
      val mid = (r + l) / 2
      if (calc(mid)) r = mid
      else l = mid
    }

    if (r == 0) out.println(0)
    else if (r == N + 1) out.println(-1)
    else out.println(r)
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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


Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:  Add the integer xi to the first ai elements of the sequence.  Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1)  Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them!

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≤ ti ≤ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≤ 103; 1 ≤ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≤ 103). If ti = 3, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence.

Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6.

NoteIn the second sample, the sequence becomes

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val additions = Array.ofDim[Long](n + 1)
  val data = Array.ofDim[Long](n + 1)
  var sum = 0l
  var length = 1
  println((1 to n).map { _ =>
    in.next().split(' ').map(_.toInt) match {
      case Array(1, x, add) =>
        additions(x - 1) += add
        sum += add * x
        sum.toDouble / length
      case Array(2, k) =>
        data(length) = k
        additions(length) = 0
        length += 1
        sum += k
        sum.toDouble / length
      case Array(3) =>
        if (length > 1)
          additions(length - 2) += additions(length - 1)
        sum -= data(length - 1)
        sum -= additions(length - 1)
        length -= 1
        if (length == 0)
          0
        else
          sum.toDouble / length
    }

  }.mkString("\n"))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val additions = Array.ofDim[Long](n)
  val data = Array.ofDim[Long](n)
  var sum = 0l
  var length = 1
  println((1 to n).map { _ =>
    in.next().split(' ').map(_.toInt) match {
      case Array(1, x, add) =>
        additions(x - 1) += add
        sum += add * x
        sum.toDouble / length
      case Array(2, k) =>
        data(length) = k
        additions(length) = 0
        length += 1
        sum += k
        sum.toDouble / length
      case Array(3) =>
        additions(Math.max(0, length - 2)) = additions(length - 1)
        sum -= data(length - 1)
        sum -= additions(length - 1)
        length -= 1
        if (length == 0)
          0
        else
          sum.toDouble / length
    }

  }.mkString("\n"))

}


Your program fails again. This time it gets "Wrong answer on test 233".This is the harder version of the problem. In this version, $$$1 \le n \le 2\cdot10^5$$$. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.The problem is to finish $$$n$$$ one-choice-questions. Each of the questions contains $$$k$$$ options, and only one of them is correct. The answer to the $$$i$$$-th question is $$$h_{i}$$$, and if your answer of the question $$$i$$$ is $$$h_{i}$$$, you earn $$$1$$$ point, otherwise, you earn $$$0$$$ points for this question. The values $$$h_1, h_2, \dots, h_n$$$ are known to you in this problem.However, you have a mistake in your program. It moves the answer clockwise! Consider all the $$$n$$$ answers are written in a circle. Due to the mistake in your program, they are shifted by one cyclically.Formally, the mistake moves the answer for the question $$$i$$$ to the question $$$i \bmod n + 1$$$. So it moves the answer for the question $$$1$$$ to question $$$2$$$, the answer for the question $$$2$$$ to the question $$$3$$$, ..., the answer for the question $$$n$$$ to the question $$$1$$$.We call all the $$$n$$$ answers together an answer suit. There are $$$k^n$$$ possible answer suits in total.You're wondering, how many answer suits satisfy the following condition: after moving clockwise by $$$1$$$, the total number of points of the new answer suit is strictly larger than the number of points of the old one. You need to find the answer modulo $$$998\,244\,353$$$.For example, if $$$n = 5$$$, and your answer suit is $$$a=[1,2,3,4,5]$$$, it will submitted as $$$a'=[5,1,2,3,4]$$$ because of a mistake. If the correct answer suit is $$$h=[5,2,2,3,4]$$$, the answer suit $$$a$$$ earns $$$1$$$ point and the answer suite $$$a'$$$ earns $$$4$$$ points. Since $$$4 > 1$$$, the answer suit $$$a=[1,2,3,4,5]$$$ should be counted.

The first line contains two integers $$$n$$$, $$$k$$$ ($$$1 \le n \le 2\cdot10^5$$$, $$$1 \le k \le 10^9$$$) — the number of questions and the number of possible answers to each question. The following line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$, ($$$1 \le h_{i} \le k)$$$ — answers to the questions.

Output one integer: the number of answers suits satisfying the given condition, modulo $$$998\,244\,353$$$.

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[Int]]): 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._
  // nCk % MOD を求める。下準備で階乗Fと≡MODでの階乗の逆元Iを作る
  class Comb(N: Int, MOD: Int) {
    def powMod(x: Int, n: Int, m: Int): Int = {
      def step(x: Long, n: Int, stack: Long): Long = {
        n match {
          case 0 => stack
          case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
        }
      }
      step(x, n, 1).toInt
    }

    private[this] val F = Array.ofDim[Long](N + 1)
    F(0) = 1
    REP(N) { i =>
      F(i + 1) = F(i) * (i + 1) % MOD
    }
    private[this] val I = Array.ofDim[Long](F.length)
    I(N) = powMod(F(N).toInt, MOD - 2, MOD)

    // x! = x(x-1)!
    // x!I(x!) ≡ (x-1)!I((x-1)!)
    // I((x-1)!) ≡ I(x!) * x   MODがでかいので(x-1)!はMODと素
    REP_r(N) { i =>
      I(i) = I(i + 1) * (i + 1) % MOD
    }

    def comb(n: Int, k: Int): Long = {
      if (n < k) 0
      else F(n) * I(n - k) % MOD * I(k) % MOD
    }

    def rev(x: Int): Long = {
      I(x) * F(x - 1) % MOD
    }

    /**
      * nのグループからk回重複ありで選ぶ組み合わせ数
      * n - 1のしきりとkの○で考える
      */
    def H(n: Int, k: Int): Long = {
      comb(n + k - 1, k)
    }

    /**
      * private[this]をつかってるのでgetterが必要
      * @return (F, I)
      */
    def get: (Array[Long], Array[Long]) = (F, I)
  }

  def powMod(x: Int, n: Int, m: Int): Int = {
    def step(x: Long, n: Int, stack: Long): Long = {
      n match {
        case 0 => stack
        case _ => step(x * x % m, n / 2, if (n % 2 == 1) stack * x % m else stack)
      }
    }
    step(x, n, 1).toInt
  }
}

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 = 998244353

  def solve(): Unit = {
    val N, K = ni()
    val H = na(N)
    var n = 0

    if (K == 1) {
      out.println("0")
      return
    }

    REP(N) { i =>
      if (H(i) != H((i + 1)%N)) n += 1
    }

    var zero = 0L
    val comb = new Comb(N, MOD)
    TO(0, n/2) { k =>
      zero += comb.comb(n, k) *
        comb.comb(n - k, k) % MOD *
        powMod(K - 2, n - 2 * k, MOD) % MOD
    }
    val ss = (MOD + powMod(K, n, MOD) - zero % MOD) % MOD
    val s = ss * (MOD + 1) / 2 % MOD
    debug(s"$n $zero $ss $s")
    val ans = s * powMod(K, N - n, MOD) % MOD
    out.println(ans)
  }
}


Your city has n junctions. There are m one-way roads between the junctions. As a mayor of the city, you have to ensure the security of all the junctions.To ensure the security, you have to build some police checkposts. Checkposts can only be built in a junction. A checkpost at junction i can protect junction j if either i = j or the police patrol car can go to j from i and then come back to i.Building checkposts costs some money. As some areas of the city are more expensive than others, building checkpost at some junctions might cost more money than other junctions.You have to determine the minimum possible money needed to ensure the security of all the junctions. Also you have to find the number of ways to ensure the security in minimum price and in addition in minimum number of checkposts. Two ways are different if any of the junctions contains a checkpost in one of them and do not contain in the other.

In the first line, you will be given an integer n, number of junctions (1 ≤ n ≤ 105). In the next line, n space-separated integers will be given. The ith integer is the cost of building checkpost at the ith junction (costs will be non-negative and will not exceed 109). The next line will contain an integer m (0 ≤ m ≤ 3·105). And each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; u ≠ v). A pair ui, vi means, that there is a one-way road which goes from ui to vi. There will not be more than one road between two nodes in the same direction.

Print two integers separated by spaces. The first one is the minimum possible money needed to ensure the security of all the junctions. And the second one is the number of ways you can ensure the security modulo 1000000007 (109 + 7).

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.collection.mutable.Stack
import scala.util.Random
import scala.util.control.Breaks._

object C extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val M = sc.nextInt
    val e, re = Array.fill[List[Int]](N)(Nil)
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      e(u)  ::= v
      re(v) ::= u
    }
    sc.close

    val history = new Stack[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        e(v) foreach dfs
        history.push(v)
      }
    }

    def rdfs(k: Int)(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true

        // update costs and CPs
        val cost = C(v)
        if (cost < lowestCost(k)) {
          lowestCost(k) = cost
          numLowestCostCP(k) = 1
        }
        else if (cost == lowestCost(k)) {
          numLowestCostCP(k) += 1
        }

        re(v) foreach rdfs(k)
      }
    }

    0 until N foreach { v => dfs(v) }
    Arrays.fill(used, false)
    var i, k = 0
    while (i < N) {
      val v = history.pop
      if (!used(v)) {
        rdfs(k)(v)
        k += 1
      }
      i += 1
    }

    i = 0
    var a: Long = 0
    var b: Long = 1
    while (i < k) {
      a += lowestCost(i)
      b = b * numLowestCostCP(i) % 1000000007
      i += 1
    }

    List(a, b)
  }

  out.println(solve.mkString(" "))
  out.flush
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.collection.mutable.Stack
import scala.util.Random
import scala.util.control.Breaks._

object C extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val M = sc.nextInt
    val e, re = Array.fill[List[Int]](N)(Nil)
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      e(u)  ::= v
      re(v) ::= u
    }
    sc.close

    val history = new Stack[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val scc: Array[Int] = Array.fill(N)(-1)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        e(v) foreach dfs
        history.push(v)
      }
    }

    def rdfs(k: Int)(v: Int): Unit = {
      if (scc(v) >= 0) ()
      else {
        scc(v) = k

        // update costs and CPs
        val cost = C(v)
        if (cost < lowestCost(k)) {
          lowestCost(k) = cost
          numLowestCostCP(k) = 1
        }
        else if (cost == lowestCost(k)) {
          numLowestCostCP(k) += 1
        }

        re(v) foreach rdfs(k)
      }
    }

    0 until N foreach { v => dfs(v) }
    var i, k = 0
    while (i < N) {
      val v = history.pop
      if (scc(v) < 0) {
        rdfs(k)(v)
        k += 1
      }
      i += 1
    }

    i = 0
    var a: Long = 0
    var b: Long = 1
    while (i < k) {
      a += lowestCost(i)
      b = b * numLowestCostCP(i) % 1000000007
      i += 1
    }

    List(a, b)
  }

  out.println(solve.mkString(" "))
  out.flush
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.collection.mutable.Stack
import scala.util.Random
import scala.util.control.Breaks._

object C extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val M = sc.nextInt
    val e = Array.fill(N)(new ArrayBuffer[Int])
    val re = Array.fill(N)(new ArrayBuffer[Int])
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      e(u)  += v
      re(v) += u
    }
    sc.close

    val history = new Stack[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val scc: Array[Int] = Array.fill(N)(-1)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        e(v) foreach dfs
        history.push(v)
      }
    }

    def rdfs(k: Int)(v: Int): Unit = {
      if (scc(v) >= 0) ()
      else {
        scc(v) = k

        // update costs and CPs
        val cost = C(v)
        if (cost < lowestCost(k)) {
          lowestCost(k) = cost
          numLowestCostCP(k) = 1
        }
        else if (cost == lowestCost(k)) {
          numLowestCostCP(k) += 1
        }

        re(v) foreach rdfs(k)
      }
    }

    0 until N foreach { v => dfs(v) }
    var i, k = 0
    while (i < N) {
      val v = history.pop
      if (scc(v) < 0) {
        rdfs(k)(v)
        k += 1
      }
      i += 1
    }

    i = 0
    var a: Long = 0
    var b: Long = 1
    while (i < k) {
      a += lowestCost(i)
      b = b * numLowestCostCP(i) % 1000000007
      i += 1
    }

    List(a, b)
  }

  out.println(solve.mkString(" "))
  out.flush
}

import scala.collection._

object Checkposts extends App {
	val (n, cost, m) = (readLine.toInt, readLine.split(' ').map(_.toInt), readLine.toInt)
	val (g, h) = (Array.fill[List[Int]](n)(Nil), Array.fill[List[Int]](n)(Nil))

	for (i <- 0 until m) {
		val Array(u, v) = readLine.split(' ').map(_.toInt).map(_-1)
		g(u) ::= v
		h(v) ::= u
	}

	val (cs, s, seen) = (Array.fill(n)(-1), mutable.Stack[Int](), Array.fill(n)(false))
	var nc = 0

	def dfs0 (x : Int) : Unit = {
		if (!seen(x)) {
			seen(x) = true
			g(x).foreach(dfs0)
			s.push(x)
		}
	}

	def dfs1 (x : Int) : Unit = {
		if (cs(x) == -1) {
			cs(x) = nc
			h(x).foreach(dfs1)
		}
	}

	(0 until n).foreach(dfs0)
	for (x <- s) if(cs(x) == -1) {
		dfs1(x)
		nc += 1
	}

	val (best, ways) = (Array.fill(n)(1234567890), Array.fill(n)(0))
	for (x <- 0 until n) {
		val c = cs(x)
		if (cost(x) < best(c)) {
			best(c) = cost(x)
			ways(c) = 1
		} else if (cost(x) == best(cs(x))) {
			ways(c) += 1
		}
	}

	var (ans_best, ans_ways) = (0l, 1l)
	for (c <- 0 until nc) {
		ans_best += best(c)
		ans_ways = ans_ways * ways(c) % 1000000007
	}

	println(ans_best + " " + ans_ways)
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

object C extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Long] = Array.fill(N)(sc.nextLong) // costs of building CPs
    val E0  = Array.fill(N)(new ListBuffer[Int])
    val RE0 = Array.fill(N)(new ListBuffer[Int])
    val M = sc.nextInt
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      E0(u)  += v
      RE0(v) += u
    }
    val E:  Array[List[Int]] = E0.map(_.toList)
    val RE: Array[List[Int]] = RE0.map(_.toList)

    val history = new ListBuffer[Int]
    val used = Array.fill(N)(false)

    def dfs(v: Int): Unit = {
      used(v) = true
      E(v).filterNot(used) foreach { u => dfs(u) }
      history += v
    }

    def rdfs(v: Int): List[Long] = {
      used(v) = true
      C(v) :: RE(v).filterNot(used).flatMap(rdfs(_))
    }

    0 until N foreach { v =>
      if(!used(v)) dfs(v)
    }
    java.util.Arrays.fill(used, false)
    val clusters = new ListBuffer[List[Long]]
    history.toList.reverse.foreach { v =>
      if (!used(v)) clusters += rdfs(v)
    }

    val clst = clusters.toList
    val minCost = clst.map(_.min).sum

    @inline
    def numMinCostCP(js: List[Long]): Int = {
      val min = js.min
      js.count(_ == min)
    }

    val numWays = clst.map(numMinCostCP).foldLeft(1) { (a, b) =>
        a * b % 1000000007
      }

    List(minCost, numWays)
  }

  out.println(solve.mkString(" "))
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

object C extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Long] = Array.fill(N)(sc.nextLong) // costs of building CPs
    val E0  = Array.fill(N)(new ListBuffer[Int])
    val RE0 = Array.fill(N)(new ListBuffer[Int])
    val M = sc.nextInt
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      E0(u)  += v
      RE0(v) += u
    }
    val E:  Array[List[Int]] = E0.map(_.toList)
    val RE: Array[List[Int]] = RE0.map(_.toList)

    val history = new ListBuffer[Int]
    val used = Array.fill(N)(false)
    val sccs = Array.fill(N)(-1)

    def dfs(v: Int): Unit = {
      used(v) = true
      E(v).filterNot(used) foreach { u => dfs(u) }
      history += v
    }

    def rdfs(v: Int, k: Int): Unit = {
      used(v) = true
      sccs(v) = k
      RE(v).filterNot(used).foreach { u =>
        if (!used(u)) rdfs(u, k)
      }
    }

    0 until N foreach { v =>
      if(!used(v)) dfs(v)
    }
    java.util.Arrays.fill(used, false)
    val buf = new ListBuffer[List[Long]]

    var k = 0
    history.toList.reverse.foreach { v =>
      if (!used(v)) {
        rdfs(v, k)
        k += 1
      }
    }

    val clusters: List[List[Long]] = List.range(0, N).groupBy(sccs(_))
      .map { (pair: (Int, List[Int])) =>
        pair._2.map(C(_))
      }.toList

    val minCost = clusters.map(_.min).sum

    def numMinCostCP(js: List[Long]): Int = {
      val m = js.min
      js.count((x: Long) => x == m)
    }

    val numMinCostCPWay: Long = clusters.map(numMinCostCP).foldLeft(1L) { (a, b) => a * b % 1000000007 }

    List(minCost)
  }

  out.println(solve.mkString(" "))
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

object C extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): List[Long] = {
    val N = sc.nextInt
    val C: Array[Int] = Array.fill(N)(sc.nextInt) // costs of building CPs
    val E0  = Array.fill(N)(new ListBuffer[Int])
    val RE0 = Array.fill(N)(new ListBuffer[Int])
    val M = sc.nextInt
    for (_ <- 0 until M) {
      val u, v = sc.nextInt - 1
      E0(u)  += v
      RE0(v) += u
    }
    val E:  Array[List[Int]] = E0.map(_.toList)
    val RE: Array[List[Int]] = RE0.map(_.toList)

    val history = new ListBuffer[Int]
    val used: Array[Boolean] = Array.fill(N)(false)
    val scc: Array[Int] = Array.fill(N)(-1)
    val lowestCost: Array[Int] = Array.fill(N)(Int.MaxValue)
    val numLowestCostCP: Array[Long] = Array.fill(N)(0)

    def dfs(v: Int): Unit = {
      if (used(v)) ()
      else {
        used(v) = true
        E(v) foreach { u => dfs(u) }
        history += v
      }
    }

    @inline
    def updateCostAndCP(v: Int, k: Int): Unit = {
      val cost = C(v)
      if (cost < lowestCost(k)) {
        lowestCost(k) = cost
        numLowestCostCP(k) = 1
      }
      else if (cost == lowestCost(k)) {
        numLowestCostCP(k) += 1
      }
    }

    def rdfs(v: Int, k: Int): Unit = {
      if (scc(v) >= 0) ()
      else {
        scc(v) = k
        updateCostAndCP(v, k)
        RE(v) foreach { u => rdfs(u, k) }
      }
    }

    0 until N foreach { v => dfs(v) }
    var k = 0
    history.toList.reverse.foreach { v =>
      if (scc(v) < 0) {
        rdfs(v, k)
        k += 1
      }
    }
    val minCost = lowestCost.take(k).sum
    val mulModP: (Long, Long) => Long = (a, b) => a * b % 1000000007
    val numMinCostCPWays = numLowestCostCP.take(k).foldLeft(1L)(mulModP)

    List(minCost, numMinCostCPWays)
  }

  out.println(solve.mkString(" "))
  out.close
}


Let's denote as  the number of bits set ('1' bits) in the binary representation of the non-negative integer x.You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and  is maximum possible. If there are multiple such numbers find the smallest of them.

The first line contains integer n — the number of queries (1 ≤ n ≤ 10000). Each of the following n lines contain two integers li, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).

For each query print the answer in a separate line.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map{ _ =>
    val Array(l, r) = in.next().split(' ').map(_.toLong)
    var nL = l
    while ((nL | (nL + 1)) <= r) {
      nL |= nL + 1
    }
    nL
  }.mkString("\n"))
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)

  for (i <- 0 until n) {
    val Array(l, r) = readLongs(2)
    var bit = 1L << 62
    var x = 0L
    var diff = false
    while (bit > 0) {
      if (!diff) {
        if ((l & bit) > 0 && (r & bit) > 0) x += bit
        if ((l & bit) != (r & bit)) diff = true
        if (diff && (r - x + 1) == bit * 2) x += bit
      } else x += bit
      bit >>= 1
    }
    println(x)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map{ _ =>
    val Array(l, r) = in.next().split(' ').map(_.toLong)
    val lStr = l.toBinaryString
    val rStr = r.toBinaryString
    val res = if (lStr.length < rStr.length)
      "1" * (rStr.length - 1)
    else {
      rStr.zip(lStr).foldLeft(((List.empty[Char], false))) {
        case ((list, true), (f, s)) => ('1' :: list, true)
        case ((list, false), (f, s)) if f == s => (f :: list, false)
        case ((list, false), (f, s)) => (f :: list, true)
      }._1.reverse.mkString
    }
    java.lang.Long.parseLong(res, 2)
  }.mkString("\n"))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  println((1 to n).map{ _ =>
    val Array(l, r) = in.next().split(' ').map(_.toLong)
    val lStr = l.toBinaryString
    val rStr = r.toBinaryString
    val res = if (lStr.length < rStr.length) {
      val str = "1" * rStr.length
      if (rStr == str) str else str.tail
    }
    else {
      rStr.zip(lStr).foldLeft((List.empty[Char], false)) {
        case ((list, true), (f, s)) => ('1' :: list, true)
        case ((list, false), (f, s)) if f == s => (f :: list, false)
        case ((list, false), (f, s)) => (f :: list, true)
      }._1.reverse.mkString
    }
    java.lang.Long.parseLong(res, 2)
  }.mkString("\n"))
}


A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they get bored, and if one compartment contain three or four students, then the compartment has fun throughout the entire trip.The students want to swap with other people, so that no compartment with students had bored students. To swap places with another person, you need to convince him that it is really necessary. The students can not independently find the necessary arguments, so they asked a sympathetic conductor for help. The conductor can use her life experience to persuade any passenger to switch places with some student.However, the conductor does not want to waste time persuading the wrong people, so she wants to know what is the minimum number of people necessary to persuade her to change places with the students. Your task is to find the number. After all the swaps each compartment should either have no student left, or have a company of three or four students.

The first line contains integer n (1 ≤ n ≤ 106) — the number of compartments in the carriage. The second line contains n integers a1, a2, ..., an showing how many students ride in each compartment (0 ≤ ai ≤ 4). It is guaranteed that at least one student is riding in the train.

If no sequence of swapping seats with other people leads to the desired result, print number "-1" (without the quotes). In another case, print the smallest number of people you need to persuade to swap places.

import scala.collection._

object E extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  def consolidate1() = {
    val c = counts(1) / 3
    counts(3) += c
    counts(1) -= 3 * c
    2 * c// + move(1, 3)
  }

  def consolidate2() = {
    val c = counts(2) / 3
    counts(2) = counts(2) % 3
    counts(3) += 2 * c
    if (counts(2) == 2) {
      counts(2) = 0
      counts(4) += 1
      2 * c + 2
    } else 2 * c
  }

  var moves = move(1, 2) + consolidate1() + consolidate2() //+ move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3)

  if (counts(1) == 1) {
	  moves += move(1, 3) + move(4, 1) + move(4, 2)
  } else if (counts(1) == 2) {
     if (counts(3) > 1) moves += move(1, 3)
     else if (counts(4) > 0){
       moves += 2
       counts(1) = 0
     }
  } else if (counts(2) == 1) {
      moves += move(4, 2) + move(2, 3) + move(1, 3)
  }
  //+ move(4, 1) + move(1, 2) + move(4, 2)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)

  if (counts(2) == 2) {
    moves += 2
    counts(2) = 0
  }
//println(counts(1), counts(2), counts(3), counts(4))
  println(if (counts(1) + counts(2) > 0) -1 else moves)
}

import scala.collection._

object E extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  def consolidate1() = {
    val c = counts(1) / 3
    counts(3) += c
    counts(1) -= 3 * c
    2 * c// + move(1, 3)
  }

  def consolidate2() = {
    val c = counts(2) / 3
    counts(2) = counts(2) % 3
    2 * c
  }

  var moves = move(1, 2) + consolidate1() + consolidate2() + move(4, 2) // //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)
//println(counts(1), counts(2), counts(3), counts(4))
  println(if (counts(1) + counts(2) > 0) -1 else moves)
}

import scala.collection._

object E extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  def consolidate1() = {
    val c = counts(1) / 3
    counts(3) += c
    counts(1) -= 3 * c
    2 * c// + move(1, 3)
  }

  def consolidate2() = {
    val c = counts(2) / 2
    counts(2) = 0
    2 * c
  }

  var moves = move(1, 2) + consolidate1() + move(4, 2) + consolidate2() + move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)

/*println(counts(1), counts(2))
  if (counts(2) > 1) {
    val consolidate2 = counts(2) / 2
    moves += consolidate2 * 2
    counts(2) = 0
  }

  moves += consolidate1()*/
  println(if (counts(1) + counts(2) > 0) -1 else moves)
}

import scala.collection._

object E extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  def consolidate1() = {
    val c = counts(1) / 3
    counts(3) += c
    counts(1) -= 3 * c
    2 * c + move(1, 3)
  }

  var moves = move(1, 2) + consolidate1() + move(4, 2) + move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)

  if (counts(2) > 1) {
    val consolidate2 = counts(2) / 2
    moves += consolidate2 * 2
    counts(2) = 0
  }

  moves += consolidate1()

  println(if (counts(1) + counts(2) > 0) -1 else moves)
}

import scala.collection._

object E  extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  var moves = move(1, 2) + move(4, 2) + move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)

  if (counts(2) > 1) {
    val consolidate2 = counts(2) / 2
    moves += consolidate2 * 2
    counts(2) = 0
  }

  val consolidate1 = counts(1) / 3
  moves += consolidate1 * 2
  counts(3) += consolidate1
  counts(1) -= 3 * consolidate1
  moves += move(1, 3)

  println(if (counts(1) + counts(2) > 0) -1 else moves)
}

import scala.collection._

object E extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  def consolidate1() = {
    val c = counts(1) / 3
    counts(3) += c
    counts(1) -= 3 * c
    2 * c// + move(1, 3)
  }

  def consolidate2() = {
    val c = counts(2) / 3
    counts(2) = counts(2) % 3
    counts(3) += 2 * c
    if (counts(2) == 2) {
      counts(2) = 0
      counts(4) += 1
      2 * c + 2
    } else 2 * c
  }

  var moves = move(1, 2) + consolidate1() + consolidate2() //+ move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3)

  if (counts(1) == 1) {
	  moves += move(1, 3) + move(4, 1) + move(4, 2)
  } else if (counts(1) == 2) {
     if (counts(3) > 1) moves += move(1, 3)
     else if (counts(4) > 0){
       moves += 2
       counts(1) = 0
     }
  } else if (counts(2) == 1) {
      moves += move(4, 2)
  }
  //+ move(4, 1) + move(1, 2) + move(4, 2)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)

  if (counts(2) == 2) {
    moves += 2
    counts(2) = 0
  }
//println(counts(1), counts(2), counts(3), counts(4))
  println(if (counts(1) + counts(2) > 0) -1 else moves)
}

import scala.collection._

object E extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  def consolidate1() = {
    val c = counts(1) / 3
    counts(3) += c
    counts(1) -= 3 * c
    2 * c// + move(1, 3)
  }

  def consolidate2() = {
    val c = counts(2) / 3
    counts(2) = counts(2) % 3
    2 * c
  }

  var moves = move(1, 2) + consolidate1() + consolidate2() + move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3) + move(4, 1) + move(1, 2) + move(4, 2)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)

  if (counts(2) == 2) {
    moves += 2
    counts(2) = 0
  }
//println(counts(1), counts(2), counts(3), counts(4))
  println(if (counts(1) + counts(2) > 0) -1 else moves)
}

import scala.collection._

object E extends App {
  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }
  def readLongs(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toLong) }
  def readBigs(n: Int) = { val t = tokenizeLine; Array.fill(n)(BigInt(t.nextToken)) }

  val counts = Array.fill(5)(0)

  val n = readString.toInt
  readInts(n).foreach(counts(_) += 1)

  def move(from: Int, to: Int) = {
    val can = counts(from) min counts(to)
    counts(from) -= can
    counts(from - 1) += can
    counts(to + 1) += can
    counts(to) -= can
    can
  }

  def consolidate1() = {
    val c = counts(1) / 3
    counts(3) += c
    counts(1) -= 3 * c
    2 * c// + move(1, 3)
  }

  def consolidate2() = {
    val c = counts(2) / 3
    counts(2) = counts(2) % 3
    2 * c
  }

  var moves = move(1, 2) + consolidate1() + consolidate2() + move(4, 2) + move(2, 3) + move(1, 2) + move(1, 3)// //+ move(1, 3) + move(2, 3) + move(1, 3) + move(1, 2) + move(4, 1) + move(1, 2)
//println(counts(1), counts(2), counts(3), counts(4))
  println(if (counts(1) + counts(2) > 0) -1 else moves)
}


Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."The class can be represented as a matrix with n rows and m columns with a student in each cell. Two students are neighbors if cells in which they sit have a common side.Let's enumerate students from 1 to n·m in order of rows. So a student who initially sits in the cell in row i and column j has a number (i - 1)·m + j. You have to find a matrix with n rows and m columns in which all numbers from 1 to n·m appear exactly once and adjacent numbers in the original matrix are not adjacent in it, or determine that there is no such matrix.

The only line contains two integers n and m (1 ≤ n, m ≤ 105; n·m ≤ 105) — the number of rows and the number of columns in the required matrix.

If there is no such matrix, output "NO" (without quotes).  Otherwise in the first line output "YES" (without quotes), and in the next n lines output m integers which form the required matrix.

NoteIn the first test case the matrix initially looks like this:1 2 3 45 6 7 8It's easy to see that there are no two students that are adjacent in both matrices.In the second test case there are only two possible seatings and in both of them students with numbers 1 and 2 are neighbors.

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) {
    println("YES")
    println(1)
  } else if (n == 3 && m == 3) {
    println("YES")
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs0 = Array.tabulate(n0, m0) { (r, c) =>
      r * m0 + c + 1
    }

    val xs = if (n0 > m0) xs0.transpose else xs0

    for {
      r <- 0 until n
    } {
      if (r % 2 == 1) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 == 2) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t3
          xs(r)(oo + 1) = t1
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        } else if (m % 4 == 3) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        } else if (m % 4 == 1) {
          val oo = m - 2
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t0
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 == 2) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t1
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t3
        } else if (m % 4 == 3) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) {
    println("YES")
    println(1)
  } else if (n == 3 && m == 3) {
    println("YES")
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs0 = Array.tabulate(n0, m0) { (r, c) =>
      r * m0 + c + 1
    }

    val xs = if (n0 > m0) xs0.transpose else xs0

    for {
      r <- 0 until n
    } {
      if (r % 2 == 1) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 == 1) {
          val oo = m - 2
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t0
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 == 2) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t1
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t3
        } else if (m % 4 == 3) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) {
    println("YES")
    println(1)
  } else if (n == 3 && m == 3) {
    println("YES")
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs = Array.tabulate(n, m) { (r, c) =>
      r * m + c + 1
    }
    //xs.foreach(row => println(row.mkString(" ")))
    for {
      r <- 0 until n
    } {
      if (r % 2 == 0) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 == 1) {
          val oo = m - 2
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t0
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) {
    println("YES")
    println(1)
  } else if (n == 3 && m == 3) {
    println("YES")
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs = Array.tabulate(n, m) { (r, c) =>
      r * m + c + 1
    }

    for {
      r <- 0 until n
    } {
      if (r % 2 == 1) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 == 1) {
          val oo = m - 2
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t0
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 == 2) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t1
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t3
        } else if (m % 4 == 3) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) println(1)
  else if (n == 3 && m == 3) {
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs = Array.tabulate(n, m) { (r, c) =>
      r * m + c + 1
    }
    //xs.foreach(row => println(row.mkString(" ")))
    for {
      r <- 0 until n
    } {
//      if (r % 2 == 1) {
//        val rev = Array.ofDim[Int](m)
//        for (i <- 0 until m) rev(i) = xs(r)(m - i - 1)
//        xs(r) = rev
//      }
      if (r % 2 == 0) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 > 0) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 > 0) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) println(1)
  else if (n == 3 && m == 3) {
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs = Array.tabulate(n, m) { (r, c) =>
      r * m + c + 1
    }
    //xs.foreach(row => println(row.mkString(" ")))
    for {
      r <- 0 until n
    } {
//      if (r % 2 == 1) {
//        val rev = Array.ofDim[Int](m)
//        for (i <- 0 until m) rev(i) = xs(r)(m - i - 1)
//        xs(r) = rev
//      }
      if (r % 2 == 0) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 > 0) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 > 0) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) {
    println("YES")
    println(1)
  } else if (n == 3 && m == 3) {
    println("YES")
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs0 = Array.tabulate(n0, m0) { (r, c) =>
      r * m0 + c + 1
    }

    val xs = if (n0 > m0) xs0.transpose else xs0

    for {
      r <- 0 until n
    } {
      if (r % 2 == 1) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 == 2) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t3
          xs(r)(oo + 1) = t1
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        } else if (m % 4 == 3) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        } else if (m % 4 == 1) {
          val oo = m - 2
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t0
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 == 2) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t1
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t3
        } else if (m % 4 == 3) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) println(1)
  else if (n == 3 && m == 3) {
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs = Array.tabulate(n, m) { (r, c) =>
      r * m + c + 1
    }
    //xs.foreach(row => println(row.mkString(" ")))
    for {
      r <- 0 until n
    } {
      if (r % 2 == 0) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 == 1) {
          val oo = m - 2
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t0
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}

object D 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(n0, m0) = readInts(2)
  val n = n0 min m0
  val m = n0 max m0

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  if (n == 1 && m == 1) {
    println("YES")
    println(1)
  } else if (n == 2 && m == 3) {
    println("YES")
    println("2 6 1")
    println("4 3 5")
  } else if (n == 3 && m == 2) {
    println("YES")
    println("2 4")
    println("6 3")
    println("1 5")
  } else if (n == 3 && m == 3) {
    println("YES")
    println("8 3 4")
    println("1 5 9")
    println("6 7 2")
  } else if (n <= 3 && m <= 3) println("NO") else {

    val xs = Array.tabulate(n, m) { (r, c) =>
      r * m + c + 1
    }
    //xs.foreach(row => println(row.mkString(" ")))
    for {
      r <- 0 until n
    } {
      if (r % 2 == 0) {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t3
          xs(r)(oo + 2) = t0
          xs(r)(oo + 3) = t2
        }
        if (m % 4 == 1) {
          val oo = m - 2
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          xs(r)(oo) = t1
          xs(r)(oo + 1) = t0
        }
      } else {
        for (o <- 0 until m / 4) {
          val oo = 4 * o
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
        if (m % 4 > 1) {
          val oo = m - 4
          val t0 = xs(r)(oo)
          val t1 = xs(r)(oo + 1)
          val t2 = xs(r)(oo + 2)
          val t3 = xs(r)(oo + 3)
          xs(r)(oo) = t2
          xs(r)(oo + 1) = t0
          xs(r)(oo + 2) = t3
          xs(r)(oo + 3) = t1
        }
      }
    }

    val xs2 = if (n0 > m0) xs.transpose else xs

    println("YES")
    xs2.foreach(row => println(row.mkString(" ")))
  }

  Console.flush
}


Ann and Borya have n piles with candies and n is even number. There are ai candies in pile with number i.Ann likes numbers which are square of some integer and Borya doesn't like numbers which are square of any integer. During one move guys can select some pile with candies and add one candy to it (this candy is new and doesn't belong to any other pile) or remove one candy (if there is at least one candy in this pile). Find out minimal number of moves that is required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer.

First line contains one even integer n (2 ≤ n ≤ 200 000) — number of piles with candies. Second line contains sequence of integers a1, a2, ..., an (0 ≤ ai ≤ 109) — amounts of candies in each pile.

Output minimal number of steps required to make exactly n / 2 piles contain number of candies that is a square of some integer and exactly n / 2 piles contain number of candies that is not a square of any integer. If condition is already satisfied output 0.

NoteIn first example you can satisfy condition in two moves. During each move you should add one candy to second pile. After it size of second pile becomes 16. After that Borya and Ann will have two piles with number of candies which is a square of integer (second and fourth pile) and two piles with number of candies which is not a square of any integer (first and third pile).In second example you should add two candies to any three piles.

import java.util.Scanner

import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve(): Long = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]

      val squared = A.map(x => squares.contains(x))
      val squaredCount = squared.count(_ == true)

      def distanceToNearestSquare(x: Int): Long = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else {
        A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
      }
    }

    println(solve())
  }
}

import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve(): Long = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]
      val squaredCount = A.map(x => squares.contains(x)).count(_ == true)

      def distanceToNearestSquare(x: Int): Long = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
    }

    println(solve())
  }
}

import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve(): Long = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]
      val squaredCount = A.count(x => squares.contains(x))

      def distanceToNearestSquare(x: Int): Long = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
    }

    println(solve())
  }
}

import java.util.Scanner

import scala.collection.immutable.TreeSet

object SquaresAndNotSquares {
  def main(args: Array[String]): Unit = {
    val R = scala.io.Source.stdin.bufferedReader()
    val N = R.readLine().toInt
    val A = R.readLine().split(" ").map(s => s.toInt)

    def solve() = {
      val squares = 0.to(40000).map(x => x * x).to[TreeSet]

      val squared = A.map(x => squares.contains(x))
      val squaredCount = squared.count(_ == true)

      def distanceToNearestSquare(x: Int) = {
       if (squares.contains(x)) 0
       else {
         val lower = squares.to(x).lastKey
         var higher = squares.from(x).firstKey

         Math.min(x - lower, higher - x)
       }
      }

      if (squaredCount >= N / 2) A.filter(x => squares.contains(x)).map(x => if (x == 0) 2 else 1).sorted.take(squaredCount - (N / 2)).sum
      else {
        A.filter(x => !squares.contains(x)).map(distanceToNearestSquare).sorted.take((N / 2) - squaredCount).sum
      }
    }

    println(solve())
  }
}


Masha has $$$n$$$ types of tiles of size $$$2 \times 2$$$. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.Masha decides to construct the square of size $$$m \times m$$$ consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of this square has to be covered with exactly one tile cell, and also sides of tiles should be parallel to the sides of the square. All placed tiles cannot intersect with each other. Also, each tile should lie inside the square. See the picture in Notes section for better understanding.Symmetric with respect to the main diagonal matrix is such a square $$$s$$$ that for each pair $$$(i, j)$$$ the condition $$$s[i][j] = s[j][i]$$$ holds. I.e. it is true that the element written in the $$$i$$$-row and $$$j$$$-th column equals to the element written in the $$$j$$$-th row and $$$i$$$-th column.Your task is to determine if Masha can construct a square of size $$$m \times m$$$ which is a symmetric matrix and consists of tiles she has. Masha can use any number of tiles of each type she has to construct the square. Note that she can not rotate tiles, she can only place them in the orientation they have in the input.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$) — the number of types of tiles and the size of the square Masha wants to construct. The next $$$2n$$$ lines of the test case contain descriptions of tiles types. Types of tiles are written one after another, each type is written on two lines.  The first line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the top left corner of the tile and the number written in the top right corner of the tile of the current type. The second line of the description contains two positive (greater than zero) integers not exceeding $$$100$$$ — the number written in the bottom left corner of the tile and the number written in the bottom right corner of the tile of the current type. It is forbidden to rotate tiles, it is only allowed to place them in the orientation they have in the input.

For each test case print the answer: "YES" (without quotes) if Masha can construct the square of size $$$m \times m$$$ which is a symmetric matrix. Otherwise, print "NO" (withtout quotes).

NoteThe first test case of the input has three types of tiles, they are shown on the picture below.  Masha can construct, for example, the following square of size $$$4 \times 4$$$ which is a symmetric matrix:

//package codeforces.contests._1426

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

      val result = (1 to n).map { _ =>
        val row0, row1 = io.StdIn.readLine.split(" ").map(_.toInt)
        row0(1) == row1(0)
      }.exists(identity) && m % 2 == 0

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

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val tiles = (0 until n).foldLeft(0) {
      case (ts, _) =>
        val Array(a, b) = readLine().split(" ").map(_.toInt)
        val Array(c, d) = readLine().split(" ").map(_.toInt)

        if (b == c) ts + 1 else ts
    }

    val ans = if (m % 2 == 0 && tiles >= 1) "YES" else "NO"

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val tiles = (0 until n).foldLeft(0) {
      case (ts, _) =>
        val Array(a, b) = readLine().split(" ").map(_.toInt)
        val Array(c, d) = readLine().split(" ").map(_.toInt)

        if (a == d && b == c) ts + 1 else ts
    }

    val ans = if (m % 2 == 0 && tiles >= 1) "YES" else "NO"

    println(ans)
  }
}