object A600 {
  def main(args: Array[String]) = {
    val input = readLine

    def isInteger(word: String): Boolean = {
      if (word.length == 0) false
      else if (word.exists{case d => !Character.isDigit(d)}) false
      else if (word(0) == '0') word.length == 1
      else true
    }

    val (integers, nonIntegers) = input.split("[,;]", -1).partition { case word => isInteger(word) }

    def convertToString(arr: Array[String]): String = {
      if (arr.length == 0) "-" else "\"" + arr.mkString(",") + "\""
    }

    println(convertToString(integers))
    println(convertToString(nonIntegers))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  def isNumber(str: String) = {
    str.forall(i => i >= '0' && i <= '9') && str.length > 0 && (str.head != '0' || str.length == 1)
  }

  val (a, b) = in.next().split("[;,]", -1).partition(isNumber)
  if (a.nonEmpty)
    println(a.mkString("\"", ",", "\""))
  else
    println("-")
  if (b.nonEmpty)
    println(b.mkString("\"", ",", "\""))
  else
    println("-")
}

object Task1 {
  def main(args: Array[String]) {
    val r = readLine()
    val normalize = if (r.last == ',' || r.last == ';') r + " " else r
    val res = normalize.split(Array(';', ','))
    val regexp = "\\d+"

    val p = res.partition { rr => rr.matches(regexp) && ! (rr.head == '0' && rr.length > 1)}
    val str1 = if (p._1.isEmpty) "-" else "\"" + p._1.mkString(",").trim + "\""
    val str2 = if (p._2.isEmpty) "-" else "\"" + p._2.mkString(",").trim + "\""
    println(str1)
    println(str2)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  def isNumber(str: String) = {
    str.forall(i => i >= '0' && i <= '9') && str.length > 0 && (str.head != '0' || str.length == 1)
  }

  val (a, b) = in.next().split("[;,]").partition(isNumber)
  if (a.nonEmpty)
    println(a.mkString("\"", ",", "\""))
  else
    println("-")
  if (b.nonEmpty)
    println(b.mkString("\"", ",", "\""))
  else
    println("-")
}

object Task1 {
  def main(args: Array[String]) {
    val r = readLine()
    val normalize = if (r.last == ',' || r.last == ';') r + " " else r
    val res = normalize.split(Array(';', ','))
    val regexp = "\\d+"

    val p = res.partition { rr =>
        rr.matches(regexp) && (rr.length > 1 && rr.head != '0')
    }
    val str1 = if (p._1.isEmpty) "-" else "\"" + p._1.mkString(",").trim + "\""
    val str2 = if (p._2.isEmpty) "-" else "\"" + p._2.mkString(",").trim + "\""
    println(str1)
    println(str2)
  }
}

object Task1 {

  import scala.util.{Success, Failure, Try}

  def main(args: Array[String]) {
    val r = readLine()
    val normalize = if (r.last == ',' || r.last == ';') r + " " else r
    val res = normalize.split(Array(';', ','))
    val p = res.partition { rr =>
      Try(rr.toInt) match {
        case Success(_) if rr.length > 1 && rr.head == '0' => false
        case Success(_) => true
        case _ => false
      }
    }
    val str1 = if (p._1.isEmpty) "-" else "\"" + p._1.mkString(",").trim + "\""
    val str2 = if (p._2.isEmpty) "-" else "\"" + p._2.mkString(",").trim + "\""
    println(str1)
    println(str2)
  }
}

object Task1 {
  def main(args: Array[String]) {
    val r = readLine()
    val normalize = if (r.last == ',' || r.last == ';') r + " " else r
    val res = normalize.split(Array(';', ','))
    val regexp = "\\d+"

    val p = res.partition { rr =>
        rr.matches(regexp) && (rr=="0" || (rr.head != '0' && rr.length > 1))
    }
    val str1 = if (p._1.isEmpty) "-" else "\"" + p._1.mkString(",").trim + "\""
    val str2 = if (p._2.isEmpty) "-" else "\"" + p._2.mkString(",").trim + "\""
    println(str1)
    println(str2)
  }
}

object Task1 {
  import scala.util.{Success, Failure, Try}

  def  main (args: Array[String]){
   val r = readLine()
    val res = r.split(Array(';',','))
    val p = res.partition{rr=>
      Try(rr.toInt) match {
        case Success(_) if rr.length>1 && rr.head == '0' => false
        case Success(_) => true
        case _ => false
      }
    }
    val str1 = if(p._1.isEmpty) "-" else p._1.mkString(",")
    val str2 = if(p._2.isEmpty) "-" else p._2.mkString(",")
    println("\""+str1+"\"")
    println("\""+str2+"\"")
    }
}

object Task1 {

  import scala.util.{Success, Failure, Try}

  def main(args: Array[String]) {
    val r = readLine()
    val normalize = if (r.last == ',' || r.last == ';') r + " " else r
    val res = normalize.split(Array(';', ','))
    val p = res.partition { rr =>
      Try(rr.toInt) match {
        case Success(_) if rr.length > 1 && rr.head == '0' => false
        case Success(_) => true
        case _ => false
      }
    }
    val str1 = if (p._1.isEmpty) "-" else p._1.mkString(",")
    val str2 = if (p._2.isEmpty) "-" else p._2.mkString(",")
    println("\"" + str1.trim + "\"")
    println("\"" + str2.trim + "\"")
  }
}

object Task1 {

  import scala.util.{Success, Failure, Try}

  def main(args: Array[String]) {
    val r = readLine()
    val normalize = if (r.last == ',' || r.last == ';') r + " " else r
    val res = normalize.split(Array(';', ','))
    val p = res.partition { rr =>
      Try(rr.toInt) match {
        case Success(_) if rr.length > 1 && rr.head == '0' => false
        case Success(_) => true
        case _ => false
      }
    }
    val str1 = if (p._1.isEmpty) "-" else "\"" + p._1.mkString(",") + "\""
    val str2 = if (p._2.isEmpty) "-" else "\"" + p._2.mkString(",") + "\""
    println(str1.trim)
    println(str2.trim)
  }
}


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

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int]

    val ans = if(n == 1) {
      "-1"
    } else if ((n-1)%3 != 0) {
      ("2" * (n-1)) + "3"
    } else {
      ("2" * (n-2)) + "73"
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any*): this.type = writeAll(obj)
  def writeLine(obj: Any*): this.type = {if (obj.isEmpty) printer.println() else obj.foreach(printer.println); this}
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = {printer.print(obj.mkString(separator)); this}
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()

