You are given a system of pipes. It consists of two rows, each row consists of $$$n$$$ pipes. The top left pipe has the coordinates $$$(1, 1)$$$ and the bottom right — $$$(2, n)$$$.There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types:  Types of pipes You can turn each of the given pipes $$$90$$$ degrees clockwise or counterclockwise arbitrary (possibly, zero) number of times (so the types $$$1$$$ and $$$2$$$ can become each other and types $$$3, 4, 5, 6$$$ can become each other).You want to turn some pipes in a way that the water flow can start at $$$(1, 0)$$$ (to the left of the top left pipe), move to the pipe at $$$(1, 1)$$$, flow somehow by connected pipes to the pipe at $$$(2, n)$$$ and flow right to $$$(2, n + 1)$$$.Pipes are connected if they are adjacent in the system and their ends are connected. Here are examples of connected pipes:  Examples of connected pipes Let's describe the problem using some example:  The first example input And its solution is below:   The first example answer As you can see, the water flow is the poorly drawn blue line. To obtain the answer, we need to turn the pipe at $$$(1, 2)$$$ $$$90$$$ degrees clockwise, the pipe at $$$(2, 3)$$$ $$$90$$$ degrees, the pipe at $$$(1, 6)$$$ $$$90$$$ degrees, the pipe at $$$(1, 7)$$$ $$$180$$$ degrees and the pipe at $$$(2, 7)$$$ $$$180$$$ degrees. Then the flow of water can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of queries. Then $$$q$$$ queries follow. Each query consists of exactly three lines. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of pipes in each row. The next two lines contain a description of the first and the second rows correspondingly. Each row description consists of $$$n$$$ digits from $$$1$$$ to $$$6$$$ without any whitespaces between them, each digit corresponds to the type of pipe in the corresponding cell. See the problem statement to understand which digits correspond to which types of pipes. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For the $$$i$$$-th query print the answer for it — "YES" (without quotes) if it is possible to turn some pipes in a way that the water flow can reach $$$(2, n + 1)$$$ from $$$(1, 0)$$$, and "NO" otherwise.

NoteThe first query from the example is described in the problem statement.

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

  override def apply(io: IO): io.type = {
    repeat(io.read[Int]) {
      val n = io.read[Int]
      val pipes = io.read[Vector, String](2)

      def isL(p: Int, i: Int) = pipes(p)(i) >= '3'

      @tailrec
      def isValid(p: Int, i: Int): Boolean =
        if (i == n) {
          p == 1
        } else if (isL(p, i)) {
          isL(1 - p, i) && isValid(1 - p, i + 1)
        } else {
          isValid(p, i + 1)
        }

      val ans = isValid(0, 0)
      io.writeLine(ans.toEnglish.toUpperCase())
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).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: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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 _1234C extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    repeat(io.read[Int]) {
      val n = io.read[Int]
      val pipes = io.read[Vector, String](2)

      @tailrec
      def isValid(p: Int, i: Int): Boolean = {
        if (i == n) {
          p == 1
        } else {
          pipes(p)(i) match {
            case c if c <= '2' => isValid(p, i + 1)
            case _ => (pipes(1 - p)(i) >= 3) && isValid(1 - p, i + 1)
          }
        }
      }
      val ans = isValid(0, 0)
      io.writeLine(ans.toEnglish.toUpperCase())
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).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: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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 _1234C extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    repeat(io.read[Int]) {
      val n = io.read[Int]
      val pipes = io.read[Vector, String](2)

      def isL(p: Int, i: Int) = pipes(p)(i) >= '3'

      @tailrec
      def isValid(p: Int, i: Int): Boolean =
        if (i == n) {
          p == 1
        } else if (isL(p, i)) {
          isValid(1 - p, i + 1)
        } else {
          isValid(p, i + 1)
        }

      val ans = isValid(0, 0)
      io.writeLine(ans.toEnglish.toUpperCase())
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).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: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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
      }
    }
  }
}


Lunar New Year is approaching, and you bought a matrix with lots of "crosses".This matrix $$$M$$$ of size $$$n \times n$$$ contains only 'X' and '.' (without quotes). The element in the $$$i$$$-th row and the $$$j$$$-th column $$$(i, j)$$$ is defined as $$$M(i, j)$$$, where $$$1 \leq i, j \leq n$$$. We define a cross appearing in the $$$i$$$-th row and the $$$j$$$-th column ($$$1 < i, j < n$$$) if and only if $$$M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $$$ 'X'.The following figure illustrates a cross appearing at position $$$(2, 2)$$$ in a $$$3 \times 3$$$ matrix. X.X.X.X.X Your task is to find out the number of crosses in the given matrix $$$M$$$. Two crosses are different if and only if they appear in different rows or columns.

The first line contains only one positive integer $$$n$$$ ($$$1 \leq n \leq 500$$$), denoting the size of the matrix $$$M$$$. The following $$$n$$$ lines illustrate the matrix $$$M$$$. Each line contains exactly $$$n$$$ characters, each of them is 'X' or '.'. The $$$j$$$-th element in the $$$i$$$-th line represents $$$M(i, j)$$$, where $$$1 \leq i, j \leq n$$$.

