The length of the longest common prefix of two strings $$$s = s_1 s_2 \ldots s_n$$$ and $$$t = t_1 t_2 \ldots t_m$$$ is defined as the maximum integer $$$k$$$ ($$$0 \le k \le min(n,m)$$$) such that $$$s_1 s_2 \ldots s_k$$$ equals $$$t_1 t_2 \ldots t_k$$$.Koa the Koala initially has $$$n+1$$$ strings $$$s_1, s_2, \dots, s_{n+1}$$$.For each $$$i$$$ ($$$1 \le i \le n$$$) she calculated $$$a_i$$$ — the length of the longest common prefix of $$$s_i$$$ and $$$s_{i+1}$$$.Several days later Koa found these numbers, but she couldn't remember the strings.So Koa would like to find some strings $$$s_1, s_2, \dots, s_{n+1}$$$ which would have generated numbers $$$a_1, a_2, \dots, a_n$$$. Can you help her?If there are many answers print any. We can show that answer always exists for the given constraints.

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in the list $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 50$$$) — the elements of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$100$$$.

For each test case: Output $$$n+1$$$ lines. In the $$$i$$$-th line print string $$$s_i$$$ ($$$1 \le |s_i| \le 200$$$), consisting of lowercase Latin letters. Length of the longest common prefix of strings $$$s_i$$$ and $$$s_{i+1}$$$ has to be equal to $$$a_i$$$. If there are many answers print any. We can show that answer always exists for the given constraints.

aeren
ari
arousal
around
ari
monogon
monogamy
monthly
kevinvu
kuroni
kurioni
korone
anton
loves
adhoc
problems

NoteIn the $$$1$$$-st test case one of the possible answers is $$$s = [aeren, ari, arousal, around, ari]$$$.Lengths of longest common prefixes are:  Between $$$\color{red}{a}eren$$$ and $$$\color{red}{a}ri$$$ $$$\rightarrow 1$$$  Between $$$\color{red}{ar}i$$$ and $$$\color{red}{ar}ousal$$$ $$$\rightarrow 2$$$  Between $$$\color{red}{arou}sal$$$ and $$$\color{red}{arou}nd$$$ $$$\rightarrow 4$$$  Between $$$\color{red}{ar}ound$$$ and $$$\color{red}{ar}i$$$ $$$\rightarrow 2$$$

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m         = in.nextInt()
      val intInputs = in.line().split(" ").map(_.toInt).toList
      val temN      = intInputs.head :: intInputs

      var lastString = ""
      temN.indices
        .foreach(f = index => {
          if (index == 0) {
            lastString = lastString + "m" * 100
          } else {
            val copy     = temN(index)
            val fromLast = if (copy == 0) "" else lastString.substring(0, copy)

            val char = if (fromLast.isEmpty) {
              if (lastString(0) == 'm') "n" else "m"
            } else {
              val in = fromLast.length
              if (lastString(in) == 'm') "n" else "m"
            }

            lastString = fromLast + char * (100 - copy)
          }
          println(lastString)
        })

      /*
      var lastChar1 = true
      var char      = "a"
      temN.indices
        .foreach(f = index => {
          val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)
          if (temN(index) == 0) {
            if (lastChar1) {
              lastChar1 = false
              char = "c"
            } else {
              lastChar1 = true
              char = "a"
            }
          }
          println(if (t == 0) char else char * t)
        })*/
//      println("-----------")
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m         = in.nextInt()
      val intInputs = in.line().split(" ").map(_.toInt).toList
      val temN      = intInputs.head :: intInputs

      val string1 = "c"
      (0.until(temN.length))
        .foreach(f = index => {
          val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)
          val s = if (t == 0 && index % 2 == 0) "c" else if (t == 0 && index % 2 == 1) "b" else "a" * t
          println(s)
        })
//      println("-----------")
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m         = in.nextInt()
      val intInputs = in.line().split(" ").map(_.toInt).toList
      val temN      = intInputs.head :: intInputs

      val string1 = "c"
      (0.until(temN.length))
        .foreach(f = index => {
          val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)
          val s = if (t == 0 && index % 2 == 0) "c" else if (t == 0 && index % 2 == 1) "a" else "a" * t
          println(s)
        })
