This is an interactive task.Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.There are $$$666$$$ black rooks and $$$1$$$ white king on the chess board of size $$$999 \times 999$$$. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square $$$(x, y)$$$, it can move to the square $$$(nx, ny)$$$ if and only $$$\max (|nx - x|, |ny - y|) = 1$$$ , $$$1 \leq nx, ny \leq 999$$$. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.Each player makes $$$2000$$$ turns, if the white king wasn't checked by a black rook during those turns, black wins. NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.

In the beginning your program will receive $$$667$$$ lines from input. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x, y \leq 999$$$) — the piece's coordinates. The first line contains the coordinates of the king and the next $$$666$$$ contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.

After getting king checked, you program should terminate immediately without printing anything extra.

NoteThe example is trimmed. The full initial positions of the rooks in the first test are available at https://pastebin.com/qQCTXgKP. It is not guaranteed that they will behave as in the example.

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 MID = 500
    var curX, curY = ni()
    var lb, rb, lt, rt = 0
    val Rx, Ry = Array.ofDim[Int](666) // ルークのIDは0-index。場所は1-index
    REP(666) { i =>
      val x, y = ni()
      Rx(i) = x
      Ry(i) = y
      inc(i)
    }

    def inc(k: Int): Unit = {
      if (Rx(k) > MID && Ry(k) > MID) rt += 1
      if (Rx(k) > MID && Ry(k) < MID) rb += 1
      if (Rx(k) < MID && Ry(k) > MID) lt += 1
      if (Rx(k) < MID && Ry(k) < MID) lb += 1
    }

    def dec(k: Int): Unit = {
      if (Rx(k) > MID && Ry(k) > MID) rt -= 1
      if (Rx(k) > MID && Ry(k) < MID) rb -= 1
      if (Rx(k) < MID && Ry(k) > MID) lt -= 1
      if (Rx(k) < MID && Ry(k) < MID) lb -= 1
    }

    sealed trait Result
    case object Continue extends Result
    case object Error extends Result
    case object Success extends Result

    def readAnswer(): Result = {
      val k, x, y = ni()
      if (k == 0 && x == 0 && y == 0) {
        return Error
      } else if (k == -1 && x == -1 && y == -1) {
        return Success
      }

      val i = k - 1
      dec(i)
      Rx(i) = x
      Ry(i) = y
      inc(i)

      Continue
    }

    def exists(x: Int, y: Int) = {
      0 until 666 exists { i =>
        Rx(i) == x && Ry(i) == y
      }
    }

    def moveTo(x: Int, y: Int): Result = {
      while(x != curX || y != curY) {
        val nextX = curX + Integer.signum(x - curX)
        val nextY = curY + Integer.signum(y - curY)
        val eat = exists(nextX, nextY)
        curX += Integer.signum(x - curX)
        if (!eat) curY += Integer.signum(y - curY) // 食べちゃうのは斜め移動だけなので、x, yどちらかの移動をやめればチェックするはず
        out.println(s"$curX $curY")
        out.flush()

        readAnswer() match {
          case Error => return Error
          case Success => return Success
          case Continue =>
        }
      }

      Continue
    }

    moveTo(MID, MID) match {
      case Success =>
      case Error =>
      case Continue =>
        val ms = min(min(lt, lb), min(rt, rb))

        val (distX, distY) =
          if (ms == lb) (999, 999)
          else if (ms == rb) (1, 999)
          else if (ms == lt) (999, 1)
          else (1, 1)

        moveTo(distX, distY) match {
          case Continue =>
            // 失敗
            throw new IllegalStateException(s"$distX $distY")

          case _ =>
        }
    }
  }

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

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

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

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

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

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

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

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

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

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

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 MID = 500
    var curX, curY = ni()
    var r, up = 0
    val Rx, Ry = Array.ofDim[Int](666) // ルークのIDは0-index。場所は1-index
    REP(666) { i =>
      val x, y = ni()
      Rx(i) = x
      Ry(i) = y
      inc(i)
    }

    def inc(k: Int): Unit = {
      if (Rx(k) > MID) r += 1
      if (Ry(k) > MID) up += 1
    }

    def dec(k: Int): Unit = {
      if (Rx(k) > MID) r -= 1
      if (Ry(k) > MID) up -= 1
    }

    sealed trait Result
    case object Continue extends Result
    case object Error extends Result
    case object Success extends Result

    def readAnswer(): Result = {
      val k, x, y = ni()
      if (k == 0 && x == 0 && y == 0) {
        return Error
      } else if (k == -1 && x == -1 && y == -1) {
        return Success
      }

      val i = k - 1
      dec(i)
      Rx(i) = x
      Ry(i) = y
      inc(i)

      Continue
    }

    def exists(x: Int, y: Int) = {
      0 until 666 exists { i =>
        Rx(i) == x && Ry(i) == y
      }
    }

    def moveTo(x: Int, y: Int): Result = {
      while(x != curX || y != curY) {
        val nextX = curX + Integer.signum(x - curX)
        val nextY = curY + Integer.signum(y - curY)
        val eat = exists(nextX, nextY)
        curX += Integer.signum(x - curX)
        if (!eat) curY += Integer.signum(y - curY) // 食べちゃうのは斜め移動だけなので、x, yどちらかの移動をやめればチェックするはず
        out.println(s"$curX $curY")
        out.flush()

        readAnswer() match {
          case Error => return Error
          case Success => return Success
          case Continue =>
        }
      }

      Continue
    }

    moveTo(MID, MID) match {
      case Success =>
      case Error =>
      case Continue =>
        val distX = if (r < 333) 1 else 999
        val distY = if (up < 333) 1 else 999
        moveTo(distX, distY) match {
          case Continue =>
            throw new IllegalStateException("Fail to achieve")

          case _ =>
        }
    }
  }

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

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

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

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

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

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

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

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

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

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

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 = {
    var curX, curY = ni()
    var l, r, up, down = 0
    val Rx, Ry = Array.ofDim[Int](666) // ルークのIDは0-index。場所は1-index
    REP(666) { i =>
      val x, y = ni()
      Rx(i) = x
      Ry(i) = y
      if (x > 455) r += 1
      if (x < 455) l += 1
      if (y > 455) up += 1
      if (y < 455) down += 1
    }

    def inc(k: Int): Unit = {
      if (Rx(k) > 455) r += 1
      if (Rx(k) < 455) l += 1
      if (Ry(k) > 455) up += 1
      if (Ry(k) < 455) down += 1
    }

    def dec(k: Int): Unit = {
      if (Rx(k) > 455) r -= 1
      if (Rx(k) < 455) l -= 1
      if (Ry(k) > 455) up -= 1
      if (Ry(k) < 455) down -= 1
    }

    def readAnswer(): Unit = {
      val k, x, y = ni()
      if (k == 0 && x == 0 && y == 0) {
        throw new IllegalArgumentException("Wrong Answer")
      } else if (k == -1 && x == -1 && y == -1) {
        return
      }

      val i = k - 1
      dec(i)
      Rx(i) = x
      Ry(i) = y
      inc(i)
    }

    def moveTo(x: Int, y: Int): Unit = {
      while(x != curX || y != curY) {
        curX += Integer.signum(x - curX)
        curY += Integer.signum(y - curY)
        out.println(s"$curX $curY")
        out.flush()

        readAnswer()
      }
    }

    moveTo(455, 455)
    val distX = if (l > r) 0 else 999
    val distY = if (down > up) 0 else 999
    moveTo(distX, distY)
  }

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

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

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

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

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

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

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

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

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

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

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 MID = 500
    var curX, curY = ni()
    var r, up = 0
    val Rx, Ry = Array.ofDim[Int](666) // ルークのIDは0-index。場所は1-index
    REP(666) { i =>
      val x, y = ni()
      Rx(i) = x
      Ry(i) = y
      inc(i)
    }

    def inc(k: Int): Unit = {
      if (Rx(k) > MID) r += 1
      if (Ry(k) > MID) up += 1
    }

    def dec(k: Int): Unit = {
      if (Rx(k) > MID) r -= 1
      if (Ry(k) > MID) up -= 1
    }

    sealed trait Result
    case object Continue extends Result
    case object Error extends Result
    case object Success extends Result

    def readAnswer(): Result = {
      val k, x, y = ni()
      if (k == 0 && x == 0 && y == 0) {
        return Error
      } else if (k == -1 && x == -1 && y == -1) {
        return Success
      }

      val i = k - 1
      dec(i)
      Rx(i) = x
      Ry(i) = y
      inc(i)

      Continue
    }

    def exists(x: Int, y: Int) = {
      0 until 666 exists { i =>
        Rx(i) == x && Ry(i) == y
      }
    }

    def moveTo(x: Int, y: Int): Result = {
      while(x != curX || y != curY) {
        val nextX = curX + Integer.signum(x - curX)
        val nextY = curY + Integer.signum(y - curY)
        val eat = exists(nextX, nextY)
        curX += Integer.signum(x - curX)
        if (!eat) curY += Integer.signum(y - curY) // 食べちゃうのは斜め移動だけなので、x, yどちらかの移動をやめればチェックするはず
        out.println(s"$curX $curY")
        out.flush()

        readAnswer() match {
          case Error => return Error
          case Success => return Success
          case Continue =>
        }
      }

      Continue
    }

    moveTo(MID, MID) match {
      case Success =>
      case Error =>
      case Continue =>
        val distX = if (r < 333) 1 else 999
        val distY = if (up < 333) 1 else 999
        moveTo(distX, distY) match {
          case Continue =>
            // 失敗
            out.println(s"$r $up, $distX $distY")
            out.flush()

          case _ =>
        }
    }
  }

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

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

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

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

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

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

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

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

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

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

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 MID = 500
    var curX, curY = ni()
    var r, up = 0
    val Rx, Ry = Array.ofDim[Int](666) // ルークのIDは0-index。場所は1-index
    REP(666) { i =>
      val x, y = ni()
      Rx(i) = x
      Ry(i) = y
      inc(i)
    }

    def inc(k: Int): Unit = {
      if (Rx(k) > MID) r += 1
      if (Ry(k) > MID) up += 1
    }

    def dec(k: Int): Unit = {
      if (Rx(k) > MID) r -= 1
      if (Ry(k) > MID) up -= 1
    }

    sealed trait Result
    case object Continue extends Result
    case object Error extends Result
    case object Success extends Result

    def readAnswer(): Result = {
      val k, x, y = ni()
      if (k == 0 && x == 0 && y == 0) {
        return Error
      } else if (k == -1 && x == -1 && y == -1) {
        return Success
      }

      val i = k - 1
      dec(i)
      Rx(i) = x
      Ry(i) = y
      inc(i)

      Continue
    }

    def exists(x: Int, y: Int) = {
      0 until 666 exists { i =>
        Rx(i) == x && Ry(i) == y
      }
    }

    def moveTo(x: Int, y: Int): Result = {
      while(x != curX || y != curY) {
        val nextX = curX + Integer.signum(x - curX)
        val nextY = curY + Integer.signum(y - curY)
        val eat = exists(nextX, nextY)
        curX += Integer.signum(x - curX)
        if (!eat) curY += Integer.signum(y - curY) // 食べちゃうのは斜め移動だけなので、x, yどちらかの移動をやめればチェックするはず
        out.println(s"$curX $curY")
        out.flush()

        readAnswer() match {
          case Error => return Error
          case Success => return Success
          case Continue =>
        }
      }

      Continue
    }

    moveTo(MID, MID) match {
      case Success =>
      case Error =>
      case Continue =>
        val distX = if (r < 333) 1 else 999
        val distY = if (up < 333) 1 else 999
        System.err.println(s"r: $r up: $up")
        System.err.println(s"move to $distX $distY")
        moveTo(distX, distY) match {
          case Continue =>
            System.err.println(s"Fail to achieve")
            throw new IllegalStateException("Fail to achieve")

          case _ =>
        }
    }
  }

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

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

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

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

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

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

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

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

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

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


Polycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row, where all $$$26$$$ lowercase Latin letters will be arranged in some order.Polycarp uses the same password $$$s$$$ on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in $$$s$$$, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in $$$s$$$, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of test cases. Then $$$T$$$ lines follow, each containing one string $$$s$$$ ($$$1 \le |s| \le 200$$$) representing the test case. $$$s$$$ consists of lowercase Latin letters only. There are no two adjacent equal characters in $$$s$$$.

For each test case, do the following:   if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem);  otherwise, print YES (in upper case), and then a string consisting of $$$26$$$ lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them.

5
ababa
codedoca
abcda
zxzytyz
abcdefghijklmnopqrstuvwxyza

YES
bacdefghijklmnopqrstuvwxyz
YES
edocabfghijklmnpqrstuvwxyz
NO
YES
xzytabcdefghijklmnopqrsuvw
NO

import scala.collection.Set

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val tb = stdin.next().toInt
  val rel = stdin.take(tb).map(solve)
  println(rel.flatten.mkString("\n"))

  def solve(str: String): List[String] = {
    var result: String = ""
    var visited = Set.empty[Char]
    var position = 0
    str.indices.foreach(i => {
      var ch = str.charAt(i)
      if (visited(ch)) {
       if (position > 0 && ch == result.charAt(position - 1))
         position -= 1
       else if (position + 1 < result.length && result.charAt(position + 1) == str.charAt(i))
         position += 1
       else
         return List("NO")
      }
      else {
        visited += ch
        if (position == 0) {
          result = ch + result
        }
        else if (position == result.length - 1) {
          result = result + ch
          position = result.length - 1
        }
        else return List("NO")
      }
    })
    result = result + ('a' to 'z').filter(ch => !visited.contains(ch)).mkString("")
    List("YES", result)
  }
}