    val sb = new mutable.StringBuilder()
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      if(n == 1){
        sb.append(-1).append(System.lineSeparator())
      }else{
        sb.append(2)
        sb.append((1 until n).map(_ => "3").mkString(""))
        sb.append(System.lineSeparator())
      }
    }
    out.print(sb.toString())
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()

    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      if(n == 1){
        out.println(-1)
      }else{
        if(n==2){
         out.println(57)
        }else {
          if (n % 2 == 0) {
            val res = (1 to (n - 2)).map(_ => '2').mkString("") + "33"
            out.println(res)
          } else {
            val res = (1 until n).map(_ => '2').mkString("") + "3"
            out.println(res)
          }
        }
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()

    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      if(n == 1){
        out.println(-1)
      }else{
        if(n%2==0){
          val res = (1 to (n-2)).map(_ => '2').mkString("")+"33"
          out.println(res)
        }else{
          val res = (1 until n).map(_ => '2').mkString("")+ "3"
          out.println(res)
        }
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()

    val sb = new mutable.StringBuilder()
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      if(n == 1){
        sb.append(-1).append(System.lineSeparator())
      }else{
        if(n==2){
          sb.append(57).append(System.lineSeparator())
        }else {
          if (n % 2 == 0) {
            val res = (1 to (n - 2)).map(_ => "2").mkString("") + "33"
            sb.append(res).append(System.lineSeparator())
          } else {
            val res = (1 until n).map(_ => "2").mkString("") + "3"
            sb.append(res).append(System.lineSeparator())
          }
        }
      }
    }
    out.print(sb.toString())
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()

    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      if(n == 1){
        out.println(-1)
      }else{
        if(n%2==0){
          val res = (1 to n).map(_ => '3').mkString("")
          out.println(res)
        }else{
          val res = (1 until n).map(_ => '2').mkString("")+ "3"
          out.println(res)
        }
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


import java.util.PriorityQueue

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  for (r <- 0 until n) {
    for (c <- 0 until n) {
      if (grid(r)(c) == 'B') {
        if (c < minHor(r)) minHor(r) = c
        if (r < minVert(c)) minVert(c) = r
        if (c > maxHor(r)) maxHor(r) = c
        if (r > maxVert(c)) maxVert(c) = r
      }
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val base = best

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    val in, out = new PriorityQueue[Int]
    for (i <- r until r + k) {
      if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {
        in.add(maxHor(i))
        out.add(minHor(i))
      }
    }
    var addHor = 0
    var addVert = 0
    for (c <- 0 until k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
    }
    for (c <- 0 to  n - k) {
      val cc = c + k - 1
      while (!in.isEmpty && in.peek <= cc) {
        in.poll()
        addHor += 1
      }
      while (!out.isEmpty && out.peek < c) {
        out.poll()
        addHor -= 1
      }
      if (base + addHor + addVert > best) {
        best = base + addHor + addVert
      }
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      if (cc + 1 < n && maxVert(cc + 1) >= 0 && minVert(cc + 1) >= r && maxVert(cc + 1) <= rr) addVert += 1
    }
  }

  println(best)
}

import java.util.PriorityQueue

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  {
    var r = 0
    while (r < n) {
      var c = 0
      while (c < n) {
        if (grid(r)(c) == 'B') {
          if (c < minHor(r)) minHor(r) = c
          if (r < minVert(c)) minVert(c) = r
          if (c > maxHor(r)) maxHor(r) = c
          if (r > maxVert(c)) maxVert(c) = r
        }
        c += 1
      }
      r += 1
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val base = best

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    val in, out = new PriorityQueue[Int]
    //val out = mutable.PriorityQueue.empty[Int]//(Ordering.by(minHor).reverse)
    var i = r
    while (i < r + k) {
      if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {
        in.add(maxHor(i))
        out.add(minHor(i))
      }
      i += 1
    }
    var addHor = 0
    var addVert = 0
    var c = 0
    while (c < k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
      c += 1
    }
    c = 0
    var cc = c + k - 1
    while (c <= n - k) {
      while (!in.isEmpty && in.peek <= cc) {
        in.poll()
        addHor += 1
      }
      while (!out.isEmpty && out.peek < c) {
        out.poll()
        addHor -= 1
      }
      if (base + addHor + addVert > best) {
        best = base + addHor + addVert
      }
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      cc += 1
      if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1
      c += 1
    }
  }

  println(best)
}

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  for (r <- 0 until n) {
    for (c <- 0 until n) {
      if (grid(r)(c) == 'B') {
        if (c < minHor(r)) minHor(r) = c
        if (r < minVert(c)) minVert(c) = r
        if (c > maxHor(r)) maxHor(r) = c
        if (r > maxVert(c)) maxVert(c) = r
      }
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val score = Array.fill(n - k + 1, n - k + 1)(best)

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    var addVert = 0
    for (c <- 0 until k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
    }
    for (c <- 0 to n - k) {
      score(r)(c) += addVert
      val cc = c + k
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1
    }
  }

  for (c <- 0 to n - k) {
    val cc = c + k - 1
    var addHor = 0
    for (r <- 0 until k) {
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor += 1
    }
    for (r <- 0 to n - k) {
      score(r)(c) += addHor
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1
      val rr = r + k
      if (rr < n && maxHor(rr) >= 0 && minHor(rr) >= c && maxHor(rr) <= cc) addHor += 1
    }
  }

  var max = 0
  for (s1 <- score) {
    for (s2 <- s1) {
      if (s2 > max) max = s2
    }
  }

  println(max)
}

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  for (r <- 0 until n) {
    for (c <- 0 until n) {
      if (grid(r)(c) == 'B') {
        if (c < minHor(r)) minHor(r) = c
        if (r < minVert(c)) minVert(c) = r
        if (c > maxHor(r)) maxHor(r) = c
        if (r > maxVert(c)) maxVert(c) = r
      }
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val score = Array.fill(n - k + 1, n - k + 1)(best)

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    var addVert = 0
    for (c <- 0 until k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
    }
    for (c <- 0 to n - k) {
      score(r)(c) += addVert
      val cc = c + k
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1
    }
  }

  for (c <- 0 to n - k) {
    val cc = c + k - 1
    var addHor = 0
    for (r <- 0 until k) {
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor += 1
    }
    for (r <- 0 to n - k) {
      score(r)(c) += addHor
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1
      val rr = r + k
      if (rr < n && maxHor(rr) >= 0 && minHor(rr) >= c && maxHor(rr) <= cc) addHor += 1
    }
  }

  println(score.flatten.max)
}

import java.util.PriorityQueue

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  {
    var r = 0
    while (r < n) {
      var c = 0
      while (c < n) {
        if (grid(r)(c) == 'B') {
          if (c < minHor(r)) minHor(r) = c
          if (r < minVert(c)) minVert(c) = r
          if (c > maxHor(r)) maxHor(r) = c
          if (r > maxVert(c)) maxVert(c) = r
        }
        c += 1
      }
      r += 1
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val base = best

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    val in, out = new PriorityQueue[Int]
    var i = r
    while (i < r + k) {
      if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {
        in.add(maxHor(i))
        out.add(minHor(i))
      }
      i += 1
    }
    var addHor = 0
    var addVert = 0
    var c = 0
    while (c < k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
      c += 1
    }
    c = 0
    var cc = c + k - 1
    while (c <= n - k) {
      while (!in.isEmpty && in.peek <= cc) {
        in.poll()
        addHor += 1
      }
      while (!out.isEmpty && out.peek < c) {
        out.poll()
        addHor -= 1
      }
      if (base + addHor + addVert > best) {
        best = base + addHor + addVert
      }
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      cc += 1
      if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1
      c += 1
    }
  }

  println(best)
}

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  for (r <- 0 until n) {
    for (c <- 0 until n) {
      if (grid(r)(c) == 'B') {
        if (c < minHor(r)) minHor(r) = c
        if (r < minVert(c)) minVert(c) = r
        if (c > maxHor(r)) maxHor(r) = c
        if (r > maxVert(c)) maxVert(c) = r
      }
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val score = Array.fill(n - k + 1, n - k + 1)(best)

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    var addVert = 0
    for (c <- 0 until k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
    }
    for (c <- 0 to n - k) {
      val cc = c + k - 1
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      if (cc + 1 < n && maxVert(cc + 1) >= 0 && minVert(cc + 1) >= r && maxVert(cc + 1) <= rr) addVert += 1
      score(r)(c) += addVert
    }
  }

  for (c <- 0 to n - k) {
    val cc = c + k - 1
    var addHor = 0
    for (r <- 0 until k) {
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(c) <= cc) addHor += 1
    }
    for (r <- 0 to n - k) {
      val rr = r + k - 1
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1
      if (rr + 1 < n && maxHor(rr + 1) >= 0 && minHor(rr + 1) >= c && maxHor(rr + 1) <= cc) addHor += 1
      score(r)(c) += addHor
    }
  }

  println(score.flatten.max)
}

import scala.collection.mutable

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  {
    var r = 0
    while (r < n) {
      var c = 0
      while (c < n) {
        if (grid(r)(c) == 'B') {
          if (c < minHor(r)) minHor(r) = c
          if (r < minVert(c)) minVert(c) = r
          if (c > maxHor(r)) maxHor(r) = c
          if (r > maxVert(c)) maxVert(c) = r
        }
        c += 1
      }
      r += 1
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val base = best

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    val in = mutable.PriorityQueue.empty[Int]//(Ordering.by(maxHor).reverse)
    val out = mutable.PriorityQueue.empty[Int]//(Ordering.by(minHor).reverse)
    var i = r
    while (i < r + k) {
      if (maxHor(i) >= 0 && maxHor(i) - minHor(i) <= k) {
        in += maxHor(i)
        out += minHor(i)
      }
      i += 1
    }
    var addHor = 0
    var addVert = 0
    var c = 0
    while (c < k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
      c += 1
    }
    c = 0
    var cc = c + k - 1
    while (c <= n - k) {
      while (in.nonEmpty && in.head <= cc) {
        in.dequeue()
        addHor += 1
      }
      while (out.nonEmpty && out.head < c) {
        out.dequeue()
        addHor -= 1
      }
      if (base + addHor + addVert > best) {
        best = base + addHor + addVert
      }
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      cc += 1
      if (cc < n && maxVert(cc) >= 0 && minVert(cc) >= r && maxVert(cc) <= rr) addVert += 1
      c += 1
    }
  }

  println(best)
}

object D extends App {

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

  val Array(n, k) = readInts(2)
  val grid = Array.fill(n){ readLine }

  val minHor, minVert = Array.fill(n) { n }
  val maxHor, maxVert = Array.fill(n) { -1 }

  for (r <- 0 until n) {
    for (c <- 0 until n) {
      if (grid(r)(c) == 'B') {
        if (c < minHor(r)) minHor(r) = c
        if (r < minVert(c)) minVert(c) = r
        if (c > maxHor(r)) maxHor(r) = c
        if (r > maxVert(c)) maxVert(c) = r
      }
    }
  }

  var best = 0
  for (i <- 0 until n) {
    if (maxVert(i) == -1) best += 1
    if (maxHor(i) == -1) best += 1
  }
  val score = Array.fill(n - k + 1, n - k + 1)(best)

  for (r <- 0 to n - k) {
    val rr = r + k - 1
    var addVert = 0
    for (c <- 0 until k) {
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert += 1
    }
    for (c <- 0 to n - k) {
      val cc = c + k - 1
      if (maxVert(c) >= 0 && minVert(c) >= r && maxVert(c) <= rr) addVert -= 1
      if (cc + 1 < n && maxVert(cc + 1) >= 0 && minVert(cc + 1) >= r && maxVert(cc + 1) <= rr) addVert += 1
      score(r)(c) += addVert
    }
  }

  for (c <- 0 to n - k) {
    val cc = c + k - 1
    var addHor = 0
    for (r <- 0 until k) {
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor += 1
    }
    for (r <- 0 to n - k) {
      val rr = r + k - 1
      if (maxHor(r) >= 0 && minHor(r) >= c && maxHor(r) <= cc) addHor -= 1
      if (rr + 1 < n && maxHor(rr + 1) >= 0 && minHor(rr + 1) >= c && maxHor(rr + 1) <= cc) addHor += 1
      score(r)(c) += addHor
    }
  }

  println(score.flatten.max)
}


import scala.io.StdIn

object MiracleSleeper extends App{
  val testCases = StdIn.readInt()
  for (_ <- 1 to testCases) {
    val input = StdIn.readLine().split(" ")
    val low = input.apply(0).toInt
    val high = input.apply(1).toInt

    val mid = Math.ceil(high/2.0).toInt

    if (mid >= low) {
      println(mid-1)
    } else {
      println(high-low)
    }
  }
}

object A extends App {
  def remainder(from: Int, to: Int): Int = {
    val t = if (to % 2 == 0) 2 else 1
    val d = from max ((to + t) / 2)
    to % d
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(l, r) = readLine().split(" ").map(_.toInt)

    val ans = remainder(l, r)

    println(ans)
  }

}


import java.util.Scanner

import scala.collection.immutable._

object RemoveExtraOne {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val p = for (i <- 0.until(N)) yield sc.nextInt()

    def process(i: Int, set: TreeSet[Int], inc: Array[Int]): Int = {
      if (i == N) {
        inc.indexOf(inc.max) + 1
      }
      else {
        val higherSet = set.from(p(i) + 1)
        if (higherSet.size == 0) process(i + 1, set + p(i), inc.updated(p(i) - 1, inc(p(i) - 1) - 1))
        else if (higherSet.size == 1) {
          val higherElement = higherSet.firstKey
          process(i + 1, set + p(i), inc.updated(higherElement - 1, inc(higherElement - 1) + 1))
        }
        else process(i + 1, set + p(i), inc)
      }
    }

    val answer = process(0, TreeSet.empty, Array.tabulate(N)(_ => 0))
    println(answer)
  }
}