//      println("-----------")
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m         = in.nextInt()
      val intInputs = in.line().split(" ").map(_.toInt).toList
      val temN      = intInputs.head :: intInputs

      var lastString = ""
      temN.indices
        .foreach(f = index => {
          if (index == 0) {
            lastString = lastString + "m" * 100
          } else {
            val copy     = temN(index)
            val fromLast = if (copy == 0) "" else lastString.substring(0, copy)

            val char = if (fromLast.isEmpty) {
              if (lastString(0) == 'm') "n" else "m"
            } else {
              val in = math.max(fromLast.length - 1, 0)
              if (fromLast(in) == 'm') "n" else "m"
            }

            lastString = fromLast + char * (100 - copy)
          }
          println(lastString)
        })

      /*
      var lastChar1 = true
      var char      = "a"
      temN.indices
        .foreach(f = index => {
          val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)
          if (temN(index) == 0) {
            if (lastChar1) {
              lastChar1 = false
              char = "c"
            } else {
              lastChar1 = true
              char = "a"
            }
          }
          println(if (t == 0) char else char * t)
        })*/
//      println("-----------")
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val m         = in.nextInt()
      val intInputs = in.line().split(" ").map(_.toInt).toList
      val temN      = intInputs.head :: intInputs

      var lastChar1 = true
      var char      = "a"
      temN.indices
        .foreach(f = index => {
          val t = if (index < m) math.max(temN(index), temN(index + 1)) else temN(index)
          if (temN(index) == 0) {
            if (lastChar1) {
              lastChar1 = false
              char = "c"
            } else {
              lastChar1 = true
              char = "a"
            }
          }
          println(if (t == 0) char else char * t)
        })
//      println("-----------")
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.A string is called a substring of another string, if it can be obtained from that string by dropping some (possibly zero) number of characters from the beginning and from the end of it. For example, "abc", "ab", and "c" are substrings of the string "abc", while "ac" and "d" are not.Let's define a palindromic count of the string as the number of its substrings that are palindromes. For example, the palindromic count of the string "aaa" is $$$6$$$ because all its substrings are palindromes, and the palindromic count of the string "abc" is $$$3$$$ because only its substrings of length $$$1$$$ are palindromes.You are given a string $$$s$$$. You can arbitrarily rearrange its characters. You goal is to obtain a string with the maximum possible value of palindromic count.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the length of string $$$s$$$. The second line contains string $$$s$$$ that consists of exactly $$$n$$$ lowercase characters of Latin alphabet.

Print string $$$t$$$, which consists of the same set of characters (and each characters appears exactly the same number of times) as string $$$s$$$. Moreover, $$$t$$$ should have the maximum possible value of palindromic count among all such strings strings. If there are multiple such strings, print any of them.

NoteIn the first example, string "ololo" has $$$9$$$ palindromic substrings: "o", "l", "o", "l", "o", "olo", "lol", "olo", "ololo". Note, that even though some substrings coincide, they are counted as many times as they appear in the resulting string.In the second example, the palindromic count of string "abccbaghghghgdfd" is $$$29$$$.

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 S = ns(N)
    val C = Array.ofDim[Int](26)
    rep(N) { i =>
      C(S(i) - 'a') += 1
    }

    C.zipWithIndex.sortBy(_._1) foreach { case (cnt1, a1) =>
      rep(cnt1) { i =>
        out.print(('a' + a1).toChar)
      }
    }

    out.println()
  }

  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 S = ns(N)
    val C = Array.ofDim[Int](26)
    rep(N) { i =>
      C(S(i) - 'a') += 1
    }

    C.zipWithIndex.sortBy(_._1).reverse.grouped(2) foreach { g =>
      if (g.length > 1) {
        val (cnt1, a1) = g(0)
        val (cnt2, a2) = g(1)

        // a1a1a1a2a1a2a1
        rep(cnt1 - cnt2) { i =>
          out.print(('a' + a1).toChar)
        }
        rep(cnt2) { i =>
          out.print(('a' + a2).toChar)
          out.print(('a' + a1).toChar)
        }
      } else {
        val (cnt1, a1) = g(0)
        rep(cnt1) { i =>
          out.print(('a' + a1).toChar)
        }
      }
    }

    out.println()
  }

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


The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.

The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.

Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.