import scala.collection.Set

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val tb = stdin.next().toInt
  val rel = stdin.take(tb).map(solve)
  println(rel.flatten.mkString("\n"))

  def solve(str: String): List[String] = {
    var m: Map[Char, Set[Char]] = str.toCharArray.sliding(2).foldLeft(Map.empty[Char, Set[Char]]) {
      case (s, Array(ch1, ch2)) =>
        val nSet1 = s.getOrElse(ch1, Set.empty[Char]) + ch2
        val nSet2 = s.getOrElse(ch2, Set.empty[Char]) + ch1
        s + (ch1 -> nSet1) + (ch2 -> nSet2)
      case (s, _) => s // sliding of 1 element
    }
    var nMap = ('a' to 'z').map(ch => ch -> m.getOrElse(ch, Set.empty[Char])).toMap
    var result = List.empty[String]
    var taken = ('a' to 'z').toSet
    var acc: Option[(Map[Char, Set[Char]], List[String], Set[Char])] = Some(nMap, List.empty[String], Set.empty[Char])
    ('a' to 'z').foldLeft(acc) {
      case (None, _) => None
      case (accum@Some((map, list, visited)), ch) if visited.contains(ch) => accum
      case (Some((map, list, visited)), ch) =>
        expand(map, list, visited, ch.toString)
    } match {
      case None => List("NO")
      case Some((m, list, set)) => List("YES", list.mkString(""))
    }
  }

  def expand(map: Map[Char, Set[Char]],list: List[String], visited: Set[Char], str: String): Option[(Map[Char, Set[Char]], List[String], Set[Char])] = {
    val neighborsFirst = map(str.head)
    val neighborsLast = map(str.last)
    if (neighborsFirst.size > 2) None
    else if (neighborsLast.size > 2) None
    else if (str.length == 1) {
      if (neighborsFirst.isEmpty) Some(map, str :: list, visited + str.head)
      else if (neighborsFirst.size == 1) expand(map, list, visited + str.head, neighborsFirst.head + str)
      else if (neighborsFirst.size == 2) expand(map, list, visited + str.head, neighborsFirst.head + str + neighborsFirst.last)
      else None
    }
    else {
      if (neighborsFirst.exists(ch => ch != str.charAt(1))) {
        var goodNeighbors = neighborsFirst.filter(ch => ch != str.charAt(1))
        if (goodNeighbors.exists(x => visited.contains(x)))
          None
        else expand(map, list, visited + str.head, goodNeighbors.head + str)
      }
      else if (neighborsLast.exists(ch => ch != str.charAt(str.length - 2))) {
        var goodNeighbors = neighborsLast.filter(ch => ch != str.charAt(str.length - 2))
        if (goodNeighbors.exists(x => visited.contains(x)))
          None
        else expand(map, list, visited + str.last, str + goodNeighbors.head)
      }
      else {
        Some(map, str :: list, visited + str.last + str.head)
      }
    }
  }
}

