After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.For a given sentence, the cipher is processed as:   Convert all letters of the sentence to lowercase.  Reverse each of the words of the sentence individually.  Remove all the spaces in the sentence. For example, when this cipher is applied to the sentenceKira is childish and he hates losingthe resulting string isariksihsidlihcdnaehsetahgnisolNow Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.

The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000.

Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.

30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note

12
iherehtolleh
5
HI
Ho
there
HeLLo
hello

Kira is childish and he hates losing
HI there HeLLo

NoteIn sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.

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

object _633C extends CodeForcesApp {
  override type Result = Seq[String]

  override def solve(read: InputReader) = {
    val n = read[Int]
    val text = read[String]
    val words = read[IndexedSeq[String]]
    val dict = words.map(_.toLowerCase.reverse).zipWithIndex
    type Ans = Option[List[Int]]
    val cache = scala.collection.mutable.Map.empty[Int, Ans]

    def solve(i: Int): Ans = cache.getOrElseUpdate(i, {
      i match {
        case `n` => Some(Nil)
        case _ =>
          val f = Function.unlift(isOkay(i))
          dict collectFirst f
      }
    })

    def isOkay(offset: Int): ((String, Int)) => Ans = {case (w, i) =>
      if(text.startsWith(w, offset)) {
        solve(offset + w.length).map(i :: _)
      } else {
        None
      }
    }

    solve(0).get.map(words)
  }

  override def format(result: Result) = result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

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

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

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

object _633C extends CodeForcesApp {
  override type Result = Seq[String]

  override def solve(read: InputReader) = {
    val (n, text, words) = read[(Int, String, IndexedSeq[String])]
    val cipher = words.map(_.toLowerCase.reverse).zipWithIndex

    type Ans = Option[List[Int]]

    lazy val solve: Int ==> Ans = Memo {
      case `n` => Some(Nil)
      case i =>
        val f = Function.unlift(isOkay(i))
        cipher collectFirst f
    }

    def isOkay(offset: Int): ((String, Int)) => Ans = {case (w, i) =>
      if(text.startsWith(w, offset)) solve(offset + w.length).map(i :: _) else None
    }

    solve(0).get.map(words)
  }

  case class Memo[I, K, O](f: I => O)(implicit encoder: I => K) extends (I => O) {
    import scala.collection.mutable.{Map => Dict}
    val cache = Dict.empty[K, O]
    override def apply(x: I) = cache getOrElseUpdate (x, f(x))
  }

  type ==>[I, O] = Memo[I, I, O]

  override def format(result: Result) = result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

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

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

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

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

object _633C extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val (n, text, words) = in[(Int, String, IndexedSeq[String])]
    val cipher = words.map(_.toLowerCase.reverse).zipWithIndex

    lazy val solve: Int => Option[List[Int]] = memoize {
      case `n` => Some(Nil)
      case i => cipher collectFirstDefined {
        case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)
      }
    }
    out ++= solve(0).get.map(words)
  }

  def memoize[A] = new {
    def apply[B](f: A => B): (A => B) = new mutable.HashMap[A, B]() {
      override def apply(key: A) = getOrElseUpdate(key, f(key))
    }
  }

  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Unit
  def main(args: Array[String]): Unit = {
    val (in, out) = (new InputReader(System.in), new OutputWriter(System.out))
    solve(in, out)
    in.close()
    out.close()
  }
}
/***********************************[Scala I/O]*********************************************/
import java.io._
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int, offset: Int = 0)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for (i <- 0 until n + offset) builder += (if (i < offset) null.asInstanceOf[A] else apply[A])
    builder.result()
  }

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

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}

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

class OutputWriter(out: PrintWriter) extends AutoCloseable {
  def this(out: OutputStream) = this(new PrintWriter(out))

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

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

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

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj

  override def close() = {
    out.flush()
    out.close()
  }
}

object _633C extends CodeForcesApp {
  override type Result = Seq[String]

  override def solve(read: InputReader) = {
    val (n, text, words) = read[(Int, String, IndexedSeq[String])]
    val cipher = words.map(_.toLowerCase.reverse).zipWithIndex

    type Ans = Option[List[Int]]

    lazy val solve: Int ==> Ans = Memo {
      case `n` => Some(Nil)
      case i =>
        cipher.view collect {
          case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)
        } collectFirst {
          case Some(x) => x
        }
    }