object Main extends App {

  import scala.io.StdIn

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

  var mx1 = 0
  var mx2 = 0

  val cnt = new Array[Integer](n+1)
  val maybe = new Array[Boolean](n+1)
  val index = new Array[Integer](n+1)

  var set = new scala.collection.mutable.TreeSet[Integer]()

  for (i <- 0 until n) {
    maybe(i) = a(i) > mx2
    index(a(i)) = i
    cnt(i+1) = cnt(i)
    if (a(i) > mx1) cnt(i+1) += 1
    if (a(i) > mx1) {
      mx2 = mx1
      mx1 = a(i)
    }
    else
    if (a(i) > mx2) {
      mx2 = a(i)
    }

    set.add(a(i))
  }

  var r = 0
  var mx = 0
  var ans = n

  for (i <- n-1 to 0 by -1) {

    if (cnt(i) + r > mx) {
      mx = cnt(i) + r
      ans = a(i)
    }
    else
    if (cnt(i) + r == mx) ans = Math.min(ans, a(i))

    if (maybe(i)) {
      val mx = set.last
      if (mx > a(i)) cnt(index(mx)) += 1 else r += 1
    }
    set.remove(a(i))
  }

  println(ans)
}

import java.util.Scanner

import scala.collection.immutable._

object RemoveExtraOne {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val p = for (i <- 0.until(N)) yield sc.nextInt()