import scala.collection.Set

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val tb = stdin.next().toInt
  val rel = stdin.take(tb).map(solve)
  println(rel.flatten.mkString("\n"))

  def solve(str: String): List[String] = {
    var result: String = ""
    var visited = Set.empty[Char]
    var position = 0
    str.indices.foreach(i => {
      var ch = str.charAt(i)
      if (visited(ch)) {
       if (position > 0 && ch == result.charAt(position - 1))
         position -= 1
       else if (position + 1 < result.length && result.charAt(position + 1) == str.charAt(i))
         position += 1
       else
         return List("NO")
      }
      else {
        visited += ch
        if (position == 0) {
          result = ch + result
        }
        else if (position == result.length - 1) {
          result = result + ch
          position = result.length - 1
        }
      }
    })
    result = result + ('a' to 'z').filter(ch => !visited.contains(ch)).mkString("")
    List("YES", result)
  }
}


Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two other cities, and from each city it was possible to get to any other city. Government of Berland introduced one-way traffic on all n roads, but it soon became clear that it's impossible to get from some of the cities to some others. Now for each road is known in which direction the traffic is directed at it, and the cost of redirecting the traffic. What is the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other?

The first line contains integer n (3 ≤ n ≤ 100) — amount of cities (and roads) in Berland. Next n lines contain description of roads. Each road is described by three integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 100) — road is directed from city ai to city bi, redirecting the traffic costs ci.