Output a single line containing only one integer number $$$k$$$ — the number of crosses in the given matrix $$$M$$$.

NoteIn the first sample, a cross appears at $$$(3, 3)$$$, so the answer is $$$1$$$.In the second sample, no crosses appear since $$$n < 3$$$, so the answer is $$$0$$$.In the third sample, crosses appear at $$$(3, 2)$$$, $$$(3, 4)$$$, $$$(4, 3)$$$, $$$(4, 5)$$$, so the answer is $$$4$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val M = nm_c(N, N)
    var ans = 0
    val X = Array(0, -1, -1, 1, 1)
    val Y = Array(0, -1, 1, -1, 1)

    def test(x: Int, y: Int) = {
      0 until 5 forall { i =>
        0 <= x + X(i) && x + X(i) < N &&
        0 <= y + Y(i) && y + Y(i) < N &&
        M(X(i) + x)(Y(i) + y) == 'X'
      }
    }

    REP(N) { i =>
      REP(N) { j =>
        if (test(i, j)) ans += 1
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

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

import java.util.Scanner
import scala.collection.mutable

object Main {

  def main(args: Array[String]): Unit = {
    val scan = new Scanner(System.in)
    val n = scan.nextInt
    scan.nextLine
    var grid = mutable.ArrayBuffer[String]()
    for (i <- 0 until n) {
      grid += scan.nextLine
    }
    var ans = 0
    for {
      i <- 1 until n - 1
      j <- 1 until n - 1
    } if (isCross(grid, i, j)) ans += 1
    println(ans)
  }

  def isCross(g: mutable.ArrayBuffer[String], x: Int, y: Int): Boolean = {
    g(x)(y) == 'X' &&
      g(x - 1)(y - 1) == 'X' &&
      g(x + 1)(y - 1) == 'X' &&
      g(x - 1)(y + 1) == 'X' &&
      g(x + 1)(y + 1) == 'X'
  }
}


The Squareland national forest is divided into equal $$$1 \times 1$$$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $$$(x, y)$$$ of its south-west corner.Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land $$$A, B, C$$$ in the forest. Initially, all plots in the forest (including the plots $$$A, B, C$$$) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots $$$A, B, C$$$ from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side.    For example, $$$A=(0,0)$$$, $$$B=(1,1)$$$, $$$C=(2,2)$$$. The minimal number of plots to be cleared is $$$5$$$. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.

The first line contains two integers $$$x_A$$$ and $$$y_A$$$ — coordinates of the plot $$$A$$$ ($$$0 \leq x_A, y_A \leq 1000$$$). The following two lines describe coordinates $$$(x_B, y_B)$$$ and $$$(x_C, y_C)$$$ of plots $$$B$$$ and $$$C$$$ respectively in the same format ($$$0 \leq x_B, y_B, x_C, y_C \leq 1000$$$). It is guaranteed that all three plots are distinct.

On the first line print a single integer $$$k$$$ — the smallest number of plots needed to be cleaned from trees. The following $$$k$$$ lines should contain coordinates of all plots needed to be cleaned. All $$$k$$$ plots should be distinct. You can output the plots in any order. If there are multiple solutions, print any of them.

NoteThe first example is shown on the picture in the legend.The second example is illustrated with the following image:

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)

  case class Coord(x: Int, y: Int)
  case class Path(p1: Coord, p2: Coord)
  type Grid = Array[Array[Boolean]]

  def solve(): Unit = {
    val MAX = 1001
//    val MAX = 3
    val C1, C2, C3 = Coord(ni(), ni())
    val E = Array(Path(C1, C2), Path(C2, C3), Path(C3, C1))

    def cnt(g: Grid) = g.map(_.count(identity)).sum

    def paintLine(c1: Coord, c2: Coord, g: Grid): Unit = {
      if (c1.x == c2.x) {
        val iniY = min(c1.y, c2.y)
        REP(abs(c1.y - c2.y) + 1, iniY) { y =>
          g(c1.x)(y) = true
        }
      } else if (c1.y == c2.y){
        val iniX = min(c1.x, c2.x)
        REP(abs(c1.x - c2.x) + 1, iniX) { x =>
          g(x)(c1.y) = true
        }
      } else {
        throw new IllegalArgumentException(s"$c1 $c2")
      }
    }

    def onLine(p: Path) = p.p1.x == p.p2.x || p.p1.y == p.p2.y

    def paint(p: Path, g: Grid, flg: Boolean): Unit = {
      if (onLine(p)) {
        paintLine(p.p1, p.p2, g)
      } else {
        val lt = Coord(min(p.p1.x, p.p2.x), max(p.p1.y, p.p2.y))
        val rt = Coord(max(p.p1.x, p.p2.x), max(p.p1.y, p.p2.y))
        val lb = Coord(min(p.p1.x, p.p2.x), min(p.p1.y, p.p2.y))
        val rb = Coord(max(p.p1.x, p.p2.x), min(p.p1.y, p.p2.y))
        val Array(c1, c2) = Array(lt, rt, lb, rb).filter(c => c != p.p1 && c != p.p2)
        val c = if (flg) c1 else c2
        paintLine(p.p1, c, g)
        paintLine(p.p2, c, g)
      }
    }

    val memo = Array.ofDim[Boolean](12, MAX, MAX)

    val grids = map(3)(identity).flatMap { i =>
      for {
        x1 <- 0 until 2
        x2 <- 0 until 2
      } yield {
        val Array(p1, p2) = E.zipWithIndex.filterNot(_._2 == i).map(_._1)
        val g = memo(i * 4 + x1 * 2 + x2)
        paint(p1, g, x1 == 1)
        paint(p2, g, x2 == 1)

        g
      }
    }

    val ans = grids.minBy(cnt)
    out.println(cnt(ans))
    REP(MAX) { i =>
      REP(MAX) { j =>
        if (ans(i)(j)) out.println(s"$i $j")
      }
    }
  }

  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)

  sealed trait Move[A] {
    val l: Int
    val r: Int
    def axis: Int
    def len = r - l + 1
    def extend(l: Int, r: Int): A
  }
  case class MoveX(y: Int, l: Int, r: Int) extends Move[MoveX] {
    override def axis = y
    def extend(l: Int, r: Int) = MoveX(y, l, r)
  }
  case class MoveY(x: Int, l: Int, r: Int) extends Move[MoveY] {
    override def axis = x
    override def extend(l: Int, r: Int) = MoveY(x, l, r)
  }
  case class Coord(x: Int, y: Int)
  case class Path(c1: Coord, c2: Coord)

  case class Moves(xs: Seq[MoveX], ys: Seq[MoveY])

  def solve(): Unit = {
    val c1, c2, c3 = Coord(ni(), ni())
    val C = Array(c1, c2, c3)

    def moveX(p1: Coord, p2: Coord) = {
      assert(p1.y == p2.y)
      MoveX(p1.y, min(p1.x, p2.x), max(p1.x, p2.x))
    }

    def moveY(p1: Coord, p2: Coord) = {
      assert(p1.x == p2.x)
      MoveY(p1.x, min(p1.y, p2.y), max(p1.y, p2.y))
    }

    def move(p: Path): (MoveX, MoveY) = {
      val Path(c1, c2) = p
      val xmin = min(c1.x, c2.x)
      val xmax = max(c1.x, c2.x)
      val ymin = min(c1.y, c2.y)
      val ymax = max(c1.y, c2.y)
      val lt = Coord(xmin, ymax)
      val rt = Coord(xmax, ymax)
      val lb = Coord(xmin, ymin)
      val rb = Coord(xmax, ymin)

      // 時計回り
      val P = Array(lt, rt, rb, lb)
      val s = P.indexOf(c1)
      val m = (s + 1) % 4
      val e = (s + 2) % 4

      // X -> Y
      if (s % 2 == 0) {
        (moveX(P(s), P(m)), moveY(P(m), P(e)))

      // Y -> X
      } else {
        (moveX(P(m), P(e)), moveY(P(s), P(m)))
      }
    }

    def len(moves: Moves) = {
      var len = (moves.xs ++ moves.ys).map(_.len).sum
      moves.xs foreach { x =>
        len -= moves.ys.count(y => y.l <= x.y && x.y <= y.r && x.l <= y.x && y.x <= x.r)
      }
      len
    }

    def merge2[A <: Move[A]](m1: A, m2: A): Seq[A] = {
      if (m1.axis == m2.axis) {
        val l = max(m1.l, m2.l)
        val r = min(m1.r, m2.r)
        // 重複部分あり
        if (l <= r) {
          Seq(m1.extend(min(m1.l, m2.l), max(m1.r, m2.r)))
        } else {
          Seq(m1, m2)
        }
      } else {
        Seq(m1, m2)
      }
    }

    def merge4(arg: (MoveX, MoveX, MoveY, MoveY)): Moves = {
      val (x1, x2, y1, y2) = arg

      val xs = merge2(x1, x2)
      val ys = merge2(y1, y2)

      Moves(xs, ys)
    }

    val ans = (for {
      c1 <- C
      c2 <- C
      c3 <- C
      if Set(c1, c2, c3).size == 3
      (x1, y1) = move(Path(c1, c2))
      (x2, y2) = move(Path(c2, c3))
    } yield merge4((x1, x2, y1, y2))).minBy(len)

    out.println(len(ans))

    val flg = Array.ofDim[Boolean](1001, 1001)

    (ans.xs ++ ans.ys) foreach { move =>
      REP(move.len) { i =>
        move match {
          case MoveX(y, l, r) =>
            if (!flg(l + i)(y)) {
              out.println(s"${l + i} $y")
              flg(l + i)(y) = true
            }

          case MoveY(x, l, r) =>
            if (!flg(x)(l + i)) {
              out.println(s"$x ${l + i}")
              flg(x)(l + i) = true
            }
        }
      }
    }
  }

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

  type In = Seq[(Int, Int)]
  type Out = String

  def solve(in: In): Out = {
    val Seq(a, b, c) = in.sorted
    def right(a: (Int, Int), b: Int) = (a._1 to b).map(x => (x, a._2))
    def up(a: (Int, Int), b: Int) = if(b >= a._2) (a._2 to b).map(y => (a._1, y)) else (b to a._2).map(y => (a._1, y))
    // Go across, then up/down, then up/down, then across
    val squares = (right(a, b._1) ++ up((b._1, a._2), b._2) ++ up(b, c._2) ++ right((b._1, c._2), c._1)).toSet
    squares.size.toString + "\n" + squares.map { case (a, b) => s"$a $b" }.mkString("\n")
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input)    = i.getLines.map{_.split(" ")}.map{case Array(a,b) => (a.toInt, b.toInt)}
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

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)

  case class Coord(x: Int, y: Int)
  case class Path(p1: Coord, p2: Coord)
  type Grid = Array[Array[Boolean]]

  def solve(): Unit = {
    val C1, C2, C3 = Coord(ni(), ni())
    val E = Array(Path(C1, C2), Path(C2, C3), Path(C3, C1))

    def paint(p: Path, g: Grid): Unit = {
      val x = min(p.p1.x, p.p2.x)
      val xLen = abs(p.p1.x - p.p2.x)
      val y = min(p.p1.y, p.p2.y)
      val yLen = abs(p.p1.y - p.p2.y)

      REP(xLen + 1) { i =>
        g(x + i)(y) = true
      }

      REP(yLen + 1) { i =>
        g(x + xLen)(y + i) = true
      }
    }

    val grids = map(3) { i =>
      val Array(e1, e2) = E.zipWithIndex.filterNot(_._2 == i).map(_._1)
      val g = Array.ofDim[Boolean](1001, 1001)
      paint(e1, g)
      paint(e2, g)
      g
    }

    def cnt(g: Grid) = g.map(_.count(identity)).sum

    val ans = grids.minBy(cnt)
    out.println(cnt(ans))
    REP(1001) { i =>
      REP(1001) { j =>
        if (ans(i)(j)) out.println(s"$i $j")
      }
    }
  }

  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)

  sealed trait Move[A] {
    val l: Int
    val r: Int
    def axis: Int
    def len = r - l + 1
    def extend(l: Int, r: Int): A
  }
  case class MoveX(y: Int, l: Int, r: Int) extends Move[MoveX] {
    override def axis = y
    def extend(l: Int, r: Int) = MoveX(y, l, r)
  }
  case class MoveY(x: Int, l: Int, r: Int) extends Move[MoveY] {
    override def axis = x
    override def extend(l: Int, r: Int) = MoveY(x, l, r)
  }
  case class Coord(x: Int, y: Int)
  case class Path(c1: Coord, c2: Coord)

  case class Moves(xs: Seq[MoveX], ys: Seq[MoveY])

  def solve(): Unit = {
    val c1, c2, c3 = Coord(ni(), ni())
    val C = Array(c1, c2, c3)

    def moveX(p1: Coord, p2: Coord) = {
      assert(p1.y == p2.y)
      MoveX(p1.y, min(p1.x, p2.x), max(p1.x, p2.x))
    }

    def moveY(p1: Coord, p2: Coord) = {
      assert(p1.x == p2.x)
      MoveY(p1.x, min(p1.y, p2.y), max(p1.y, p2.y))
    }

    def move(p: Path): (MoveX, MoveY) = {
      val Path(c1, c2) = p
      val xmin = min(c1.x, c2.x)
      val xmax = max(c1.x, c2.x)
      val ymin = min(c1.y, c2.y)
      val ymax = max(c1.y, c2.y)
      val lt = Coord(xmin, ymax)
      val rt = Coord(xmax, ymax)
      val lb = Coord(xmin, ymin)
      val rb = Coord(xmax, ymin)

      // 時計回り
      val P = Array(lt, rt, rb, lb)
      val s = P.indexOf(c1)
      val m = (s + 1) % 4
      val e = (s + 2) % 4

      // X -> Y
      if (s % 2 == 0) {
        (moveX(P(s), P(m)), moveY(P(m), P(e)))

      // Y -> X
      } else {
        (moveX(P(m), P(e)), moveY(P(s), P(m)))
      }
    }

    def len(moves: Moves) = {
      var len = (moves.xs ++ moves.ys).map(_.len).sum
      moves.xs foreach { x =>
        len -= moves.ys.count(y => y.l <= x.y && x.y <= y.r)
      }
      len
    }

    def merge2[A <: Move[A]](m1: A, m2: A): Seq[A] = {
      if (m1.axis == m2.axis) {
        val l = max(m1.l, m2.l)
        val r = min(m1.r, m2.r)
        // 重複部分あり
        if (l <= r) {
          Seq(m1.extend(min(m1.l, m2.l), max(m1.r, m2.r)))
        } else {
          Seq(m1, m2)
        }
      } else {
        Seq(m1, m2)
      }
    }

    def merge4(arg: (MoveX, MoveX, MoveY, MoveY)): Moves = {
      val (x1, x2, y1, y2) = arg

      val xs = merge2(x1, x2)
      val ys = merge2(y1, y2)

      Moves(xs, ys)
    }

    val ans = (for {
      c1 <- C
      c2 <- C
      c3 <- C
      if Set(c1, c2, c3).size == 3
      (x1, y1) = move(Path(c1, c2))
      (x2, y2) = move(Path(c2, c3))
    } yield merge4((x1, x2, y1, y2))).minBy(len)

    out.println(len(ans))

    val flg = Array.ofDim[Boolean](1001, 1001)

    (ans.xs ++ ans.ys) foreach { move =>
      REP(move.len) { i =>
        move match {
          case MoveX(y, l, r) =>
            if (!flg(l + i)(y)) {
              out.println(s"${l + i} $y")
              flg(l + i)(y) = true
            }

          case MoveY(x, l, r) =>
            if (!flg(x)(l + i)) {
              out.println(s"$x ${l + i}")
              flg(x)(l + i) = true
            }
        }
      }
    }
  }

  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)

  sealed trait Move[A] {
    val l: Int
    val r: Int
    def axis: Int
    def len = r - l + 1
    def extend(l: Int, r: Int): A
  }
  case class MoveX(y: Int, l: Int, r: Int) extends Move[MoveX] {
    override def axis = y
    def extend(l: Int, r: Int) = MoveX(y, l, r)
  }
  case class MoveY(x: Int, l: Int, r: Int) extends Move[MoveY] {
    override def axis = x
    override def extend(l: Int, r: Int) = MoveY(x, l, r)
  }
  case class Coord(x: Int, y: Int)
  case class Path(c1: Coord, c2: Coord)

  case class Moves(xs: Seq[MoveX], ys: Seq[MoveY])

  def solve(): Unit = {
    val c1, c2, c3 = Coord(ni(), ni())
    val P = Array(Path(c1, c2), Path(c2, c3), Path(c3, c1))

    def moveX(p1: Coord, p2: Coord) = {
      assert(p1.y == p2.y)
      MoveX(p1.y, min(p1.x, p2.x), max(p1.x, p2.x))
    }

    def moveY(p1: Coord, p2: Coord) = {
      assert(p1.x == p2.x)
      MoveY(p1.x, min(p1.y, p2.y), max(p1.y, p2.y))
    }

    def move(p: Path): (MoveX, MoveY) = {
      val Path(c1, c2) = p
      val xmin = min(c1.x, c2.x)
      val xmax = max(c1.x, c2.x)
      val ymin = min(c1.y, c2.y)
      val ymax = max(c1.y, c2.y)
      val lt = Coord(xmin, ymax)
      val rt = Coord(xmax, ymax)
      val lb = Coord(xmin, ymin)
      val rb = Coord(xmax, ymin)

      // 時計回り
      val P = Array(lt, rt, rb, lb)
      val s = P.indexOf(c1)
      val m = (s + 1) % 4
      val e = (s + 2) % 4

      // X -> Y
      if (s % 2 == 0) {
        (moveX(P(s), P(m)), moveY(P(m), P(e)))

      // Y -> X
      } else {
        (moveX(P(m), P(e)), moveY(P(s), P(m)))
      }
    }

    def len(moves: Moves) = {
      var len = (moves.xs ++ moves.ys).map(_.len).sum
      moves.xs foreach { x =>
        len -= moves.ys.count(y => y.l <= x.y && x.y <= y.r)
      }
      len
    }

    def merge2[A <: Move[A]](m1: A, m2: A): Seq[A] = {
      if (m1.axis == m2.axis) {
        val l = max(m1.l, m2.l)
        val r = min(m1.r, m2.r)
        // 重複部分あり
        if (l <= r) {
          Seq(m1.extend(min(m1.l, m2.l), max(m1.r, m2.r)))
        } else {
          Seq(m1, m2)
        }
      } else {
        Seq(m1, m2)
      }
    }

    def merge4(arg: (MoveX, MoveX, MoveY, MoveY)): Moves = {
      val (x1, x2, y1, y2) = arg

      val xs = merge2(x1, x2)
      val ys = merge2(y1, y2)

      Moves(xs, ys)
    }

    val ans = (for {
      p1 <- P
      p2 <- P
      if p1 != p2
      (x1, y1) = move(p1)
      (x2, y2) = move(p2)
    } yield merge4((x1, x2, y1, y2))).minBy(len)

    out.println(len(ans))

    val flg = Array.ofDim[Boolean](1001, 1001)

    (ans.xs ++ ans.ys) foreach { move =>
      REP(move.len) { i =>
        move match {
          case MoveX(y, l, r) =>
            if (!flg(l + i)(y)) {
              out.println(s"${l + i} $y")
              flg(l + i)(y) = true
            }

          case MoveY(x, l, r) =>
            if (!flg(x)(l + i)) {
              out.println(s"$x ${l + i}")
              flg(x)(l + i) = true
            }
        }
      }
    }
  }

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

  type In = Seq[(Int, Int)]
  type Out = String

  def solve(in: In): Out = {
    val Seq(a, b, c) = in.sorted
    def right(a: (Int, Int), b: Int) = (a._1 to b).map(x => (x, a._2))
    def up(a: (Int, Int), b: Int) = (a._2 to b).map(y => (a._1, y))
    // Go across, then up/down, then up/down, then across
    val squares = (right(a, b._1) ++ up((b._1, a._1), b._2) ++ up(b, c._2) ++ right((b._1, c._2), c._1)).toSet
    squares.size.toString + "\n" + squares.map { case (a, b) => s"$a $b" }.mkString("\n")
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input)    = i.getLines.map{_.split(" ")}.map{case Array(a,b) => (a.toInt, b.toInt)}
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}