    def process(i: Int, set: TreeSet[Int], candidates: TreeMap[Int, Int], hopeless: TreeSet[Int]): Int = {
      if (i == N) {
        if (candidates.size == 0) {
          if (hopeless.size == 0) 1 else hopeless.min
        }
        else if (candidates.values.max == 1) (hopeless.toList ++ candidates.keys).min
        else candidates.filter{case (_, freq) => freq == candidates.values.max}.keys.min
      }
      else {
        val higherSet = set.from(p(i) + 1)
        if (higherSet.size == 1) {
          val higherElement = higherSet.firstKey
          process(i + 1, set + p(i), candidates.updated(higherElement, 1 + candidates.getOrElse(higherElement, 0)), hopeless)
        }
        else if (higherSet.size > 1) process(i + 1, set + p(i), candidates, hopeless + p(i))
        else process(i + 1, set + p(i), candidates, hopeless)
      }
    }

    val answer = process(0, TreeSet.empty, TreeMap.empty, TreeSet.empty)
    println(answer)
  }
}

import java.util.Scanner

import scala.collection.immutable._

object RemoveExtraOne {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val p = for (i <- 0.until(N)) yield sc.nextInt()

    def process(i: Int, set: TreeSet[Int], candidates: TreeMap[Int, Int]): Int = {
      if (i == N) {
        if (candidates.size == 0) N else candidates.filter{case (_, freq) => freq == candidates.values.max}.keys.min
      }
      else {
        val higherSet = set.from(p(i) + 1)
        if (higherSet.size == 1) {
          val higherElement = higherSet.firstKey
          process(i + 1, set + p(i), candidates.updated(higherElement, 1 + candidates.getOrElse(higherElement, 0)))
        }
        else process(i + 1, set + p(i), candidates)
      }
    }

    val answer = process(0, TreeSet.empty, TreeMap.empty)
    println(answer)
  }
}

import java.util.Scanner

import scala.collection.immutable._

object RemoveExtraOne {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val p = for (i <- 0.until(N)) yield sc.nextInt()

    def process(i: Int, set: TreeSet[Int], candidates: TreeMap[Int, Int], hopeless: TreeSet[Int]): Int = {
      if (i == N) {
        if (candidates.size == 0) {
          if (hopeless.size == 0) 1 else hopeless.min
        } else candidates.filter{case (_, freq) => freq == candidates.values.max}.keys.min
      }
      else {
        val higherSet = set.from(p(i) + 1)
        if (higherSet.size == 1) {
          val higherElement = higherSet.firstKey
          process(i + 1, set + p(i), candidates.updated(higherElement, 1 + candidates.getOrElse(higherElement, 0)), hopeless)
        }
        else if (higherSet.size > 1) process(i + 1, set + p(i), candidates, hopeless + p(i))
        else process(i + 1, set + p(i), candidates, hopeless)
      }
    }

    val answer = process(0, TreeSet.empty, TreeMap.empty, TreeSet.empty)
    println(answer)
  }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(n / 2 * n + (if (n % 2 != 0) (n + 1) / 2 else 0))
  println(Range(0, n).map(i => Range(0, n).map(j => if ((j + i) % 2 == 0) 'C' else '.').mkString).mkString("\n"))
}

//1.1.1
//.1.1.
//1.1.1
//.1.1.
//1.1.1

import java.util.StringTokenizer

object _384A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val cb = (0 until n).map(i => if (i % 2 == 0) 'C' else '.').mkString("")
  val wb = (0 until n).map(i => if (i % 2 == 1) 'C' else '.').mkString("")
  val a = cb.count(i => i == 'C')
  val b = wb.count(i => i == 'C')

  var sum = 0
  for (i <- 0 until n)
    if (i % 2 == 0) sum = sum + a
    else sum = sum + b
  println(sum)
  for (i <- 0 until n)
    if (i % 2 == 0) println(cb)
    else println(wb)
}

object A384 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val res = Array.fill(n)(Array.fill[Char](n)('.'))
    for(i <- 0 until n) {
      val start = if(i%2 == 0) 0 else 1
      for(j <- start until n by 2) {
        res(i)(j) = 'C'
      }
    }
    println(res.map(x => x.count(_ == 'C')).sum)
    println(res.map(_.mkString("")).mkString("\n"))
  }

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

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

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

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

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

}

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

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

  val numC = N * N / 2 + N % 2
  out.println(numC)

  0 until N foreach { i =>
    0 until N foreach { j =>
      if (i % 2 == j % 2) out.print('C')
      else out.print('.')
    }
    out.println
  }

  out.close
}

import java.util.StringTokenizer

object _384A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val cb = (0 until n).map(i => if (i % 2 == 0) 'C' else '.').mkString("")
  val wb = (0 until n).map(i => if (i % 2 == 1) 'C' else '.').mkString("")

  for (i <- 0 until n)
    if (i % 2 == 0) println(cb)
    else println(wb)
}

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

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

  0 until N foreach { i =>
    0 until N foreach { j =>
      if (i % 2 == j % 2) out.print('C')
      else out.print('.')
    }
    out.println
  }

  out.close
}


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

import scala.StringBuilder
import scala.collection.mutable

object D {

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

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  case class Rectangle(width: Int, height: Int) {

    def normalize(): Rectangle = {
      new Rectangle(Math.min(width, height), Math.max(width, height))
    }

    def maximize(): Rectangle = {
      new Rectangle(Math.max(width, height), Math.min(width, height))
    }

    def rotate(): Rectangle = {
      new Rectangle(height, width)
    }

  }

  def getSecond(i: Int): Int = {
    i match {
      case 0 => 1
      case 1 => 2
      case 2 => 0
    }
  }

  def getThird(i: Int): Int = {
    i match {
      case 0 => 2
      case 1 => 0
      case 2 => 1
    }
  }

  def rectLetter(i: Int): String = {
    i match {
      case 0 => "A"
      case 1 => "B"
      case 2 => "C"
    }
  }

  def appendZeroes(s: String): String = {
    val sb = new StringBuilder()
    while (sb.length < 3 - s.length) {
      sb.append("0")
    }
    sb.append(s).toString()
  }

  def rotate(rectangle: Rectangle, s: String, i: Int) = if (s.charAt(i) == '1') rectangle else rectangle.rotate()

  def checkRects(i: Int, rects: Array[Rectangle]): Boolean = {
    for (i <- 0 until 3) {
      for (k <- 0 to 8) {
        val s = appendZeroes(Integer.toBinaryString(k))
        val fst = rotate(rects(i), s, 0)
        val snd = rotate(rects(getSecond(i)), s, 1)
        val thrd = rotate(rects(getThird(i)), s, 2)
        if (fst.height == snd.width + thrd.width && fst.height == fst.width + snd.height && snd.height == thrd.height) {
          // output the result
          out.println(fst.height)
          for (j <- 0 until fst.height) {
            for (k <- 0 until fst.height) {
              if (j < snd.height) {
                if (k < snd.width) {
                  out.print(rectLetter(getSecond(i)))
                } else {
                  out.print(rectLetter(getThird(i)))
                }
              } else {
                out.print(rectLetter(i))
              }
            }
            out.println()
          }
          return true
        }
      }
    }
    false
  }