Output single integer — the smallest amount of money the government should spend on the redirecting of roads so that from every city you can get to any other.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val edge = Array.fill[List[(Int, Int)]](n)(Nil)

  in.take(n).map(_.split(' ').map(_.toInt)).foreach {
    case Array(a, b, c) =>
      edge(a - 1) ::= (b - 1, 0)
      edge(b - 1) ::= (a - 1, c)
  }

  def count(index: Int) = {
    val visited = Array.ofDim[Boolean](n)
    val next = edge(0)(index)
    visited(0) = true

    val (res, i) = (1 until n - 1).foldLeft(next._2, next._1) {
      case ((sum, i), _) =>
        visited(i) = true
        val candidate = edge(i).find(e => !visited(e._1)).get
        (candidate._2 + sum, candidate._1)
    }
    res + edge(i).find(e => e._1 == 0).get._2
  }

  println(Math.min(count(0), count(1)))
}


You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".

The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.

Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.

NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".

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 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("[;,]").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)
  }
}


You are given a integer $$$n$$$ ($$$n > 0$$$). Find any integer $$$s$$$ which satisfies these conditions, or report that there are no such numbers:In the decimal representation of $$$s$$$:   $$$s > 0$$$,  $$$s$$$ consists of $$$n$$$ digits,  no digit in $$$s$$$ equals $$$0$$$,  $$$s$$$ is not divisible by any of it's digits.

The input consists of multiple test cases. The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 400$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case contains one positive integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). It is guaranteed that the sum of $$$n$$$ for all test cases does not exceed $$$10^5$$$.