object CF_528_2_C {

  type In = Seq[(Int, Int)]
  type Out = String

  def solve(in: In): Out = {
    val Seq(a, b, c) = in.sorted
    def right(a: (Int, Int), b: Int) = (a._1 to b).map(x => (x, a._2))
    def up(a: (Int, Int), b: Int) = (a._2 to b).map(y => (a._1, y))
    // Go across, then up/down, then up/down, then across
    val squares = (right(a, b._1) ++ up((b._1, a._2), b._2) ++ up(b, c._2) ++ right((b._1, c._2), c._1)).toSet
    squares.size.toString + "\n" + squares.map { case (a, b) => s"$a $b" }.mkString("\n")
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input)    = i.getLines.map{_.split(" ")}.map{case Array(a,b) => (a.toInt, b.toInt)}
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change:

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream) =       this(new Scanner(i))
    def this(s: String) =            this(new Scanner(s.stripMargin))
    def int =                        sc.nextInt()
    def long =                       sc.nextLong()
    def double =                     sc.nextDouble()
    def nextLine =                   sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq =                     collect(_.toInt)
    def doubleSeq =                  collect(_.toDouble)
    def getLines: Vector[String] =   if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def solveVal: Out =              (solve _).tupled(formatIn(this))
    def solveStr: String =           formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  def ceil(a: Int, b: Int)   = (a - 1)/b + 1
  def ceil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}