  def solve: Int = {
    val x1 = nextInt
    val y1 = nextInt
    val a = new Rectangle(x1, y1).normalize
    val a1 = new Rectangle(x1, y1).maximize
    val x2 = nextInt
    val y2 = nextInt
    val b = new Rectangle(x2, y2).normalize
    val b1 = new Rectangle(x2, y2).maximize
    val x3 = nextInt
    val y3 = nextInt
    val c = new Rectangle(x3, y3).normalize
    val c1 = new Rectangle(x3, y3).maximize
    if (a.height == b.height && b.height == c.height && a.width + b.width + c.width == a.height) {
      // output the result
      out.println(a.height)
      for (i <- 0 until a.height) {
        for (j <- 0 until a.height) {
          if (j < a.width) {
            out.print("A")
          } else if (j < a.width + b.width) {
            out.print("B")
          } else {
            out.print("C")
          }
        }
        out.println()
      }
      return 0
    }
    val rects = new Array[Rectangle](3)
    rects(0) = a
    rects(1) = b
    rects(2) = c
    val reversedRects = new Array[Rectangle](3)
    reversedRects(0) = a1
    reversedRects(1) = b1
    reversedRects(2) = c1
    for (i <- 0 until 3) {
      if (checkRects(i, rects)) {
        return 0
      }
    }
    for (i <- 0 until 3) {
      if (checkRects(i, reversedRects)) {
        return 0
      }
    }
    out.println(-1)
    return 0
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next().split(" ").map(_.toInt).grouped(2).flatMap(_.sorted.reverse)
  val t = data.grouped(2).map(_.toList).toList.zip(List("A", "B", "C")).map{
    case(List(a, b), c) => (a, b, c)
  }
  var Seq((y1, x1, ch1), (y2, x2, ch2), (y3, x3, ch3)) = t.sorted.reverse.toSeq

  val a = y1
  val first = (1 to x1).map(_ => ch1 * a).toList

    //разместим a
  val second =
    if (x1 * y1 + x2 * y2 + x3 * y3 != a * a) None
    else if (y2 == a && y3 != a) None
    else if (y2 == a)
      Some(
        (1 to x2).map(_ => ch2 * a).toList :::
        (1 to x3).map(_ => ch3 * a).toList)
    else {
      val b = a - x1
      if (x2 == y3 && x2 == b && x3 + y2 == a)
        Some((1 to b).map(_ => ch2 * y2 + ch3 * x3).toList)
      else if (x3 == y2 && y2 == b && x2 + y3 == a)
        Some((1 to b).map(_ => ch2 * x2 + ch3 * y3).toList)
      else if (y2 + y3 == a && x2 == x3 && x2== b)
        Some((1 to b).map(_ => ch2 * y2 + ch3 * y3).toList)
      else if (x2 + x3 == a && y2 == y3 && y2 == b)
        Some((1 to b).map(_ => ch2 * x2 + ch3 * x3).toList)
      else
        None
    }
  if (second.isEmpty)
    println(-1)
  else {
    println(a)
    println(second.map(t => first ::: t).get.mkString("\n"))
  }

}

object _581D extends App {
  val scanner = new java.util.Scanner(System.in)
  val logos = Seq("A", "B", "C") map {c => c -> Seq(scanner.nextInt, scanner.nextInt)}
  var rows: Seq[String] = Nil
  for {
    Seq((c1, p), (c2, q), (c3, r)) <- logos.permutations if rows.isEmpty
    Seq(x1, y1) <- p.permutations
    Seq(x2, y2) <- q.permutations
    Seq(x3, y3) <- r.permutations
  } {
    if ((y1 == y2) && (y2 == y3) && ((x1 + x2 + x3) == y3)) {
      rows = Seq.fill(x1)(c1 * y1) ++ Seq.fill(x2)(c2 * y2) ++ Seq.fill(x3)(c3 * y3)
    } else if ((x2 == x3) && (y1 == y2 + y3) && (x1 + x2) == y1) {
      rows = Seq.fill(x1)(c1 * y1) ++ Seq.fill(x2)((c2 * y2) + (c3 * y3))
    }
  }
  println(if (rows.isEmpty) -1 else rows.length)
  rows foreach println
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _581D extends CodeForcesApp[Option[List[String]]]({scanner => import scanner._
  def rotate(p: (Int, Int)) = List(p, p.swap)

  val (ax, ay, bx, by, cx, cy) = (nextInt, nextInt, nextInt, nextInt, nextInt, nextInt)

  val stacks = for {
    (x1, y1) <- rotate(ax, ay)
    (x2, y2) <- rotate(bx, by) if y2 == y1
    (x3, y3) <- rotate(cx, cy) if y3 == y2
    if (x1 + x2 + x3) == y3
  } yield ((x1, y1), (x2, y2), (x3, y3))

  def block(d: (Int, Int), char: String) = {
    val (x, y) = d
    List.fill(x)(char * y)
  }

  val logos = List("A" -> (ax, ay), "B" -> (bx, by), "C" -> (cx, cy))
  lazy val sided = for {
    Seq((c1, p), (c2, q), (c3, r)) <- logos.permutations
    (x1, y1) <- rotate(p)
    (x2, y2) <- rotate(q)
    (x3, y3) <- rotate(r)
    if (x2 == x3) && (y1 == y2 + y3) && (x1 + x2) == y1
  } yield (c1 -> (x1, y1), c2 -> (x2, y2), c3 -> (x3, y3))

  stacks match {
    case (a, b, c) :: _ => Some(block(a, "A") ::: block(b, "B") ::: block(c, "C"))

    case _ => sided.toSeq.headOption map {case ((c1, p), (c2, (x2, y2)), (c3, (x3, y3))) =>
       block(p, c1) ::: List.fill(x2)((c2 * y2) + (c3 * y3))
    }
  }
}) {
  override def format(result: Result) = result match {
    case None => "-1"
    case Some(block) => s"""
    |${block.size}
    |${block.mkString("\n")}
    """.stripMargin
  }
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val x1 = sc.nextInt
  val y1 = sc.nextInt
  val x2 = sc.nextInt
  val y2 = sc.nextInt
  val x3 = sc.nextInt
  val y3 = sc.nextInt

  var a = false

  def print1(x: Int,
             y: Int,
             z: Int,
             pos: Seq[Char]
            ) {
    println(x)
    (1 to y).foreach(_ => {(1 to x).foreach(_ => print(pos(0))); println})
    (1 to z).foreach(_ => {(1 to x).foreach(_ => print(pos(1))); println})
    (1 to (x - y - z)).foreach(_ => {(1 to x).foreach(_ => print(pos(2))); println})
  }

  def print2(x: Int,
             y: Int,
             z: Int,
             pos: Seq[Char]
            ) {
    println(x)
    (1 to y).foreach(_ => {(1 to x).foreach(_ => print(pos(0))); println})
    (1 to (x - y)).foreach(_ => {
      (1 to z).foreach(_ => print(pos(1)))
      (1 to (x - z)).foreach(_ => print(pos(2)))
      println
    })
  }

  def check1(p1: (Int, Int),
             p2: (Int, Int),
             p3: (Int, Int),
             pos: Seq[Char]
            ) {
    def c1 =
      (p1._1 == p2._1 && p1._1 == p3._1) &&
        (p1._2 + p2._2 + p3._2  == p1._1) &&
        ({print1(p1._1, p1._2, p2._2, pos); true})
    def c2 =
      (p2._2 == p3._2) && (p2._2 + p1._2 == p1._1) &&
        (p2._1 + p3._1 == p1._1) &&
        ({print2(p1._1, p1._2, p2._1, pos); true})

    a = a || c1 || c2
  }

  def check(p1: (Int, Int),
            p2: (Int, Int),
            p3: (Int, Int)
           ) = {
    check1(p1, p2, p3, Seq('A', 'B', 'C'))
    check1(p1, p3, p2, Seq('A', 'C', 'B'))
    check1(p2, p1, p3, Seq('B', 'A', 'C'))
    check1(p2, p3, p1, Seq('B', 'C', 'A'))
    check1(p3, p1, p2, Seq('C', 'A', 'B'))
    check1(p3, p2, p1, Seq('C', 'B', 'A'))
  }

  def c = {
    val p1 = (x1, y1)
    val p2 = (x2, y2)
    val p3 = (x3, y3)
    val s1 = Seq(p1, p1.swap)
    val s2 = Seq(p2, p2.swap)
    val s3 = Seq(p3, p3.swap)

    s1.foreach(a => {
      s2.foreach(b => {
        s3.foreach(c => {
          check(a, b, c)
        })
      })
    })
  }

  c
  if (!a)
    println(-1)
}

import java.io._
import scala.collection.mutable.Map

//581D
object D_ThreeLogos {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
//    val line1 = "5 1 2 5 5 2".split(" ")
//    val line1 = "4 4 2 6 4 2".split(" ")