6
Jack captain
Alice woman
Charlie man
Teddy rat
Bob child
Julia woman

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(" ")).toList
  println(
    (data.filter(_.last == "rat") ::: data.filter(j => j.last == "woman" || j.last == "child")
      ::: data.filter(j => j.last == "man") ::: data.filter(j => j.last == "captain")).map(_.head).mkString("\n"))
}

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

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

  // rats < women == children < men < captain
  // rats 0
  // women 1
  // children 1
  // men 2
  // captain 3

  val priority = Map("rat" -> 0,
                     "woman" -> 1,
                     "child" -> 1,
                     "man" -> 2,
                     "captain" -> 3)

  val N = sc.nextInt
  sc.nextLine
  val crewList: List[(String, Int)] = List.fill(N)(sc.nextLine).map {
      case s: String => {
        val List(name, status) = s.split(" ").toList
        (name, priority(status))
      }
    }.sortBy(_._2)

  crewList.foreach { tpl =>
    out.println(tpl._1)
  }
  out.close
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" "))

    val bs = scala.collection.mutable.Buffer[Array[String]]()

    bs ++= a.filter(_.apply(1) == "rat")
    bs ++= a.filter(a0 => a0(1) == "woman" || a0(1) == "child")
    bs ++= a.filter(_.apply(1) == "man")
    bs ++= a.filter(_.apply(1) == "captain")

    bs.foreach(s => println(s.toSeq.apply(0)))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(" "))
  println(data.filter(_.last == "rat").map(_.head).mkString("\n"))
  println(data.filter(j => j.last == "woman" || j.last == "child").map(_.head).mkString("\n"))
  println(data.filter(j => j.last == "man").map(_.head).mkString("\n"))
  println(data.filter(j => j.last == "captain").map(_.head).mkString("\n"))

}


Lena is a beautiful girl who likes logical puzzles.As a gift for her birthday, Lena got a matrix puzzle!The matrix consists of $$$n$$$ rows and $$$m$$$ columns, and each cell is either black or white. The coordinates $$$(i,j)$$$ denote the cell which belongs to the $$$i$$$-th row and $$$j$$$-th column for every $$$1\leq i \leq n$$$ and $$$1\leq j \leq m$$$. To solve the puzzle, Lena has to choose a cell that minimizes the Manhattan distance to the farthest black cell from the chosen cell.More formally, let there be $$$k \ge 1$$$ black cells in the matrix with coordinates $$$(x_i,y_i)$$$ for every $$$1\leq i \leq k$$$. Lena should choose a cell $$$(a,b)$$$ that minimizes $$$$$$\max_{i=1}^{k}(|a-x_i|+|b-y_i|).$$$$$$As Lena has no skill, she asked you for help. Will you tell her the optimal cell to choose?

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2\leq n,m \leq 1000$$$)  — the dimensions of the matrix.  The following $$$n$$$ lines contain $$$m$$$ characters each, each character is either 'W' or 'B'. The $$$j$$$-th character in the $$$i$$$-th of these lines is 'W' if the cell $$$(i,j)$$$ is white, and 'B' if the cell $$$(i,j)$$$ is black.  It is guaranteed that at least one black cell exists. It is guaranteed that the sum of $$$n\cdot m$$$ does not exceed $$$10^6$$$.

For each test case, output the optimal cell $$$(a,b)$$$ to choose. If multiple answers exist, output any.

5
3 2
BW
WW
WB
3 3
WWB
WBW
BWW
2 3
BBB
BBB
5 5
BWBWB
WBWBW
BWBWB
WBWBW
BWBWB
9 9
WWWWWWWWW
WWWWWWWWW
BWWWWWWWW
WWWWWWWWW
WWWWBWWWW
WWWWWWWWW
WWWWWWWWW
WWWWWWWWW
WWWWWWWWB