The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $$$n$$$ haybale piles on the farm. The $$$i$$$-th pile contains $$$a_i$$$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) such that $$$|i-j|=1$$$ and $$$a_i>0$$$ and apply $$$a_i = a_i - 1$$$, $$$a_j = a_j + 1$$$. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile $$$1$$$ (i.e. to maximize $$$a_1$$$), and she only has $$$d$$$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $$$1$$$ if she acts optimally!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)  — the number of test cases. Next $$$2t$$$ lines contain a description of test cases  — two lines per test case. The first line of each test case contains integers $$$n$$$ and $$$d$$$ ($$$1 \le n,d \le 100$$$) — the number of haybale piles and the number of days, respectively.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$)  — the number of haybales in each pile.

For each test case, output one integer: the maximum number of haybales that may be in pile $$$1$$$ after $$$d$$$ days if Bessie acts optimally.

NoteIn the first test case of the sample, this is one possible way Bessie can end up with $$$3$$$ haybales in pile $$$1$$$:   On day one, move a haybale from pile $$$3$$$ to pile $$$2$$$  On day two, move a haybale from pile $$$3$$$ to pile $$$2$$$  On day three, move a haybale from pile $$$2$$$ to pile $$$1$$$  On day four, move a haybale from pile $$$2$$$ to pile $$$1$$$  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $$$2$$$ to pile $$$1$$$ on the second day.

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 minDays(a: Array[Int],pos: Int, target: Int): Option[Int] = {
    if(a(pos) >= target){
      Some(0)
    }else{
      if(pos >= a.length-1)
        None
      else
        minDays(a,pos+1,target-a(pos)).map{ d =>
          d+target-a(pos)
        }
    }
  }

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach(_ => {
      val n = in.nextInt()
      val d = in.nextInt()
      val a = (1 to n).map(_ => in.nextInt()).toArray
      val res = (0 to 200).zipWithIndex.flatMap{case (h,i) => minDays(a,0,h).flatMap(m => if(m <= d) Some(i) else None)}.max
      out.println(res)
    })
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