    val coo = Array[Array[Int]]( Array(Integer.parseInt(line1(0)),Integer.parseInt(line1(1))),
        Array(Integer.parseInt(line1(2)),Integer.parseInt(line1(3))),
        Array(Integer.parseInt(line1(4)),Integer.parseInt(line1(5)))
        )

    val x1 = Integer.parseInt(line1(0))
    val y1 = Integer.parseInt(line1(1))
    val x2 = Integer.parseInt(line1(0))
    val y2 = Integer.parseInt(line1(1))
    val x3 = Integer.parseInt(line1(0))
    val y4 = Integer.parseInt(line1(1))

    val layouts = Array("123", "132", "213", "231", "312", "321")

    for (i <- layouts) {
      rows(i)
    }
    println(-1)
    System.exit(0)

    def rows(lay:String) {
      flips(lay)
      flips(lay.replace("1", "1."))
      flips(lay.replace("2", "2."))
      flips(lay.replace("1", "1.").replace("2", "2."))
    }

    def flips(row:String) {
      check(row)
      check(row.replace("", ""))
      check(row.replace("1", "1a"))
      check(row.replace("2", "2a"))
      check(row.replace("3", "3a"))
      check(row.replace("1", "1a").replace("2", "2a"))
      check(row.replace("2", "2a").replace("3", "3a"))
      check(row.replace("1", "1a").replace("3", "3a"))
      check(row.replace("1", "1a").replace("2", "2a").replace("3", "3a"))
    }

    def check(comb:String) {
//      println("variant: " + comb)
      if (comb == "1a23") {
//        println("here")
      }
      val grid = comb.split('.')
      val line0 = grid(0)
      var line0Li = parseLine(line0).reverse.toArray
      var width = 0
      for (i <- line0Li) {
        val ind = Integer.parseInt(i(0).toString()) - 1
        if (i.length() == 1) {
          width += coo(ind)(0)
        } else {
          width += coo(ind)(1)
        }
      }

      var pixCounter = 0
      val result = Array.ofDim[Char](width, width)
      var y = 0
      for (line <- grid) {
        val figNames = parseLine(line).reverse.toArray
        var x = 0
        for (i <- figNames) {
          val fig = getFig(i)
          if (x + fig._1 > width) return
          if (y + fig._2 > width) return

          //render
          for (fy <- 0 until fig._2) {
            for (fx <- 0 until fig._1) {
//              println("---- " + result(fx)(fy).toInt)
              val pixX = x + fx
              val pixY = y + fy
              if (result(pixY)(pixX).toInt != 0) {
                return
              }
              val dispChar = getFigChar(i)
              result(pixY)(pixX) = dispChar
              pixCounter += 1
            }
          }
          x += fig._1

        }
        y += getFig(figNames(0))._2
      }

      //DELME
//      printResult

      //success
      if (pixCounter == width * width) {
        println(width)
        printResult
        System.exit(0)
      }

      def printResult() {
        for (x <- 0 until result.length) {
          for (y <- 0 until result.length) {
            print(result(y)(x))
          }
          println
        }
      }
    }

    def getFigChar(name:String): Char = {
      if (name.startsWith("1")) 'A'
      else  if (name.startsWith("2")) 'B'
      else    if (name.startsWith("3")) 'C'
          else 'X'
    }

    def getFig(name:String): (Int, Int) = {
      val ind = Integer.parseInt(name(0).toString) - 1
        if (name.length() == 1) {
          (coo(ind)(0), coo(ind)(1))
        } else {
          (coo(ind)(1), coo(ind)(0))
        }
    }

    def parseLine(line:String):List[String] = {
      var res = List[String]()
      var cur = line(0).toString()
      for (i <- 1 until line.length()) {
        if (line(i) == 'a') {
          res = (cur + 'a') :: res
          cur = null
        } else {
          if (cur != null) {
            res = cur :: res
          }
          cur = line(i).toString
        }
      }
      if (cur != null) {
        res = cur :: res
      }
      res
    }
  }
}

import java.util.Scanner

import scala.language.postfixOps
import scala.math.sqrt

object TaskD extends App {
  type Board = Array[Array[Char]]
  val sc = new Scanner(System.in)
  val logos = 'A' to 'C' map {
    Logo(sc.nextInt, sc.nextInt, _)
  }

  val sq = logos.map(l => l.x * l.y).sum
  val sqr = sqrt(sq) toInt

  if (sqr * sqr != sq) {
    println(-1)
  } else {
    val a = sqr
    val board = Array.fill(a)(new Array[Char](a))
    if (logos.flatMap(l => List(l.x, l.y)).count(_ > a) > 0) {
      println(-1)
    } else {
      val res = findBestMatch(board, 0, 0, logos)
      if (res) {
        println(a)
        println(board.map(_.mkString).mkString("\n"))
      } else {
        println(-1)
      }
    }
  }