    solve(0).get.map(words)
  }

  case class Memo[I, K, O](f: I => O)(implicit encoder: I => K) extends (I => O) {
    import scala.collection.mutable.{Map => Dict}
    val cache = Dict.empty[K, O]
    override def apply(x: I) = cache getOrElseUpdate (x, f(x))
  }

  type ==>[I, O] = Memo[I, I, O]

  override def format(result: Result) = result mkString " "
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {_ <- 1 to n} builder += apply[A]
    builder.result()
  }

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

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

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

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

object _633C extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val (n, text, words) = in[(Int, String, IndexedSeq[String])]
    val cipher = words.map(_.toLowerCase.reverse).zipWithIndex

    lazy val solve: Int => Option[List[Int]] = memoize {
      case `n` => Some(Nil)
      case i => cipher collectFirstDefined {
        case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)
      }
    }
    out ++= solve(0).get.map(words)
  }

  def memoize[A] = new {
    def apply[B](f: A => B): (A => B) = new mutable.HashMap[A, B]() {
      override def apply(key: A) = getOrElseUpdate(key, f(key))
    }
  }

  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Unit
  def main(args: Array[String]): Unit = {
    solve(new InputReader(System.in), new OutputWriter(System.out))
  }
}
/***********************************[Scala I/O]*********************************************/
import java.io._
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int, offset: Int = 0)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for (i <- 0 until n + offset) builder += (if (i < offset) null.asInstanceOf[A] else apply[A])
    builder.result()
  }

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

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}

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

class OutputWriter(out: PrintWriter) extends AutoCloseable {
  def this(out: OutputStream) = this(new PrintWriter(out))

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

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

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

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj

  override def close() = {
    out.flush()
    out.close()
  }
}

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

object _633C extends CodeForcesApp {
  override def solve(in: InputReader, out: OutputWriter) = {
    val (n, text, words) = in[(Int, String, IndexedSeq[String])]
    val cipher = words.map(_.toLowerCase.reverse).zipWithIndex

    lazy val solve: Int => Option[List[Int]] = memoize {
      case `n` => Some(Nil)
      case i => cipher collectFirstDefined {
        case (w, j) if text.startsWith(w, i) => solve(i + w.length).map(j :: _)
      }
    }
    out ++= solve(0).get.map(words)
  }

  def memoize[A] = new {
    def apply[B](f: A => B): (A => B) = new mutable.HashMap[A, B]() {
      override def apply(key: A) = getOrElseUpdate(key, f(key))
    }
  }

  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def collectFirstDefined[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def solve(in: InputReader, out: OutputWriter): Unit
  def main(args: Array[String]): Unit = solve(new InputReader(System.in), new OutputWriter(System.out))
}
/***********************************[Scala I/O]*********************************************/
import java.io._
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int, offset: Int = 0)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for (i <- 0 until n + offset) builder += (if (i < offset) null.asInstanceOf[A] else apply[A])
    builder.result()
  }

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

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

class Parser[A](val apply: InputReader => A) {
  def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
}

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

class OutputWriter(out: PrintWriter) {
  def this(out: OutputStream) = this(new PrintWriter(out, true))

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

  def +=(obj: Any): this.type = {
    if (isNewLine) isNewLine = false else out.print(separator)
    out.print(obj)
    this
  }

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

  def ++=(obj: Traversable[_], ifEmpty: => Any = ""): this.type = {
    var c = 0
    obj foreach {i =>
      this += i
      c += 1
    }
    if (c == 0) this += ifEmpty else this
  }

  def append(obj: Any*): this.type = this ++= obj
}


Alice and Bob are playing chess on a huge chessboard with dimensions $$$n \times n$$$. Alice has a single piece left — a queen, located at $$$(a_x, a_y)$$$, while Bob has only the king standing at $$$(b_x, b_y)$$$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself — he needs to march his king to $$$(c_x, c_y)$$$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check. Remember that a king can move to any of the $$$8$$$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.