import java.io.PrintWriter

import scala.collection.mutable
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        var Array(n, d) = readArrayInt()
        val a = readArrayInt()
        var rs = a(0)
        for (i <- 1 until n if a(i) > 0) {
            rs += math.min(d / i, a(i))
            d -= math.min(d/i, a(i))*i
        }
        println(rs)
    }

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

import java.io.PrintWriter

import scala.collection.mutable
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        var Array(n, d) = readArrayInt()
        val a = readArrayInt()
        var rs = a(0)
        for (i <- 1 until n) {
            while (d > 0 && a(i) >= i) {
                rs += 1
                d -= i
                a(i) -= 1
            }
        }
        println(rs)
    }

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


Game "Minesweeper 1D" is played on a line of squares, the line's height is 1 square, the line's width is n squares. Some of the squares contain bombs. If a square doesn't contain a bomb, then it contains a number from 0 to 2 — the total number of bombs in adjacent squares.For example, the correct field to play looks like that: 001*2***101*. The cells that are marked with "*" contain bombs. Note that on the correct field the numbers represent the number of bombs in adjacent cells. For example, field 2* is not correct, because cell with value 2 must have two adjacent cells with bombs.Valera wants to make a correct field to play "Minesweeper 1D". He has already painted a squared field with width of n cells, put several bombs on the field and wrote numbers into some cells. Now he wonders how many ways to fill the remaining cells with bombs and numbers are there if we should get a correct field in the end.