For each test case, print an integer $$$s$$$ which satisfies the conditions described above, or "-1" (without quotes), if no such number exists. If there are multiple possible solutions for $$$s$$$, print any solution.

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


Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of $$$n$$$ rows and $$$n$$$ columns of square cells. The rows are numbered from $$$1$$$ to $$$n$$$, from top to bottom, and the columns are numbered from $$$1$$$ to $$$n$$$, from left to right. The position of a cell at row $$$r$$$ and column $$$c$$$ is represented as $$$(r, c)$$$. There are only two colors for the cells in cfpaint — black and white.There is a tool named eraser in cfpaint. The eraser has an integer size $$$k$$$ ($$$1 \le k \le n$$$). To use the eraser, Gildong needs to click on a cell $$$(i, j)$$$ where $$$1 \le i, j \le n - k + 1$$$. When a cell $$$(i, j)$$$ is clicked, all of the cells $$$(i', j')$$$ where $$$i \le i' \le i + k - 1$$$ and $$$j \le j' \le j + k - 1$$$ become white. In other words, a square with side equal to $$$k$$$ cells and top left corner at $$$(i, j)$$$ is colored white.A white line is a row or a column without any black cells.Gildong has worked with cfpaint for some time, so some of the cells (possibly zero or all) are currently black. He wants to know the maximum number of white lines after using the eraser exactly once. Help Gildong find the answer to his question.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2000$$$) — the number of rows and columns, and the size of the eraser. The next $$$n$$$ lines contain $$$n$$$ characters each without spaces. The $$$j$$$-th character in the $$$i$$$-th line represents the cell at $$$(i,j)$$$. Each character is given as either 'B' representing a black cell, or 'W' representing a white cell.

Print one integer: the maximum number of white lines after using the eraser exactly once.

NoteIn the first example, Gildong can click the cell $$$(2, 2)$$$, then the working screen becomes: BWWWWWWWWWWWWWWBThen there are four white lines — the $$$2$$$-nd and $$$3$$$-rd row, and the $$$2$$$-nd and $$$3$$$-rd column.In the second example, clicking the cell $$$(2, 3)$$$ makes the $$$2$$$-nd row a white line.In the third example, both the $$$2$$$-nd column and $$$5$$$-th row become white lines by clicking the cell $$$(3, 2)$$$.

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

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


Ringo found a string $$$s$$$ of length $$$n$$$ in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string $$$s$$$ into a palindrome by applying two types of operations to the string. The first operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_2s_3 \ldots s_i$$$ ($$$i - 1$$$ characters) reversed to the front of $$$s$$$.The second operation allows him to choose $$$i$$$ ($$$2 \le i \le n-1$$$) and to append the substring $$$s_i s_{i + 1}\ldots s_{n - 1}$$$ ($$$n - i$$$ characters) reversed to the end of $$$s$$$.Note that characters in the string in this problem are indexed from $$$1$$$.For example suppose $$$s=$$$abcdef. If he performs the first operation with $$$i=3$$$ then he appends cb to the front of $$$s$$$ and the result will be cbabcdef. Performing the second operation on the resulted string with $$$i=5$$$ will yield cbabcdefedc.Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most $$$30$$$ times. The length of the resulting palindrome must not exceed $$$10^6$$$It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.

The only line contains the string $$$S$$$ ($$$3 \le |s| \le 10^5$$$) of lowercase letters from the English alphabet.

The first line should contain $$$k$$$ ($$$0\le k \le 30$$$)  — the number of operations performed. Each of the following $$$k$$$ lines should describe an operation in form L i or R i. $$$L$$$ represents the first operation, $$$R$$$ represents the second operation, $$$i$$$ represents the index chosen. The length of the resulting palindrome must not exceed $$$10^6$$$.

NoteFor the first example the following operations are performed:abac $$$\to$$$ abacab $$$\to$$$ abacabaThe second sample performs the following operations: acccc $$$\to$$$ cccacccc $$$\to$$$ ccccaccccThe third example is already a palindrome so no operations are required.