The first line contains a single integer $$$n$$$ ($$$3 \leq n \leq 1000$$$) — the dimensions of the chessboard. The second line contains two integers $$$a_x$$$ and $$$a_y$$$ ($$$1 \leq a_x, a_y \leq n$$$) — the coordinates of Alice's queen. The third line contains two integers $$$b_x$$$ and $$$b_y$$$ ($$$1 \leq b_x, b_y \leq n$$$) — the coordinates of Bob's king. The fourth line contains two integers $$$c_x$$$ and $$$c_y$$$ ($$$1 \leq c_x, c_y \leq n$$$) — the coordinates of the location that Bob wants to get to. It is guaranteed that Bob's king is currently not in check and the target location is not in check either. Furthermore, the king is not located on the same square as the queen (i.e. $$$a_x \neq b_x$$$ or $$$a_y \neq b_y$$$), and the target does coincide neither with the queen's position (i.e. $$$c_x \neq a_x$$$ or $$$c_y \neq a_y$$$) nor with the king's position (i.e. $$$c_x \neq b_x$$$ or $$$c_y \neq b_y$$$).

Print "YES" (without quotes) if Bob can get from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares $$$(2, 3)$$$ and $$$(3, 2)$$$. Note that the direct route through $$$(2, 2)$$$ goes through check.  In the second case, the queen watches the fourth rank, and the king has no means of crossing it.  In the third case, the queen watches the third file.

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 ax, ay, bx, by, cx, cy = ni()

    def region(x: Int, y: Int): Int = {
      (if (ax - x > 0) 1 else 0) + (if (ay - y > 0) 2 else 0)
    }

    def onLine(x: Int, y: Int): Boolean = {
      ax == x || ay == y || abs(ax - x) == abs(ay - y)
    }

    if (!onLine(cx, cy) && region(bx, by) == region(cx, cy)) {
      out.println("YES")
    } else {
      out.println("NO")
    }
  }

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

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

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

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

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

import scala.io.StdIn

object CoverPoints {
  def main(args: Array[String]): Unit ={

  val n = StdIn.readInt()
  val Axy = StdIn.readLine().split(" ").map(_.toInt)
  val Bxy = StdIn.readLine().split(" ").map(_.toInt)
  val Cxy = StdIn.readLine().split(" ").map(_.toInt)
  var check = true
  if(Axy(0) > Bxy(0) && Axy(1) > Bxy(1) ){
    if(Axy(0) > Cxy(0) && Axy(1) > Cxy(1) ){
      check = false
    }
  }

  if(Axy(0) < Bxy(0) && Axy(1) < Bxy(1) ){
    if(Axy(0) < Cxy(0) && Axy(1) < Cxy(1) ){
      check = false
    }
  }

  if(Axy(0) < Bxy(0) && Axy(1) > Bxy(1) ){
    if(Axy(0) < Cxy(0) && Axy(1) > Cxy(1) ){
      check = false
    }
  }

  if(Axy(0) > Bxy(0) && Axy(1) < Bxy(1) ){
    if(Axy(0) > Cxy(0) && Axy(1) < Cxy(1) ){
      check = false
    }
  }

  if(check)
    print("NO")
  else print("YES")
}
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val n = readInt
    val q1q2 = readLine.split(" ").map(_.toInt)
    val q1 = q1q2.head
    val q2 = q1q2.last
    val k1k2 = readLine.split(" ").map(_.toInt)
    val k1 = k1k2.head
    val k2 = k1k2.last
    val t1t2 = readLine.split(" ").map(_.toInt)
    val t1 = t1t2.head
    val t2 = t1t2.last
    if ( ( ( (k1 < q1) && (t1 < q1)  ) || ( (k1 > q1) && (t1 > q1) ) ) && ( ( (k2 < q2) && (t2 < q2) ) || ( (k2 > q2) && (t2 > q2) )) ) println("YES") else println("NO")
  }
}

object A extends App {

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

  val Array(n) = readInts(1)
  val Array(ax, ay) = readInts(2)
  val Array(bx, by) = readInts(2)
  val Array(cx, cy) = readInts(2)

  val minx = bx min cx
  val miny = by min cy
  val maxx = bx max cx
  val maxy = by max cy

  val ok = (ax < minx || ax > maxx) && (ay < miny || ay > maxy)