The first line contains sequence of characters without spaces s1s2... sn (1 ≤ n ≤ 106), containing only characters "*", "?" and digits "0", "1" or "2". If character si equals "*", then the i-th cell of the field contains a bomb. If character si equals "?", then Valera hasn't yet decided what to put in the i-th cell. Character si, that is equal to a digit, represents the digit written in the i-th square.

Print a single integer — the number of ways Valera can fill the empty cells and get a correct field. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

NoteIn the first test sample you can get the following correct fields: 001**1, 001***, 001*2*, 001*10.

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

/**
 * Created by hama_du on 2014/03/20.
 */
object ProblemD extends App {
  val MOD = 1000000007L
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val c = in.nextLine().toCharArray

  out.println(solve())
  out.flush()

  def solve(): Long = {
    val n = c.length
    val dp = Array.ofDim[Long](6,n+1)
    dp(5)(0) = 1
    def add(i: Int, ai: Int, base: Long) {
      if (c(i) == '?') {
        dp(ai)(i+1) += base
        dp(ai)(i+1) %= MOD
      } else {
        if (ai == 0) {
          if (c(i) == '0') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        } else if (ai == 1 || ai == 2) {
          if (c(i) == '1') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        } else if (ai == 3) {
          if (c(i) == '2') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        } else {
          if (c(i) == '*') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        }
      }
    }

    // 0:0
    // 1:1/left
    // 2:1/right
    // 3:2
    // 4:bomb
    for (i <- 0 until n) {
      for (j <- 0 until 6) {
        val base = dp(j)(i)
        if (j == 0) {
          add(i, 0, base)
          add(i, 2, base)
        } else if (j == 1) {
          add(i, 0, base)
          add(i, 2, base)
        } else if (j == 2) {
          add(i, 4, base)
        } else if (j == 3) {
          add(i, 4, base)
        } else if (j == 4) {
          add(i, 1, base)
          add(i, 3, base)
          add(i, 4, base)
        } else {
          add(i, 0, base)
          add(i, 2, base)
          add(i, 4, base)
        }
      }
    }
    (dp(0)(n) + dp(1)(n) + dp(4)(n)) % MOD
  }
}

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