  def findBestMatch(board: Board, iOff: Int, jOff: Int, logos: Seq[Logo]): Boolean = {
    if (logos.nonEmpty) {
      val (w, h) = (board(0).length - jOff, board.length - iOff)
      (logos ++ logos.map(_.rotate)).find(l => l.x == w || l.y == h).exists { best =>
        val (io, jo) = fillBoard(board, iOff, jOff, best)
        findBestMatch(board, io, jo, logos diff Seq(best, best.rotate))
      }
    } else {
      true
    }
  }

  def fillBoard(board: Board, iOff: Int, jOff: Int, logo: Logo) = {
    val (iEnd, jEnd) = (iOff + logo.y, jOff + logo.x)
    iOff until iEnd foreach (i => jOff until jEnd foreach (j => board(i)(j) = logo.char))
    if (iEnd == board.length) (iOff, jEnd) else (iEnd, jOff)
  }

  case class Logo(x: Int, y: Int, char: Char) {
    def rotate = Logo(y, x, char)
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next().split(" ").map(_.toInt).grouped(2).flatMap(_.sorted.reverse)
  val t = data.grouped(2).map(_.toList).toList.zip(List("A", "B", "C")).map{
    case(List(a, b), c) => (a, b, c)
  }
  var Seq((y1, x1, ch1), (y2, x2, ch2), (y3, x3, ch3)) = t.sorted.reverse.toSeq

  val a = y1
  if (x1 * y1 + x2 * y2 + x3 * y3 != a * a) {
    println(-1)
  }
  else {
    //разместим a
    if (y2 == a)  {
      if (y3 == a) {
        //разместим a b и с горизонтально
        println(((1 to x1).map(_ => ch1 * a).toList :::
        (1 to x2).map(_ => ch2 * a).toList :::
        (1 to x3).map(_ => ch3 * a).toList).mkString("\n"))
      }
      else
        println(-1)
    } else {
      val b = a - x1
      if (x2 == y3 && x2 == b && x3 + y2 == a) {
        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * y2 + ch3 * x3).toList).mkString("\n"))
      }
      else if (x3 == y2 && y2 == b && x2 + y3 == a){

        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * x2 + ch3 * y3 ).toList).mkString("\n"))
      }
      else if (y2 + y3 == a && x2 == x3 && x2== b){
        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * y2 + ch3 * y3 ).toList).mkString("\n"))
      }
      else if (x2 + x3 == a && y2 == y3 && y2 == b){
        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * x2 + ch3 * x3 ).toList).mkString("\n"))
      }
      else {
        println(-1)
      }
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val data = in.next().split(" ").map(_.toInt).grouped(2).flatMap(_.sorted.reverse)
  val t = data.grouped(2).map(_.toList).toList.zip(List("A", "B", "C")).map{
    case(List(a, b), c) => (a, b, c)
  }
  var Seq((y1, x1, ch1), (y2, x2, ch2), (y3, x3, ch3)) = t.sorted.reverse.toSeq

  val a = y1
  println(a)
  if (x1 * y1 + x2 * y2 + x3 * y3 != a * a) {
    println(-1)
  }
  else {
    //разместим a
    if (y2 == a)  {
      if (y3 == a) {
        //разместим a b и с горизонтально
        println(((1 to x1).map(_ => ch1 * a).toList :::
        (1 to x2).map(_ => ch2 * a).toList :::
        (1 to x3).map(_ => ch3 * a).toList).mkString("\n"))
      }
      else
        println(-1)
    } else {
      val b = a - x1
      if (x2 == y3 && x2 == b && x3 + y2 == a) {
        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * y2 + ch3 * x3).toList).mkString("\n"))
      }
      else if (x3 == y2 && y2 == b && x2 + y3 == a){

        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * x2 + ch3 * y3 ).toList).mkString("\n"))
      }
      else if (y2 + y3 == a && x2 == x3 && x2== b){
        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * y2 + ch3 * y3 ).toList).mkString("\n"))
      }
      else if (x2 + x3 == a && y2 == y3 && y2 == b){
        println(((1 to x1).map(_ => ch1 * a).toList :::
          (1 to b).map(_ => ch2 * x2 + ch3 * x3 ).toList).mkString("\n"))
      }
      else {
        println(-1)
      }
    }
  }
}

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

import scala.collection.mutable

object D {

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

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  case class Rectangle(width: Int, height: Int) {

    def normalize(): Rectangle = {
      new Rectangle(Math.min(width, height), Math.max(width, height))
    }
  }

  def getSecond(i: Int): Int = {
    i match {
      case 0 => 1
      case 1 => 2
      case 2 => 0
    }
  }

  def getThird(i: Int): Int = {
    i match {
      case 0 => 2
      case 1 => 0
      case 2 => 1
    }
  }

  def rectLetter(i: Int): String = {
    i match {
      case 0 => "A"
      case 1 => "B"
      case 2 => "C"
    }
  }

  def solve: Int = {
    val x1 = nextInt
    val y1 = nextInt
    val a = new Rectangle(x1, y1).normalize
    val x2 = nextInt
    val y2 = nextInt
    val b = new Rectangle(x2, y2).normalize
    val x3 = nextInt
    val y3 = nextInt
    val c = new Rectangle(x3, y3).normalize
    if (a.height == b.height && b.height == c.height && a.width + b.width + c.width == a.height) {
      // output the result
      for (i <- 0 until a.height) {
        for (j <- 0 until a.height) {
          if (j < a.width) {
            out.print("A")
          } else if (j < a.width + b.width) {
            out.print("B")
          } else {
            out.print("C")
          }
        }
        out.println()
      }
      return 0
    }
    val rects = new Array[Rectangle](3)
    rects(0) = a
    rects(1) = b
    rects(2) = c
    for (i <- 0 until 3) {
      val fst = rects(i)
      val snd = rects(getSecond(i))
      val thrd = rects(getThird(i))
      if (fst.height == snd.width + thrd.width && fst.height == fst.width + snd.height && snd.height == thrd.height) {
        for (j <- 0 until fst.height) {
          for (k <- 0 until fst.height) {
            if (j < snd.height) {
              if (k < snd.width) {
                out.print(rectLetter(getSecond(i)))
              } else {
                out.print(rectLetter(getThird(i)))
              }
            } else {
              out.print(rectLetter(i))
            }
          }
          out.println()
        }
        return 0
      }
    }
    out.println(-1)
    return 0
  }
}

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

import scala.collection.mutable

object D {

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

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  case class Rectangle(width: Int, height: Int) {

    def normalize(): Rectangle = {
      new Rectangle(Math.min(width, height), Math.max(width, height))
    }
  }

  def getSecond(i: Int): Int = {
    i match {
      case 0 => 1
      case 1 => 2
      case 2 => 0
    }
  }

  def getThird(i: Int): Int = {
    i match {
      case 0 => 2
      case 1 => 0
      case 2 => 1
    }
  }

  def rectLetter(i: Int): String = {
    i match {
      case 0 => "A"
      case 1 => "B"
      case 2 => "C"
    }
  }