NoteIn the first test case the two black cells have coordinates $$$(1,1)$$$ and $$$(3,2)$$$. The four optimal cells are $$$(1,2)$$$, $$$(2,1)$$$, $$$(2,2)$$$ and $$$(3,1)$$$. It can be shown that no other cell minimizes the maximum Manhattan distance to every black cell.In the second test case it is optimal to choose the black cell $$$(2,2)$$$ with maximum Manhattan distance being $$$2$$$.

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var aa = 0
      var bb = 0
      var AA = List[Int]()
      var AAA = List[Int]()
      if ((s1+s2) % 2 == 0) {
       AA ::=  (s1 + s2) /2
      }
      else {
        AA ::= (s1 + s2 + 1) / 2
        AA ::= (s1 + s2 - 1) / 2
      }
      if ((s3+s4) % 2 == 0) {
        AAA ::=  (s3 + s4) /2
      }
      else {
        AAA ::= (s3 + s4 + 1) / 2
        AAA ::= (s3 + s4 - 1) / 2
      }
      var qqq = 0
      for {h <- AA;
           f <- AAA
           if (h+f) % 2 ==0}{
        qqq+=1
        aa = (h + f) / 2
        bb = (h - f) / 2
      }
      if (qqq == 0) {
        if (s2 - s1 > s4 - s3) {
          aa = (AA.last + AAA.last+1) / 2
          bb = (AA.last - AAA.last-1) / 2
        }
        else {
          aa = (AA.last + AAA.last+1) / 2
          bb = (AA.last - AAA.last+1) / 2
        }
      }
      aa +=1
      bb +=1
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var aa = 0
      var bb = 0
      var AA = List[Int]()
      var AAA = List[Int]()
      if ((s1+s2) % 2 == 0) {
       AA ::=  (s1 + s2) /2
      }
      else {
        AA ::= (s1 + s2 + 1) / 2
        AA ::= (s1 + s2 - 1) / 2
      }
      if ((s3+s4) % 2 == 0) {
        AAA ::=  (s3 + s4) /2
      }
      else {
        AAA ::= (s3 + s4 + 1) / 2
        AAA ::= (s3 + s4 - 1) / 2
      }
      var qqq = 0
      for {h <- AA;
           f <- AAA
           if (h+f) % 2 ==0}{
        qqq+=1
        aa = (h + f) / 2
        bb = (h - f) / 2
      }
      if (qqq == 0) {
        if (s2 - s1 > s4 - s3) {
          aa = (AA.last + AAA.last+1) / 2
          bb = (AA.last - AAA.last+1) / 2
        }
      }
      aa +=1
      bb +=1
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var sa = 0
      var da = 0
      var aa = 0
      var bb = 0
      var mins: Long = 100000000
      for {o <- scala.math.max(0, -10 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 10);
           p <- scala.math.max(-m+1,-10 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +10)
           if (o+p) % 2 == 0} {
        if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {
            mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))
            sa = o
            da = p
        }
      }
      sa = sa+2
      aa = (sa+da) / 2
      bb = (sa - da) / 2
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var sa = 0
      var da = 0
      var aa = 0
      var bb = 0
      var mins = 1000000
      for {o <- scala.math.max(0, -10 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 10);
           p <- scala.math.max(-m+1,-10 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +10)
           if (o+p) % 2 == 0} {
        if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {
            mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))
            sa = o
            da = p
        }
      }
      sa = sa+2
      aa = (sa+da) / 2
      bb = (sa - da) / 2
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var sa = 0
      var da = 0
      var aa = 0
      var bb = 0
      var mins = 100000000
      for {o <- scala.math.max(0, -10 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 10);
           p <- scala.math.max(-m+1,-10 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +10)
           if (o+p) % 2 == 0} {
        if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {
            mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))
            sa = o
            da = p
        }
      }
      sa = sa+2
      aa = (sa+da) / 2
      bb = (sa - da) / 2
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var sa = 0
      var da = 0
      var aa = 0
      var bb = 0
      var mins = 100000000
      for {o <- scala.math.max(0, -1 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 1);
           p <- scala.math.max(-m+1,-1 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +1)
           if (o+p) % 2 == 0} {
        if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {
            mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))
            sa = o
            da = p
        }
      }
      sa = sa+2
      aa = (sa+da) / 2
      bb = (sa - da) / 2
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var sa = 0
      var da = 0
      var aa = 0
      var bb = 0
      var mins = 100000000
      for {o <- scala.math.max(0, -1 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 1);
           p <- scala.math.max(-m+1,-1 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +1)
           if (o+p) % 2 == 0} {
        if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {
            mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))
            sa = o+2
            da = p
        }
      }
      aa = (sa+da) / 2
      bb = (sa - da) / 2
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var sa = 0
      var da = 0
      var aa = 0
      var bb = 0
      var mins = 100000000
      for {o <- scala.math.max(0, -5 + ((s1+s2)/2)) to scala.math.min(m+n-2,((s1+s2)/2) + 5);
           p <- scala.math.max(-m+1,-5 + (s3+s4/2)) to scala.math.min(n-1, ((s3+s4)/2) +5)
           if (o+p) % 2 == 0} {
        if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {
            mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))
            sa = o+2
            da = p
        }
      }
      aa = (sa+da) / 2
      bb = (sa - da) / 2
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.math.abs

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var sa = 0
      var da = 0
      var aa = 0
      var bb = 0
      var mins = 10000000
      for {o <- scala.math.max(0, -3 + (s1+s2)/2) to scala.math.min(m+n-2,(s1+s2)/2 + 3);
           p <- scala.math.max(-m+1,-3 + (s3+s4/2)) to scala.math.min(n-1, (s3+s4)/2 +3)
           if (o+p) % 2 == 0} {
        if (scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4)))) < mins) {
            mins = scala.math.max(abs(o - s1),scala.math.max(abs(o - s2),scala.math.max(abs(p -s3), abs(p - s4))))
            sa = o+2
            da = p
        }
      }
      aa = (sa+da) / 2
      bb = (sa - da) / 2
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var aa = 0
      var bb = 0
      if ((((s2+s1 + 4) / 2) - ((s3 + s4) / 2) ) % 2 !=0 ) {
        if ((s2+s1+4) % 2 == 1) {
          aa = (((s2+s1+4)/2) + 1 + ((s3 + s4) / 2)) / 2
          bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2
        }
        else if (((s3+s4) % 2 == 1) && (s3+s4 >= 0)) {
          aa = (((s2+s1+4)/2) + 1 + ((s3 + s4) / 2)) / 2
          bb = (((s2+s1+4)/2) - 1 - ((s3 + s4) / 2)) / 2
        }
        else if (((s3+s4) % 2 == 1) && (s3+s4 < 0)) {
          aa = (((s2+s1+4)/2) - 1 + ((s3 + s4) / 2)) / 2
          bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2
        }
        else if (s2 - s1 > s4 - s3){
          aa = (((s2+s1+4)/2) - 1 + ((s3 + s4) / 2)) / 2
          bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2
        }
        else if (s2 - s1 > s4 - s3){
          aa = (((s2+s1+4)/2) + 1 + ((s3 + s4) / 2)) / 2
          bb = (((s2+s1+4)/2) + 1 - ((s3 + s4) / 2)) / 2
        }
      }
      else {
        aa = (((s2+s1+4)/2) + ((s3 + s4) / 2)) / 2
        bb = (((s2+s1+4)/2) - ((s3 + s4) / 2)) / 2
      }
      output.println(aa.toString+" "+ bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var aa = 0
      var bb = 0
      if (((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {
        if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {
          if ((s1+s2+4) % 2 == 1) {
            aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
          else {
            aa = (1*scala.math.signum(s3+s4)  + ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (-1*scala.math.signum(s3+s4)  + ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
        }
        else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
          bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2

        }
      }
      else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {
        if (s2 -s1 > s4-s3) {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1*scala.math.signum(s3+s4) ) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1*scala.math.signum(s3+s4) ) / 2
        }
        else {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2
        }
      }
      else {
        aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
        bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
      }
      output.println(aa.toString+" " + bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var aa = 0
      var bb = 0
      if (((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {
        if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {
          if ((s1+s2+4) % 2 == 1) {
            aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
          else {
            aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (-1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
        }
        else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
          bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2

        }
      }
      else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {
        if (s2 -s1 > s4-s3) {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1) / 2
        }
        else {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2
        }
      }
      else {
        aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
        bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
      }
      output.println(aa.toString+" " + bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }

      var aa = 0
      var bb = 0
      if ( ((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {
        if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {
          if ((s1+s2+4) % 2 == 1) {
            aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
          else {
            aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (-1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
        }
        else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
          bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2

        }
      }
      else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) / 2 != 0) {
        if (s2 -s1 > s4-s3) {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1) / 2
        }
        else {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2
        }
      }
      else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
        bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
      }
      output.println(aa.toString+" " + bb.toString)
    }
  }
}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object prob2 {
  def main(args: Array[String]) = {
    import scala.collection.mutable.ListBuffer
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer

  def run() {
    def scan1(s: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,s-A(0).length+1) to scala.math.min((A.length-1),s)) {
        if (A(j)(s-j) == "B"(0))
        i = false
      }
      i
    }
    def scan2(d: Int, A: Array[String]): Boolean = {
      var i= true
      for (j <- scala.math.max(0,d) to scala.math.min((A.length-1),d+A(0).length-1)) {
        if (A(j)(j-d) == "B"(0))
          i = false
      }
      i
    }
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (i <- 1 to q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken.toInt
      val m = tokenizer.nextToken.toInt
      val A = ListBuffer.empty[String]
      for (j <- 1 to n) {
        tokenizer = new StringTokenizer(input.readLine())
        A+= tokenizer.nextToken()
      }
      var s1 = 0
      val B = A.toArray
      while (scan1(s1,B)) {
        s1+=1
      }
      var s2 = n+m-2
      while (scan1(s2,B)) {
        s2-=1
      }
      var s3 = -m+1
      while (scan2(s3,B)) {
        s3+=1
      }

      var s4 = n-1
      while (scan2(s4,B)) {
        s4-=1
      }
      var aa = 0
      var bb = 0
      if ( ((s1+s2+4) % 2 == 1) || ((s3+s4) % 2 == 1 )) {
        if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {
          if ((s1+s2+4) % 2 == 1) {
            aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
          else {
            aa = (1+ ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
            bb = (-1+ ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
          }
        }
        else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
          bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2

        }
      }
      else if ((((s1+s2+4) / 2 ) - ((s3+s4) / 2)) % 2 != 0) {
        if (s2 -s1 > s4-s3) {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) - 1) / 2
        }
        else {
          aa = (((s1+s2+4) / 2 ) + ((s3+s4) / 2) + 1) / 2
          bb = (((s1+s2+4) / 2 ) - ((s3+s4) / 2) + 1) / 2
        }
      }
      else { aa = ( ((s1+s2+4)/2) + ((s3+s4) / 2)) / 2
        bb = ( ((s1+s2+4)/2) - ((s3+s4) / 2)) / 2
      }
      output.println(aa.toString+" " + bb.toString)
    }
  }
}


Permutation $$$p$$$ is a sequence of integers $$$p=[p_1, p_2, \dots, p_n]$$$, consisting of $$$n$$$ distinct (unique) positive integers between $$$1$$$ and $$$n$$$, inclusive. For example, the following sequences are permutations: $$$[3, 4, 1, 2]$$$, $$$[1]$$$, $$$[1, 2]$$$. The following sequences are not permutations: $$$[0]$$$, $$$[1, 2, 1]$$$, $$$[2, 3]$$$, $$$[0, 1, 2]$$$.The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $$$p$$$ of length $$$n$$$. You don't know this permutation, you only know the array $$$q$$$ of prefix maximums of this permutation. Formally:  $$$q_1=p_1$$$,  $$$q_2=\max(p_1, p_2)$$$,  $$$q_3=\max(p_1, p_2,p_3)$$$,  ...  $$$q_n=\max(p_1, p_2,\dots,p_n)$$$. You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $$$q$$$ for this permutation is equal to the given array).

The first line contains integer number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ $$$(1 \le n \le 10^{5})$$$ — the number of elements in the secret code permutation $$$p$$$. The second line of a test case contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ $$$(1 \le q_i \le n)$$$ — elements of the array $$$q$$$ for secret permutation. It is guaranteed that $$$q_i \le q_{i+1}$$$ for all $$$i$$$ ($$$1 \le i < n$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.

For each test case, print:   If it's impossible to find such a permutation $$$p$$$, print "-1" (without quotes).  Otherwise, print $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). If there are multiple possible answers, you can print any of them.

import scala.io.StdIn._
import scala.collection.mutable.ArrayBuffer
object Main extends App{
    // Your code here!
    val t = readInt()
    for (i <- 1 to t) {
        val n = readInt()
        val arr = readLine().split(" ").map(_.toInt)
        var curr = 1
        val vis = new Array[Boolean](n+1)
        val res = ArrayBuffer[Int]()
        var flag = false
        for (j <- 0 until arr.length) {
            vis(arr(j)) = true
            if (j > 0 && arr(j) == arr(j-1)) {
                while(vis(curr)) curr += 1
                if (curr >= arr(j)) {
                    flag = true
                } else {
                    res += curr
                    vis(curr) = true
                    curr += 1
                }
            } else {
                res += arr(j)
            }
        }
        if (flag) {
            print(-1)
        } else {
            for (k <- 0 until n) print(s"${res(k)} ")
        }
        println()
    }
}

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

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

  def solve1(): Unit = {
    val N = ni()
    val A = na(N)
    val B = Array.ofDim[Int](N)
    val used = Array.ofDim[Boolean](N + 1)
    var p = 1
    var mx = 0
    REP(N) { i =>
      if (A(i) > mx) {
        mx = A(i)
        B(i) = A(i)
        used(A(i)) = true
      } else {
        while(p <= mx && used(p)) p += 1
        if (p > mx) {
          out.println(-1)
          return
        }
        B(i) = p
        used(p) = true
      }
    }
    out.println(B.mkString(" "))
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve1()
    }
  }
}


One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by $$$n$$$ machines, and the power of the $$$i$$$-th machine is $$$a_i$$$. This year 2D decided to cultivate a new culture, but what exactly he didn't say. For the successful growth of the new culture, it is necessary to slightly change the powers of the machines. 2D can at most once choose an arbitrary integer $$$x$$$, then choose one machine and reduce the power of its machine by $$$x$$$ times, and at the same time increase the power of one another machine by $$$x$$$ times (powers of all the machines must stay positive integers). Note that he may not do that if he wants. More formally, 2D can choose two such indices $$$i$$$ and $$$j$$$, and one integer $$$x$$$ such that $$$x$$$ is a divisor of $$$a_i$$$, and change powers as following: $$$a_i = \frac{a_i}{x}$$$, $$$a_j = a_j \cdot x$$$Sasha is very curious, that's why he wants to calculate the minimum total power the farmer can reach. There are too many machines, and Sasha can't cope with computations, help him!

The first line contains one integer $$$n$$$ ($$$2 \le n \le 5 \cdot 10^4$$$) — the number of machines. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the powers of the machines.

Print one integer — minimum total power.

NoteIn the first example, the farmer can reduce the power of the $$$4$$$-th machine by $$$2$$$ times, and increase the power of the $$$1$$$-st machine by $$$2$$$ times, then the powers will be: $$$[2, 2, 3, 2, 5]$$$.In the second example, the farmer can reduce the power of the $$$3$$$-rd machine by $$$2$$$ times, and increase the power of the $$$2$$$-nd machine by $$$2$$$ times. At the same time, the farmer can leave is be as it is and the total power won't change.In the third example, it is optimal to leave it be as it is.

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 A = na(N)
    val B = Array.ofDim[Boolean](101)
    REP(N) { i =>
      B(A(i)) |= true
    }
//    debug(B)

    val sum = A.sum
    var diff = 0
    val ms = A.min
//    debug(ms)
    REP_r(101) { a =>
      if (B(a) && ms < a) {
        val D = divisors(a)
        REP(D.length) { i =>
          val d = D(i)
          val gain = a / d - a + ms * d - ms
//          debug(s"$a $d $gain")
          diff = min(diff, gain)
        }
      }
    }

    val ans = sum + min(0, diff)
    out.println(ans)
  }

  /**
    * O(√x)
    */
  def divisors(x: Int): Array[Int] = {
    val pre = ArrayBuffer[Int]()
    val post = ArrayBuffer[Int]()
    REP(math.sqrt(x).toInt, 1) { d =>
      if (x % d == 0) {
        pre += d
        if (d * d != x) post += x / d
      }
    }

    val res = Array.ofDim[Int](pre.length + post.length)
    REP(pre.length)(i => res(i) = pre(i))
    val preLen = pre.length
    val postLen = post.length
    REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))
    res
  }

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

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

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

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

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

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

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

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

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

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

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

object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var a = arr.sorted
		var i = n-1
		var sum = 0
		for (i <- 0 until n)
			sum += a(i)
		i = n-1
		var rez = sum
		var najmal = a(0)

		while (i > 0)
		{
			for (j <- 1 to a(i))
				if (a(i) % j == 0)
				{
					var new_rez = min(rez, sum - a(i) - a(0) + a(i) / j + a(0)*j)
					rez = new_rez
				}
			i -= 1
		}

		println(rez)
	}
}

object Main
{
	def min (a : Int, b : Int) : Int =
		if (a < b) return a
		else return b
	def main (args : Array[String]) =
	{
		val n = readLine.toInt
		val arr = readLine.split(' ').map(_.toInt)

		var a = arr.sorted
		var i = n-1
		var sum = 0
		for (i <- 0 until n)
			sum += a(i)
		i = n-1
		var rez = sum
		var najmal = a(0)

		while (i > 0)
		{
			for (j <- 1 to a(i))
				if (a(i) % j == 0)
				{
					var new_rez = min(rez, rez - a(i) - a(0) + a(i) / j + a(0)*j)
					rez = new_rez
				}
			i -= 1
		}

		println(rez)
	}
}


This is the hard version of the problem. The only difference is that in this version $$$n \leq 200000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 200000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.

Output a single integer, the maximum number of potions you can drink without your health becoming negative.

NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point

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

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ").map(_.toLong)

  def slowSolution(n: Int, a: Array[Long]): Long = {
    val init = (0 to n).map {i => if (i == 0) 0l else -1l }
    val results = a.foldLeft(init) { (v, next) =>
      (0 to n).map { i =>
        if (i == 0)
          0
        else if (v(i - 1) == -1)
          -1
        else
          Math.max(v(i), v(i - 1) + next)
      }
    }
    (0 to n).filter(results(_) != -1).max
  }

  def fastSolution(n: Int, a: Array[Long]): Long = {
    val q = new mutable.PriorityQueue[Long].reverse
    val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>
      val (curResult, curSum) = state;
      if (next + curSum >= 0) {
        q.enqueue(next)
        (curResult + 1, next + curSum)
      } else if (q.nonEmpty && q.head < next) {
        val old = q.dequeue()
        q.enqueue(next)
        (curResult, curSum - old + next)
      } else {
        (curResult, curSum)
      }
    }
    result
  }

  println(fastSolution(n, a))
}

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