/**
 * Created by hama_du on 2014/03/20.
 */
object ProblemD extends App {
  val MOD = 1000000007
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val c = in.nextLine().toCharArray

  out.println(solve())
  out.flush()

  def solve(): Long = {
    val n = c.length
    val dp = Array.ofDim[Long](6,n+1)
    dp(5)(0) = 1
    def add(i: Int, ai: Int, base: Long) {
      if (c(i) == '?') {
        dp(ai)(i+1) += base
        dp(ai)(i+1) %= MOD
      } else {
        if (ai == 0) {
          if (c(i) == '0') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        } else if (ai == 1 || ai == 2) {
          if (c(i) == '1') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        } else if (ai == 3) {
          if (c(i) == '2') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        } else {
          if (c(i) == '*') {
            dp(ai)(i+1) += base
            dp(ai)(i+1) %= MOD
          }
        }
      }
    }

    // 0:0
    // 1:1/left
    // 2:1/right
    // 3:2
    // 4:bomb
    for (i <- 0 until n) {
      for (j <- 0 until 6) {
        val base = dp(j)(i)
        if (j == 0) {
          add(i, 0, base)
          add(i, 2, base)
        } else if (j == 1) {
          add(i, 0, base)
          add(i, 2, base)
        } else if (j == 2) {
          add(i, 4, base)
        } else if (j == 3) {
          add(i, 4, base)
        } else if (j == 4) {
          add(i, 1, base)
          add(i, 2, base)
          add(i, 4, base)
        } else {
          add(i, 0, base)
          add(i, 2, base)
          add(i, 4, base)
        }
      }
    }
    (dp(0)(n) + dp(1)(n) + dp(4)(n)) % MOD
  }
}


Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?

The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000).

Print the n-th even-length palindrome number.

NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.

object B {
  def main(args: Array[String]) = {
    val n = readLine()
    println(n + n.reverse)
  }

  def readLine() = io.StdIn.readLine()
  def readInts() = readLine().split(' ').map(_.toInt)

  def digits(s: String) = s.map(_.toString.toInt)
}

object Main {
  def main(args: Array[String]) {
    val  x = readLine()
    println(x + x.reverse)
  }
}

object B {
    def main(args: Array[String]) {
        val n = readLine
        println(n + n.reverse)
    }
}

import scala.io._
import java.util.Scanner

object Main {
    def main(args: Array[String]) {
        val scanner = new Scanner(System.in)
        val a = scanner.next()

        println(a + a.reverse)
    }
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val line = lines.next()
  print(line)
  print(line.reverse)
}

object B688 {
  @inline def read = scala.io.StdIn.readLine

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

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

  def main(args: Array[String]): Unit = {
    val n = read
    println(n + n.reverse)
  }
}

object cf_688B {
  def main(args: Array[String]) {
    val input = readLine()
    print(input)
    for (s <- input.reverse) print(s)
  }
}

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

object _688B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val s = read[String]
    write(s + s.reverse)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toYesNo = if(x) "yes" else "no"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    def bitCount: Int = java.lang.Integer.bitCount(x)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V]: mutable.MultiMap[K, V] = new mutable.HashMap[K, mutable.Set[V]] with mutable.MultiMap[K, V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @inline 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)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: C of A): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  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 = write(obj mkString separator)

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