  def solve: Int = {
    val x1 = nextInt
    val y1 = nextInt
    val a = new Rectangle(x1, y1).normalize
    val x2 = nextInt
    val y2 = nextInt
    val b = new Rectangle(x2, y2).normalize
    val x3 = nextInt
    val y3 = nextInt
    val c = new Rectangle(x3, y3).normalize
    if (a.height == b.height && b.height == c.height && a.width + b.width + c.width == a.height) {
      // output the result
      out.println(a.height)
      for (i <- 0 until a.height) {
        for (j <- 0 until a.height) {
          if (j < a.width) {
            out.print("A")
          } else if (j < a.width + b.width) {
            out.print("B")
          } else {
            out.print("C")
          }
        }
        out.println()
      }
      return 0
    }
    val rects = new Array[Rectangle](3)
    rects(0) = a
    rects(1) = b
    rects(2) = c
    for (i <- 0 until 3) {
      val fst = rects(i)
      val snd = rects(getSecond(i))
      val thrd = rects(getThird(i))
      if (fst.height == snd.width + thrd.width && fst.height == fst.width + snd.height && snd.height == thrd.height) {
        // output the result
        out.println(fst.height)
        for (j <- 0 until fst.height) {
          for (k <- 0 until fst.height) {
            if (j < snd.height) {
              if (k < snd.width) {
                out.print(rectLetter(getSecond(i)))
              } else {
                out.print(rectLetter(getThird(i)))
              }
            } else {
              out.print(rectLetter(i))
            }
          }
          out.println()
        }
        return 0
      }
    }
    out.println(-1)
    return 0
  }
}

import java.io._
import scala.collection.mutable.Map

//581D
object D_ThreeLogos {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
//    val line1 = "5 1 2 5 5 2".split(" ")
//    val line1 = "4 4 2 6 4 2".split(" ")

    val coo = Array[Array[Int]]( Array(Integer.parseInt(line1(0)),Integer.parseInt(line1(1))),
        Array(Integer.parseInt(line1(2)),Integer.parseInt(line1(3))),
        Array(Integer.parseInt(line1(4)),Integer.parseInt(line1(5)))
        )

    val x1 = Integer.parseInt(line1(0))
    val y1 = Integer.parseInt(line1(1))
    val x2 = Integer.parseInt(line1(0))
    val y2 = Integer.parseInt(line1(1))
    val x3 = Integer.parseInt(line1(0))
    val y4 = Integer.parseInt(line1(1))

    val layouts = Array("123", "132", "213", "231", "312", "321")

    for (i <- layouts) {
      rows(i)
      println(-1)
    }

    def rows(lay:String) {
      flips(lay)
      flips(lay.replace("1", "1."))
      flips(lay.replace("2", "2."))
      flips(lay.replace("1", "1.").replace("2", "2."))
    }

    def flips(row:String) {
      check(row)
      check(row.replace("", ""))
      check(row.replace("1", "1a"))
      check(row.replace("2", "2a"))
      check(row.replace("3", "3a"))
      check(row.replace("1", "1a").replace("2", "2a"))
      check(row.replace("2", "2a").replace("3", "3a"))
      check(row.replace("1", "1a").replace("3", "3a"))
      check(row.replace("1", "1a").replace("2", "2a").replace("3", "3a"))
    }

    def check(comb:String) {
//      println("variant: " + comb)
      if (comb == "1a23") {
//        println("here")
      }
      val grid = comb.split('.')
      val line0 = grid(0)
      var line0Li = parseLine(line0).reverse.toArray
      var width = 0
      for (i <- line0Li) {
        val ind = Integer.parseInt(i(0).toString()) - 1
        if (i.length() == 1) {
          width += coo(ind)(0)
        } else {
          width += coo(ind)(1)
        }
      }

      var pixCounter = 0
      val result = Array.ofDim[Char](width, width)
      var y = 0
      for (line <- grid) {
        val figNames = parseLine(line).reverse.toArray
        var x = 0
        for (i <- figNames) {
          val fig = getFig(i)
          if (x + fig._1 > width) return
          if (y + fig._2 > width) return

          //render
          for (fy <- 0 until fig._2) {
            for (fx <- 0 until fig._1) {
//              println("---- " + result(fx)(fy).toInt)
              val pixX = x + fx
              val pixY = y + fy
              if (result(pixY)(pixX).toInt != 0) {
                return
              }
              val dispChar = getFigChar(i)
              result(pixY)(pixX) = dispChar
              pixCounter += 1
            }
          }
          x += fig._1

        }
        y += getFig(figNames(0))._2
      }

      //DELME
//      printResult

      //success
      if (pixCounter == width * width) {
        println(width)
        printResult
        System.exit(0)
      }

      def printResult() {
        for (x <- 0 until result.length) {
          for (y <- 0 until result.length) {
            print(result(y)(x))
          }
          println
        }
      }
    }

    def getFigChar(name:String): Char = {
      if (name.startsWith("1")) 'A'
      else  if (name.startsWith("2")) 'B'
      else    if (name.startsWith("3")) 'C'
          else 'X'
    }

    def getFig(name:String): (Int, Int) = {
      val ind = Integer.parseInt(name(0).toString) - 1
        if (name.length() == 1) {
          (coo(ind)(0), coo(ind)(1))
        } else {
          (coo(ind)(1), coo(ind)(0))
        }
    }

    def parseLine(line:String):List[String] = {
      var res = List[String]()
      var cur = line(0).toString()
      for (i <- 1 until line.length()) {
        if (line(i) == 'a') {
          res = (cur + 'a') :: res
          cur = null
        } else {
          if (cur != null) {
            res = cur :: res
          }
          cur = line(i).toString
        }
      }
      if (cur != null) {
        res = cur :: res
      }
      res
    }
  }
}


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 n = in.nextInt()

    n.times {
      val x = in.nextInt()
      val y = in.nextInt()
      val k = in.nextInt()

      val r = (k - y) / x
      println((r * x) + y)
    }
  }

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

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/A
 */
object RequiredRemainder {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt()) {
      val Array(x, y, n) = io.StdIn.readLine.split(" ").map(_.toInt)

      val maxN = {
        val r = n % x
        val mN = n - r + y
        if (mN > n) mN - x else mN
      }

      println(maxN)
    }
  }
}

import scala.io.StdIn._

object CF653_A extends App {
  val t = readInt()
  for (_ <- 0 until t) {
    val xyn = readLine()
    val tmp = xyn.split(' ').map(_.toInt)
    var (x, y, n) = (tmp(0), tmp(1), tmp(2))

//    println(x, y, n)
//    println(List(1, 2, 3))
//    val (x, y, n) = new Tuple3(: _*)

    println(n - (n - y) % x)
//    println((n - y) / x)
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new CF653A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

    def nextInt(): Int = Integer.parseInt(next())

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class CF653A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val x = ni()
      val y = ni()
      val n = ni()

      val r = n / x
      if(r * x + y <= n) out.println(r * x + y)
      else out.println((r-1)*x + y)
    }
  }
}

import scala.io.StdIn.readLine
object Main {
  def main(args: Array[String]) {
    val T = readLine.split(" ")(0).toInt
    for(cas <- 0 until T) {
      val Line = readLine.split(" ").map(
        item => item.toInt
      )
      val x = Line(0)
      val y = Line(1)
      val n = Line(2)
      var r = n / x * x + y
      if(r > n) {
        r -= x
      }
      println(r)
    }
  }
}