object Main extends App {
  val n = StdIn.readLine().toInt
  val a = StdIn.readLine().split(" ").map(_.toLong)
  val q = new mutable.PriorityQueue[Long].reverse
  val (result, _) = a.foldLeft((0l, 0l)) { (state, next) =>
    val (curResult, curSum) = state;
    if (next + curSum >= 0) {
      q.enqueue(next)
      (curResult + 1, next + curSum)
    } else if (q.nonEmpty && q.head < next) {
      val old = q.dequeue()
      q.enqueue(next)
      (curResult, curSum - old + next)
    } else {
      (curResult, curSum)
    }
  }

  println(result)
}


You are given two integers $$$a$$$ and $$$b$$$. You may perform any number of operations on them (possibly zero).During each operation you should choose any positive integer $$$x$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$ or $$$a := a - 2x$$$, $$$b := b - x$$$. Note that you may choose different values of $$$x$$$ in different operations.Is it possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously?Your program should answer $$$t$$$ independent test cases.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow, each test case is represented by one line containing two integers $$$a$$$ and $$$b$$$ for this test case ($$$0 \le a, b \le 10^9$$$).

For each test case print the answer to it — YES if it is possible to make $$$a$$$ and $$$b$$$ equal to $$$0$$$ simultaneously, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first test case of the example two operations can be used to make both $$$a$$$ and $$$b$$$ equal to zero:  choose $$$x = 4$$$ and set $$$a := a - x$$$, $$$b := b - 2x$$$. Then $$$a = 6 - 4 = 2$$$, $$$b = 9 - 8 = 1$$$;  choose $$$x = 1$$$ and set $$$a := a - 2x$$$, $$$b := b - x$$$. Then $$$a = 2 - 2 = 0$$$, $$$b = 1 - 1 = 0$$$.

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

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      var a, b = ni()
      val ok =
        a == 0 && b == 0 || {
          // a <= b にする
          if (a > b) {
            val t = a
            a = b
            b = t
          }

          if (a * 2 < b)
            false
          else {
            val ccc = 2 * a - b
            debug(s"ccc:$ccc")
            ccc % 3 == 0 && {
              val c = ccc / 3
              debug(s"c:$c")
              (a - 2 * c) * 2 == b - c
            }
          }
        }

      if (ok) out.println("YES")
      else out.println("NO")
    }
  }
}

import scala.io.StdIn._
object Main{
  def main(args: Array[String]): Unit ={
    val N = readInt()
    for(_ <- 0 until N){
      val line = readLine().split(" ").map(_.toInt)
      val a = line(0)
      val b = line(1)
      def valid(a: Int) = a % 3 == 0 && a >= 0
      println(if(valid(2*b - a) && valid(2*a - b)) "YES" else "NO")
    }
  }
}