import java.util.Scanner

object MainApp {
  def isEvenPalindrome(n: List[Char]): Boolean =
    n match {
      case Nil => true
      case x if n.length % 2 != 0 => false
      case x :: xs => if (n.head == n.last) isEvenPalindrome(xs.init) else false
    }

  def generatePalindromes(last: Int): Seq[(Int, String)] = {
    (1 to last) zip {
      for (
        x <- 1 to last if isEvenPalindrome(x.toString.toList)
      ) yield x.toString
    }
  }

  def main(args: Array[String]) = {
    val n = new Scanner(System.in).nextLine()
    println(n ++ n.reverse)
//    println(generatePalindromes(1000000000))
  }
}

object problem_B{
  def main(args: Array[String]): Unit = {
    val scanner = new java.util.Scanner(System.in)
    val line = scanner.nextLine()

    println(line + line.reverse)

  }
}


A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string consisting of six digits.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output "YES" if the given ticket is lucky, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, the sum of the first three digits is $$$2 + 1 + 3 = 6$$$ and the sum of the last three digits is $$$1 + 3 + 2 = 6$$$, they are equal so the answer is "YES".In the second test case, the sum of the first three digits is $$$9 + 7 + 3 = 19$$$ and the sum of the last three digits is $$$8 + 9 + 4 = 21$$$, they are not equal so the answer is "NO".In the third test case, the sum of the first three digits is $$$0 + 4 + 5 = 9$$$ and the sum of the last three digits is $$$2 + 0 + 7 = 9$$$, they are equal so the answer is "YES".

object Lucky {
  def main(args: Array[String]) = {
    val num = io.StdIn.readInt
    for (_ <- 1 to num) {
      println(goodNum(io.StdIn.readLine) match {
        case true => "YES"
        case false => "NO"
      })
    }
  }
  def goodNum(num: String) = {
    val firstPart: String = num.substring(0, 3)
    val secondPart: String = num.substring(3, 6)
    val sums: List[Int] = List(firstPart, secondPart).map { s =>
      s.foldLeft(0) { (total, char) =>
        total + Integer.parseInt(char.toString)
      }
    }
    sums(0) == sums(1)
  }
}


Dima worked all day and wrote down on a long paper strip his favorite number $$$n$$$ consisting of $$$l$$$ digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf.To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive integer without leading zeros. After that he will compute the sum of the two integers and write it down on a new strip.Dima wants the resulting integer to be as small as possible, because it increases the chances that the sum will fit it in the bookshelf. Help Dima decide what is the minimum sum he can obtain.

The first line contains a single integer $$$l$$$ ($$$2 \le l \le 100\,000$$$) — the length of the Dima's favorite number. The second line contains the positive integer $$$n$$$ initially written on the strip: the Dima's favorite number. The integer $$$n$$$ consists of exactly $$$l$$$ digits and it does not contain leading zeros. Dima guarantees, that there is at least one valid way to split the strip.

Print a single integer — the smallest number Dima can obtain.

NoteIn the first example Dima can split the number $$$1234567$$$ into integers $$$1234$$$ and $$$567$$$. Their sum is $$$1801$$$.In the second example Dima can split the number $$$101$$$ into integers $$$10$$$ and $$$1$$$. Their sum is $$$11$$$. Note that it is impossible to split the strip into "1" and "01" since the numbers can't start with zeros.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    val N = ni()
    val S = ns(N)

    var ms = Integer.MAX_VALUE
    val cand = ArrayBuffer[Int]()

    TO(1, N - 1) { i =>
      if (S(i) != '0') {
        val d = max(i, N - i) + 1
        if (ms > d) {
          ms = d
          cand.clear()
          cand += i
        } else if (ms == d) {
          cand += i
        }
      }
    }

    debug(s"ms:$ms")
    debug(cand.mkString(" "))

    val ans = (for {
      i <- cand
    } yield {
      val l = BigInt(S.take(i).mkString)
      val r = BigInt(S.drop(i).mkString)
      l + r
    }).min

    out.println(ans)
  }
}

import scala.io.StdIn._

object B_1181 extends App {
  val l = readInt()
  val A = readLine()

  def split(i: Int): BigInt = {
    if (i < 1 || i >= l) return BigInt("0")

    var (a, b) = A.splitAt(i)

    val aa = BigInt(a)
    val bb = BigInt(b)

//    println(a + " + " + b + " = " + (aa + bb))

    aa + bb
  }

  def getLeft(i: Int) = {
    var left = i
    while (left >= 0 && A(left) == '0') left -= 1
    left
  }

  def getRight(i: Int) = {
    var right = i
    while (right < l && A(right) == '0') right += 1
    right
  }

  val l1 = getLeft(l / 2)
  val l2 = getLeft(l / 2 - 1)
  val r1 = getRight(l / 2)
  val r2 = getRight(l / 2 + 1)

  val l3 = r1
  val l4 = r2
  val r3 = l1
  val r4 = l2

  val result = Set(l1, l2, l3, l4, r1, r2, r3, r4)
    .map { i =>
      split(i)
    }
    .filterNot(_ == 0)
    .min

  println(result)
}