  println(if (ok) "YES" else "NO")

  Console.flush
}

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

  override def apply(io: IO): io.type = {
    val _, qx, qy, kx, ky, dx, dy = io.read[Int]
    val ans = (qx - kx).signum == (qx - dx).signum && (qy - ky).signum  == (qy - dy).signum
    io.write(if (ans) "YES" else "NO")
  }
}
/****************************[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()
}
/***********************************[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 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
      }
    }
  }
}


You are given a binary matrix $$$A$$$ of size $$$n \times n$$$. Let's denote an $$$x$$$-compression of the given matrix as a matrix $$$B$$$ of size $$$\frac{n}{x} \times \frac{n}{x}$$$ such that for every $$$i \in [1, n], j \in [1, n]$$$ the condition $$$A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$$$ is met.Obviously, $$$x$$$-compression is possible only if $$$x$$$ divides $$$n$$$, but this condition is not enough. For example, the following matrix of size $$$2 \times 2$$$ does not have any $$$2$$$-compression: $$$01$$$   $$$10$$$ For the given matrix $$$A$$$, find maximum $$$x$$$ such that an $$$x$$$-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.

The first line contains one number $$$n$$$ ($$$4 \le n \le 5200$$$) — the number of rows and columns in the matrix $$$A$$$. It is guaranteed that $$$n$$$ is divisible by $$$4$$$. Then the representation of matrix follows. Each of $$$n$$$ next lines contains $$$\frac{n}{4}$$$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $$$0$$$ to $$$9$$$ or as uppercase Latin letters from $$$A$$$ to $$$F$$$). Binary representation of each of these numbers denotes next $$$4$$$ elements of the matrix in the corresponding row. For example, if the number $$$B$$$ is given, then the corresponding elements are 1011, and if the number is $$$5$$$, then the corresponding elements are 0101. Elements are not separated by whitespaces.

Print one number: maximum $$$x$$$ such that an $$$x$$$-compression of the given matrix is possible.

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)

  val HEX = Array.ofDim[Int](128)
  REP(10) { i =>
    HEX('0' + i) = i
  }
  REP(6) { i =>
    HEX('A' + i) = i + 10
  }

  def solve(): Unit = {
    import java.util
    val N = ni()
    val cum = Array.ofDim[Int](N + 1, N + 1)
//    val M = Array.ofDim[Boolean](N, N)
    REP(N) { i =>
      val hex = ns()
      REP(N / 4) { j =>
        val bits = HEX(hex(j))
        REP(4) { k =>
          if ((bits & (1 << (3 - k))) > 0) cum(i + 1)(j * 4 + k + 1) = 1
        }
      }
    }
//        REP(N) { i =>
//          debug(M(i))
//        }

    val d = divisors(N)
//        debug(d)

//    val cum = Array.ofDim[Int](N + 1, N + 1)
//    REP(N) { i =>
//      REP(N) { j =>
//        if (M(i)(j)) cum(i + 1)(j + 1) = 1
//      }
//    }

    REP(N + 1) { i =>
      REP(N) { j =>
        cum(i)(j + 1) += cum(i)(j)
      }
    }

    REP(N + 1) { i =>
      REP(N) { j =>
        cum(j + 1)(i) += cum(j)(i)
      }
    }

//    REP(N + 1) { i =>
//      debug(cum(i))
//    }

    // [(r0, c0), (r1, c1))
    def count(r0: Int, c0: Int, r1: Int, c1: Int): Int = {
      cum(r1)(c1) + cum(r0)(c0) - cum(r1)(c0) - cum(r0)(c1)
    }

    def valid(x: Int): Boolean = {
      val sum = x * x

      REP(N / x) { i =>
        REP(N / x) { j =>
          val cnt = count(i * x, j * x, (i + 1) * x, (j + 1) * x)
          if (cnt != 0 && cnt != sum) return false
        }
      }

      true
    }

    var ans = 1
    REP_r(d.length - 1, 1) { i =>
      if (valid(d(i))) {
        ans = max(ans, d(i))
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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

  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)

  val HEX = Array.ofDim[Int](128)
  REP(10) { i =>
    HEX('0' + i) = i
  }
  REP(6) { i =>
    HEX('A' + i) = i + 10
  }

  def solve(): Unit = {
    val N = ni()
    val M = Array.ofDim[Boolean](N, N)
    REP(N) { i =>
      val hex = ns()
      REP(N / 4) { j =>
        val bits = HEX(hex(j))
        REP(4) { k =>
          M(i)(j * 4 + k) = (bits & (1 << (3 - k))) > 0
        }
      }
    }
//    REP(N) { i =>
//      debug(M(i))
//    }

    val d = divisors(N)
//    debug(d)

    // 縦、横の1の数
    val V, H = Array.ofDim[Int](N)
    REP(N) { i =>
      REP(N) { j =>
        if (M(i)(j)) {
          V(i) += 1
          H(j) += 1
        }
      }
    }

//    debug(V)
//    debug(H)

    def valid(x: Int) = {
      // 圧縮されるブロックのサイズ
      val sum = x * x

      var ok = true

      // 各列、行はxの倍数
      REP(N) { i =>
        ok &&= V(i) % x == 0 && H(i) % x == 0
      }

      // 圧縮予定の各列、各行を足したものはsumの倍数
      REP(N / x) { i =>
        var v, h = 0
        REP(x) { j =>
          v += V(i * x + j)
          h += H(i * x + j)
        }
        ok &&= v % sum == 0 && h % sum == 0
      }
      ok
    }

    var ans = 1
    REP_r(d.length - 1, 1) { i =>
      if (valid(d(i))) {
        ans = max(ans, d(i))
      }
    }

    out.println(ans)
  }

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

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

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

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

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

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

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


You are given a positive decimal number x.Your task is to convert it to the "simple exponential notation".Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.

The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.

Print the only line — the "simple exponential notation" of the given number x.

object Solution extends App {

  def normalize(str: String): String = {
    if (str.contains('.'))
      str.dropWhile(_ == '0').reverse.dropWhile(_ == '0').dropWhile(_ == '.').reverse
    else
      str.dropWhile(_ == '0')
  }

  val in = io.Source.stdin.getLines()
  val line = normalize(in.next())
  val point = line.indexOf('.')
  if (point != -1) {
    if (line.length == 1)
      println(0)
    else if (point == 0) {
      val e = line.indices.find(ch => line(ch) != '0' && line(ch) != '.').get
      val c = normalize(s"${line(e)}.${line.drop(e + 1)}")
      println(s"${c}E${-e}")
    } else {
      if (point == 1) {
        val c = normalize(s"${line.head}.${line.tail.filter(_ != '.')}")
        println(c)
      }
      else {
        println(s"${line.head}.${line.tail.filter(_ != '.')}E${point - 1}")
      }
    }
  } else {
    if (line.isEmpty)
      println(0)
    else if (line.length == 1)
      println(line)
    else {
      val e = line.length - 1
      val c = normalize(s"${line.head}.${line.tail}")
      println(s"${c}E$e")
    }

  }

}

import scala.io.StdIn._

object C extends App {
  var input = readLine()
  if (input == ".") input = "0.0"
  var Tmp = input.split("\\.")

  var left = Tmp(0)
  var right = if (Tmp.length == 2) Tmp(1) else ""
  left = left.dropWhile(_ == '0')
  right = right.reverse.dropWhile(_ == '0').reverse

  var E = "0"
  var L = ""
  var R = ""

  if (left.isEmpty && right.isEmpty) {
    println(0)
  } else if (left.isEmpty) {
    val rightFirstNonZero = right.dropWhile(_ == '0')
    L = rightFirstNonZero.head.toString
    R = rightFirstNonZero.tail
    E = "-" + (right.length - rightFirstNonZero.length + 1).toString
  } else {
    L = left.head.toString
    R = left.tail + right
    E = left.tail.length.toString
  }

  R = R.reverse.dropWhile(_ == '0').reverse

  val result = L + (if (R.isEmpty) "" else ".") + R + (if (E != "0") "E" + E else "")
  println(result)
}

object Solution extends App {

  def normalize(str: String): String = {
    if (str.contains('.'))
      str.dropWhile(_ == '0').reverse.dropWhile(_ == '0').dropWhile(_ == '.').reverse
    else
      str.dropWhile(_ == '0')
  }

  val in = io.Source.stdin.getLines()
  val line = normalize(in.next())
  val point = line.indexOf('.')
  if (point != -1) {
    if (line.length == 1)
      println(0)
    else if (point == 0) {
      val e = line.indices.find(ch => line(ch) != '0' && line(ch) != '.').get
      val c = normalize(s"${line(e)}.${line.drop(e + 1)}")
      println(s"${c}E${-e}")
    } else {
      if (point == 1) {
        val c = normalize(s"${line.head}.${line.tail.filter(_ != '.')}")
        println(c)
      }
      else {
        println("h")
        println(s"${line.head}.${line.tail.filter(_ != '.')}E${point - 1}")
      }
    }
  } else {
    if (line.isEmpty)
      println(0)
    else if (line.length == 1)
      println(line)
    else {
      val e = line.length - 1
      val c = normalize(s"${line.head}.${line.tail}")
      println(s"${c}E$e")
    }

  }

}


A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.Let's represent the length of the shortest by the number of edges path in the tree between vertices v and u as d(v, u).A parent of vertex v in the rooted tree with the root in vertex r (v ≠ r) is vertex pv, such that d(r, pv) + 1 = d(r, v) and d(pv, v) = 1. For example, on the picture the parent of vertex v = 5 is vertex p5 = 2.One day Polycarpus came across a rooted tree, consisting of n vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex pv to vertex v (1 < v ≤ n), he knows string sv that is written on it. All strings are written on the edges from top to bottom. For example, on the picture s7="ba". The characters in the strings are numbered starting from 0.    An example of Polycarpus's tree (corresponds to the example from the statement) Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (v, x) that means that the position is the x-th letter of the string sv (1 < v ≤ n, 0 ≤ x < |sv|), where |sv| is the length of string sv. For example, the highlighted letters are positions (2, 1) and (3, 1).Let's consider the pair of positions (v, x) and (u, y) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string z. String z consists of all letters on the way from (v, x) to (u, y), written in the order of this path. For example, in the picture the highlighted positions define string "bacaba".Polycarpus has a string t, he wants to know the number of pairs of positions that define string t. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!

The first line contains integer n (2 ≤ n ≤ 105) — the number of vertices of Polycarpus's tree. Next n - 1 lines contain the tree edges. The i-th of them contains number pi + 1 and string si + 1 (1 ≤ pi + 1 ≤ n; pi + 1 ≠ (i + 1)). String si + 1 is non-empty and consists of lowercase English letters. The last line contains string t. String t consists of lowercase English letters, its length is at least 2. It is guaranteed that the input contains at most 3·105 English letters.

Print a single integer — the required number. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
aba

7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
bacaba

NoteIn the first test case string "aba" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down.

import collection.mutable
import java.util.Scanner

object E {
  def main(args: Array[String]) {
    val in = new Scanner(System.in)
    val n = in.nextInt()
    val a = new Array[Vertex](n)
    for (i <- a.indices) {
      a(i) = new Vertex
    }
    for (i <- 1 until n) {
      val x = in.nextInt() - 1
      val s = in.next()
      a(x).ch add new Edge(s, a(i))
    }

    var s = in.next()
    val l = s length
    val go = new Array[Array[Int]](l + 1)
    val pref = new Array[Int](l + 1)
    for (i <- 0 until l + 1) {
      go(i) = new Array(26)
      if (i < l)
        go(i)(s(i) - 'a') = i + 1
      if (i < 2)
        pref(i) = 0
      else
        pref(i) = go(pref(i - 1))(s(i - 1) - 'a')
      for (j <- 0 until 26)
        if (go(i)(j) != i + 1)
          go(i)(j) = go(pref(i))(j)
    }

    val ans = a(0).dfs(go, l, 0)
    println(ans)
  }
}

class Vertex {
  val ch = new mutable.HashSet[Edge]

  def dfs(go: Array[Array[Int]], good: Int, state: Int): Int = {
    var res = 0
    for (e <- ch) {
      var cur = state
      for (c <- e.s) {
        cur = go(cur)(c - 'a')
        if (cur == good) {
          res += 1
        }
      }
      res += e.to.dfs(go, good, cur)
    }
    res
  }
}

class Edge(val s: String, val to: Vertex)

import io.Source
import java.io.PrintWriter

object CF291E {

  def solve(in: In, out: PrintWriter) {
//    val t0 = System.currentTimeMillis()
    val n = in().toInt
//    val n = 100000
    val par = Array.ofDim[Int](n)
    val strs = Array.ofDim[String](n)
    for (i <- 1 until n) {
      par(i) = in().toInt - 1
      strs(i) = in()
//      par(i) = i - 1
//      strs(i) = "a"
    }
    val str = in()
//    val str = "a" * 300000
    val p = Array.fill(str.size)(0)
    for (i <- 1 until str.length) {
      p(i) = p(i - 1)
      while (p(i) != 0 && str(i) != str(p(i))) {
        p(i) = p(p(i) - 1)
      }
      if (str(i) == str(p(i))) {
        p(i) += 1
      }
    }
    val q = Array.fill(n)(-1)
    q(0) = 0
    var ans = 0
    def eval(i: Int): Int = {
      if (q(i) == -1) {
        q(i) = eval(par(i))
        for (c <- strs(i)) {
          while (q(i) != 0 && c != str(q(i))) {
            q(i) = p(q(i) - 1)
          }
          if (c == str(q(i))) {
            q(i) += 1
          }
          if (q(i) == str.length) {
            ans += 1
            q(i) = p(q(i) - 1)
          }
        }
      }
      q(i)
    }
    (0 until n).foreach(eval)
    out.println(ans)
//    println(System.currentTimeMillis() - t0)
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "run", 128000000).run()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}


A programming coach has n students to teach. We know that n is divisible by 3. Let's assume that all students are numbered from 1 to n, inclusive.Before the university programming championship the coach wants to split all students into groups of three. For some pairs of students we know that they want to be on the same team. Besides, if the i-th student wants to be on the same team with the j-th one, then the j-th student wants to be on the same team with the i-th one. The coach wants the teams to show good results, so he wants the following condition to hold: if the i-th student wants to be on the same team with the j-th, then the i-th and the j-th students must be on the same team. Also, it is obvious that each student must be on exactly one team.Help the coach and divide the teams the way he wants.

The first line of the input contains integers n and m (3 ≤ n ≤ 48, . Then follow m lines, each contains a pair of integers ai, bi (1 ≤ ai < bi ≤ n) — the pair ai, bi means that students with numbers ai and bi want to be on the same team. It is guaranteed that n is divisible by 3. It is guaranteed that each pair ai, bi occurs in the input at most once.

If the required division into teams doesn't exist, print number -1. Otherwise, print  lines. In each line print three integers xi, yi, zi (1 ≤ xi, yi, zi ≤ n) — the i-th team.  If there are multiple answers, you are allowed to print any of them.

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

object B {

  def ma(n:Int, M:List[(Int,Int)], x:Int):Set[Int] = {
    var R:Set[Int] = Set(x)
    for(i <- 0 until n) {
      for(p <- M) {
        if(R.contains(p._1) || R.contains(p._2)){
          R = R union Set(p._1, p._2)
        }
      }
    }
    R
  }

  def pr(L:List[Int]) = {
    for(x<-L)print((x+1)+" ")
	println
  }

  def solve(n: Int, M: List[(Int, Int)]): List[List[Int]] = {
    var R: List[List[Int]] = List()
    val U = Array.fill(n)(false)
    var left:Set[Int] = Set()
    for (i <- 0 until n) {
      if (!U(i)) {
        val S = ma(n, M, i);
        if (S.size > 3) return null
        if (S.size == 1)left += i
        else {
          S.foreach( x=>U(x) = true)
          R = S.toList :: R
        }
      }
    }
    if(R.length>n/3)return null
    while(R.length < n/3)R=List()::R
    val it = left.iterator
    for(L<-R){
      var rl = L
      while(rl.length<3){
        rl = it.next ::rl
      }
      pr(rl)
    }
    R
  }
  def main(args: Array[String]) {
	  var scan = new Scanner(System.in)
	  val n = scan.nextInt;val m = scan.nextInt
	  val M = List.fill(m)((scan.nextInt-1, scan.nextInt-1))
	  val R = solve(n,M)
	  if (R==null)println(-1)
  }
}