import scala.io.StdIn
object A {
  def main(args: Array[String]): Unit = {
    var ans:StringBuilder=new StringBuilder()
//    var t=StdIn.readInt();
    var t=1
    while(t>0)
      {
        var str:String=StdIn.readLine()
        var n:Int=str.length
        ans.append("4\n")
        ans.append("L 2\n")
        n+=1

        ans.append("R 3\n")
        n+=n-3

        ans.append("R 2\n")
        n+=n-2

        ans.append("R ").append(n-1).append("\n")

        t-=1;
      }
    println(ans.toString());

  }
}


You are given two integers $$$l$$$ and $$$r$$$, $$$l\le r$$$. Find the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.As a reminder, $$$a \bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \bmod 8 = 2$$$.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\le t\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\le l \le r \le 10^9$$$).

For every test case, output the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.

NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \bmod b = 1 \bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \bmod b = 1$$$.

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

}


You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai.

The first line contains the only integer n (1 ≤ n ≤ 105) — the length of the permutation. The second line contains n integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation. All the integers are distinct.

Print the only integer — the element that should be removed to make the number of records the maximum possible. If there are multiple such elements, print the smallest one.

NoteIn the first example the only element can be removed.

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

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


You have a string $$$s_1 s_2 \ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \le k \le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$$$. What is the lexicographically smallest string you can see?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$): the number of test cases. The next $$$t$$$ lines contain the description of the test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$): the length of the string. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase English characters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the lexicographically smallest string you can see.

4
10
codeforces
9
cbacbacba
3
aaa
4
bbaa

NoteIn the first test case choose $$$k = 1$$$ to obtain "cc".In the second test case choose $$$k = 3$$$ to obtain "cbaabc".In the third test case choose $$$k = 1$$$ to obtain "aa".In the fourth test case choose $$$k = 1$$$ to obtain "bb".

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val s = nextLine
      var i = 1

      while (i < n && (s(i) < s(i - 1) || (s(i) == s(i - 1) && s(i) != s(0)))) {
        i += 1
      }

      val res = s.take(i) ++ s.take(i).reverse

      out.println(res)
    }

    out.flush()
  }

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

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val s = nextLine
      var i = 1

      while (i < n && s(i) < s(i - 1)) {
        i += 1
      }

      val res = s.take(i) ++ s.take(i).reverse

      out.println(res)
    }

    out.flush()
  }

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


You are given a cube of size k × k × k, which consists of unit cubes. Two unit cubes are considered neighbouring, if they have common face.Your task is to paint each of k3 unit cubes one of two colours (black or white), so that the following conditions must be satisfied:  each white cube has exactly 2 neighbouring cubes of white color;  each black cube has exactly 2 neighbouring cubes of black color.

The first line contains integer k (1 ≤ k ≤ 100), which is size of the cube.

Print -1 if there is no solution. Otherwise, print the required painting of the cube consequently by layers. Print a k × k matrix in the first k lines, showing how the first layer of the cube should be painted. In the following k lines print a k × k matrix — the way the second layer should be painted. And so on to the last k-th layer. Note that orientation of the cube in the space does not matter. Mark a white unit cube with symbol "w" and a black one with "b". Use the format of output data, given in the test samples. You may print extra empty lines, they will be ignored.

object A extends App {

  def solve(n: Int): Int = {

    n
  }

  def readString = Console.readLine

  val n = readString.toInt

  if (n % 2 == 0) {
    for (i <- 0 until n) {
      val ii = (i / 2) % 2
      for (j <- 0 until n) {
        val b1 = (j / 2) % 2 == ii
        println((0 until n).map(k => if ((k % 2 == 0) == b1) 'b' else 'w').mkString)
      }
      println
    }
  } else println(-1)
}

object A extends App {

  def solve(n: Int): Int = {

    n
  }

  def readString = Console.readLine

  val k = readString.toInt

  if (k == 2) {
    println("bb")
    println("ww")
    println("")
    println("bb")
    println("ww")
  } else println(-1)
}

object A extends App {

  def solve(n: Int): Int = {

    n
  }

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt

  println(solve(n))
}


Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.

The first line contains an integer n (1 ≤ n ≤ 1000).

On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.

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

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
}