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

import scala.collection.mutable

object A {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    var ans = 0
    for (i <- 0 until n) {
      for (j <- 0 until 2 * m by 2) {
        val fst = nextInt
        val snd = nextInt
        if (fst + snd >= 1) {
          ans += 1
        }
      }
    }
    out.println(ans)
    return 0
  }
}

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

  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).flatMap{_ =>
    in.next().split(' ').grouped(2).map{t =>
    t.head == "1" || t.last == "1"}}.count(_ == true)
  println(res)

}

object A595 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val in = Array.fill(n)(readInts(2*m))
    println(in.map{arr => arr.grouped(2).count{a => a(0) == 1 || a(1) == 1}}.sum)
  }

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

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

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

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

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

}

import scala.collection._

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, m) = readInts(2)
  val ss = Array.fill(n){ readInts(2 * m) }

  var cnt = 0

  for (s <- ss) {
    for (i <- 0 until m) {
      if (s(2 * i) + s(2 * i + 1) > 0) cnt += 1
    }
  }

  println(cnt)
}

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

object _595A extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val (n, m) = (nextInt(), nextInt())
    var ans = 0
    repeat(n * m) {
      val (a, b) = (nextInt(), nextInt())
      if (((a | b) & 1) == 1) {
        ans += 1
      }
    }
    ans
  }

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

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null) //TODO: In Java 8 reader.lines().iterator

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

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

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

object Main{
  def main (args: Array[String]){
    val Array(n, m) = io.StdIn.readLine.split(' ').map(_.toInt)
    var ans = 0
    for(i <- 1 to n){
      val al = io.StdIn.readLine.split(' ').map(_.toInt).toList
      ans += test(al)
    }
    println(ans)
  }

  def test(al: List[Int]): Int = al match{
    case Nil | (_ :: Nil) => 0
    case x :: y :: l1 =>
      if(x+y == 0) test(l1)
      else 1 + test(l1)
  }

}

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

object A_330 {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val line1 = new StringTokenizer(br.readLine())
    val n = line1.nextToken().toInt //floor
    val m = line1.nextToken().toInt //window

    var result = 0
    for (i <- 0 until n) {
      val line = new StringTokenizer(br.readLine(), " ")
      for (j <- 1 to m) {
        val w1 = line.nextToken().toInt
        val w2 = line.nextToken().toInt
        if (w1 == 1 || w2 == 1) {
          result += 1
        }
      }
    }
    //---------------------------- parameters reading end --------------------------------

    println(result)

  }
}

import scala.io.StdIn

object Main {
  private def readInts(): Array[Int] = StdIn.readLine().split(" ").map(_.toInt)

  def main(args: Array[String]) {
    val Array(n, m) = readInts()
    val sum = (0 until n).map(s => {
      val w = readInts()
      val e = w.zipWithIndex.filter(_._2 % 2 == 0).map(_._1)
      val o = w.zipWithIndex.filter(_._2 % 2 == 1).map(_._1)
      e.zip(o).count(s => s._1 == 1 || s._2 == 1)
    }).sum
    println(sum)
  }
}

object CF595A extends App{
  val Array(n,m) = readLine.split(" ").map(_.toInt)
  print((for(i <- 1 to n) yield (readLine.split(" ").sliding(2,2).count(a => a(0)=="1" || a(1) =="1"))).sum)
}

object Main extends App {
  val Array(n,m) = readLine().split(" ").map(_.toInt)
	var s = 0
	for(i <- 1 to n ) {
	  var r = readLine().split(" ").map(_.toInt)
		val t = for(j <- 0 until r.length by 2) yield { Math.max(r(j) , r(j+1)) }
		s += t.sum
	}
	println(s)
}


import java.io.FileInputStream
import scala.io.StdIn

object ProblemA extends App {
  // Console.withIn(new FileInputStream("inputs/test01.in")) {
    val n = StdIn.readLine().trim.toInt
    val p = -1 +: StdIn.readLine().trim.split("\\s+").map(_.toInt - 1)
    var a = List.empty[Int]
    var f = n - 1
    while (f != 0) {
      a ::= f
      f = p(f)
    }
    a ::= 0
    println(a.map(_ + 1).mkString(" "))
  // }
}

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

object Solution {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val pw = new PrintWriter(System.out)

    val n = sc.nextInt()

    val p = new Array[Int](n + 1)

    val g = new Array[util.ArrayList[Int]](n + 1)

    for (i <- 2 to n) {
      p.update(i, sc.nextInt())
      var gg = g.apply(p.apply(i))
      if (gg == null) {
        gg = new util.ArrayList[Int]
      }
      gg.add(i)
    }

    var result = Vector[Int]()

    var cur = n

    while (cur != 1) {
      result = cur +: result
      cur = p.apply(cur)
    }

    result = 1 +: result

    result.foreach(f => {
      pw.print(f + " ")
    })

    sc.close()
    pw.close()
  }
}


import scala.io.Source

object Solution extends App {

  def go(symbol: Int, number: Int, i: Int, j: Int, prevI: Int, prevJ: Int, data: Array[Array[Int]]): Boolean = {
    if (i < 0 || j < 0 || i >= data.length || j >= data.head.length)
      false
    else if (data(i)(j) == number) true
    else if (data(i)(j) == symbol) {
      data(i)(j) = number
      ((i + 1 != prevI || j != prevJ) && go(symbol, number, i + 1, j, i, j, data)) ||
      ((i != prevI || j + 1 != prevJ) && go(symbol, number, i, j + 1, i, j, data)) ||
      ((i - 1 != prevI || j != prevJ) && go(symbol, number, i - 1, j, i, j, data)) ||
      ((i != prevI || j - 1 != prevJ) && go(symbol, number, i, j - 1, i, j, data))
    } else
      false
  }

  def solveIndex(line: Int, column: Int, data: Array[Array[Int]]) = {
    val symbol = data(line)(column)
    val number =  - (line * data.head.length + column + 1)
    if (symbol < 0)
      false
    else {
      go(symbol: Int, number: Int, line, column, line, column, data)
    }
  }

  def solve(data: Array[Array[Int]]): Boolean = {
    data.indices.exists{ line =>
      data.head.indices.exists(column => solveIndex(line, column, data))
    }
  }

  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).map(_ => in.next().map(_.toInt).toArray).toArray
  if (solve(data))
    println("Yes")
  else
    println("No")
}

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

import scala.collection.mutable._

/**
  * @author Mehdi Maick
  */
object Main {

  def solve(in: InputReader): Unit = {
    val n = in.next.toInt
    val m = in.next.toInt
    var grid: Array[Array[Char]] = new Array[Array[Char]](n)
    (0 until n).foreach((i) => grid(i) = in.next.toCharArray)
    var hasCycle = false
    var visited: Array[Array[Boolean]] = null

    def fill(): Array[Array[Boolean]] = {
      var ret = new Array[Array[Boolean]](n)
      (0 until n).foreach((i) => ret(i) = new Array[Boolean](m))
      ret
    }

    var dx = Array(1, -1, 0, 0)
    var dy = Array(0, 0, 1, -1)

    def dfs(x: Int, y: Int, parentX: Int, parentY: Int, c: Char, cycleCount: Int): Boolean = {
      if (visited(x)(y)) {
        if(cycleCount >= 4){
          println("Yes")
          System.exit(0)
        }
        return false
      }
      visited(x)(y) = true
      var ans = false
      for (i <- 0 until 4) {
        val xx = x + dx(i)
        val yy = y + dy(i)
        if (xx >= 0 && yy >= 0 && xx < n && ((parentX, parentY) != (xx, yy)) && yy < m && grid(xx)(yy) == c) {
          ans |= dfs(xx, yy, x, y, c, cycleCount + 1)
        }
      }
      return ans
    }

    for (i <- 0 until n) {
      for (j <- 0 until m) {
        visited = fill
        hasCycle |= dfs(i, j, -1, -1, grid(i)(j), 0)
        if(hasCycle){

        }
      }
    }
    println(if (hasCycle) "Yes" else "No")
  }

  def main(args: Array[String]): Unit = {
    val in = new InputReader
    solve(in)
  }

  class InputReader() {
    var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var st: StringTokenizer = null

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

    def nextLine(): String = in.readLine
  }

}

import collection.mutable.Set
import collection.mutable.Queue

object Main extends App {
  val Array(n,m) = readLine.split(" ").map(_.toInt)

  val land = (1 to n) map { _ => readLine.trim }

  val dirs = List((0,1), (1,0), (-1,0), (0,-1))

  def eqColor(color: Char)(pos: (Int, Int)): List[(Int, Int)] = pos match {
    case (x, y) =>
      if(x >= 0 && x < n && y >= 0 && y < m && land(x)(y) == color) List(pos)
      else List()
  }

  def steps(node: (Int, Int)): List[(Int, Int)] = node match {
     case (x, y) =>
       val color = land(x)(y)
       dirs map { case (dx, dy) => (x+dx, y+dy) } flatMap eqColor(color)
  }

  val white = Set((for {
    i <- 0 to n-1
    j <- 0 to m-1
  } yield (i, j)): _*)
  val gray = Set[(Int, Int)]()
  val black = Set[(Int, Int)]()

  def dfs(prev: (Int, Int), node: (Int, Int)): Unit = {
    white.remove(node)
    gray.add(node)
    steps(node) foreach { k =>
        if(k != prev) {
          if(gray.contains(k)) {
            println("Yes")
            System.exit(0)
          }

          if(!black.contains(k)) dfs(node, k)
        }
    }
    gray.remove(node)
    black.add(node)
  }

  while(white.size > 0) {
    dfs((-1,-1), white.head)
  }

  println("No")
}

import scala.math._
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val n, m = readInt

  val game = Array.fill(n)(readString.toArray)
  val visited = Array.ofDim[Boolean](n, m)
  def hasCycle(x: Int, y: Int, lx: Int, ly: Int): Boolean = {
    if(x < 0 || x >= n || y < 0 || y >= m || game(x)(y) != game(lx)(ly))
      return false
    if(!visited(x)(y)) {
      visited(x)(y) = true

      if(x != lx+1 && hasCycle(x-1, y, x, y))
        return true
      if(x != lx-1 && hasCycle(x+1, y, x, y))
        return true
      if(y != ly+1 && hasCycle(x, y-1, x, y))
        return true
      if(y != ly-1 && hasCycle(x, y+1, x, y))
        return true
      false
    } else true
  }

  for(x <- 0 until n; y <- 0 until m; if !visited(x)(y)) {
    if(hasCycle(x, y, x, y)) {
      println("Yes")
      System.exit(0)
    }
  }
  println("No")

  /*
   * val names = Array.fill(readInt)(readString)
  val order = List[Char]()

  for(name <- names) {
    val c = name(0)
  }
   */
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

/**
 * @author pvasilyev
 * @since 04 Aug 2016
 */
object B510 extends App {

  // 0 - left
  // 1 - down
  // 2 - up
  // 3 - right
  def recursiveFoo(row: Int, col: Int, mainSymbol: Char, field: Array[Array[Char]],
                   mask: Array[Array[Boolean]], n: Int, m: Int, movement: Int): Boolean = {
    if (mask(row)(col)) {
      return true
    }
    mask(row)(col) = true
    var b = false
    if (row + 1 < n && field(row + 1)(col) == mainSymbol && movement != 2) {
      b |= recursiveFoo(row + 1, col, mainSymbol, field, mask, n, m, 1)
    }
    if (row - 1 >= 0 && field(row - 1)(col) == mainSymbol && movement != 1) {
      b |= recursiveFoo(row - 1, col, mainSymbol, field, mask, n, m, 2)
    }
    if (col + 1 < m && field(row)(col + 1) == mainSymbol && movement != 0) {
      b |= recursiveFoo(row, col + 1, mainSymbol, field, mask, n, m, 3)
    }
    if (col - 1 >= 0 && field(row)(col - 1) == mainSymbol && movement != 3) {
      b |= recursiveFoo(row, col - 1, mainSymbol, field, mask, n, m, 0)
    }
    return b
  }

  def runFoo(row: Int, col: Int, field: Array[Array[Char]], mask: Array[Array[Boolean]], n: Int, m: Int): Boolean = {
    recursiveFoo(row, col, field(row)(col), field, mask, n, m, 1)
  }

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val field: Array[Array[Char]] = Array.ofDim[Char](n, m)
    for (i <- 0 until n) {
      field(i) = scala.io.StdIn.readLine().toCharArray
    }
    if (foo(n, m, field)) {
      println("Yes")
    } else {
      println("No")
    }
  }

  def foo(n: Int, m: Int, field: Array[Array[Char]]): Boolean = {
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        val mask: Array[Array[Boolean]] = Array.ofDim[Boolean](n, m)
        if (runFoo(i, j, field, mask, n, m))
          return true
      }
    }

    false
  }

  solve()

}

import scala.math._
import scala.util.control.Breaks

object Problem extends App {
  import Scanner._

  val n, m = readInt

  val game = Array.fill(n)(readString.toArray)
  val path = Array.ofDim[Boolean](n, m)
  val visited = Array.ofDim[Boolean](n, m)
  def hasCycle(x: Int, y: Int, last: Char): Boolean = {
    if(x < 0 || x >= n || y < 0 || y >= n)
      return false
    val c = game(x)(y)
    if(last != c)
      return false
    if(!path(x)(y)) {
      if(!visited(x)(y)) {
        visited(x)(y) = true
        path(x)(y) = true

        if(hasCycle(x+1, y, c) || hasCycle(x-1, y, c) || hasCycle(x, y+1, c) || hasCycle(x, y-1, c))
          return true

        path(x)(y) = false
      }
      false
    } else true
  }

  for(x <- 0 until n; y <- 0 until m; if !visited(x)(y)) {
    if(hasCycle(x, y, game(x)(y))) {
      println("Yes")
      System.exit(0)
    }
  }
  println("No")

  /*
   * val names = Array.fill(readInt)(readString)
  val order = List[Char]()

  for(name <- names) {
    val c = name(0)
  }
   */
}

case class Memo[A, B](f: A => B, size: Int = 10) extends (A => B) {
  private val cache = new scala.collection.mutable.HashMap[A, B] {
    override def initialSize = size
  }
  def apply(x: A) = cache getOrElseUpdate (x, f(x))
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

/**
 * @author pvasilyev
 * @since 04 Aug 2016
 */
object B510 extends App {

  // 0 - left
  // 1 - down
  // 2 - up
  // 3 - right
  def recursiveFoo(row: Int, col: Int, mainSymbol: Char, field: Array[Array[Char]],
                   mask: Array[Array[Boolean]], n: Int, m: Int, movement: Int): Boolean = {
    if (mask(row)(col)) {
      return true
    }
    mask(row)(col) = true
    if (row + 1 < n && field(row + 1)(col) == mainSymbol && movement != 2) {
      recursiveFoo(row + 1, col, mainSymbol, field, mask, n, m, 1)
    } else if (row - 1 >= 0 && field(row - 1)(col) == mainSymbol && movement != 1) {
      recursiveFoo(row - 1, col, mainSymbol, field, mask, n, m, 2)
    } else if (col + 1 < m && field(row)(col + 1) == mainSymbol && movement != 0) {
      recursiveFoo(row, col + 1, mainSymbol, field, mask, n, m, 3)
    } else if (col - 1 >= 0 && field(row)(col - 1) == mainSymbol && movement != 3) {
      recursiveFoo(row, col - 1, mainSymbol, field, mask, n, m, 0)
    } else {
      return false
    }
  }

  def runFoo(row: Int, col: Int, field: Array[Array[Char]], mask: Array[Array[Boolean]], n: Int, m: Int): Boolean = {
    recursiveFoo(row, col, field(row)(col), field, mask, n, m, 1)
  }

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val field: Array[Array[Char]] = Array.ofDim[Char](n, m)
    for (i <- 0 until n) {
      field(i) = scala.io.StdIn.readLine().toCharArray
    }
    if (foo(n, m, field)) {
      println("Yes")
    } else {
      println("No")
    }
  }

  def foo(n: Int, m: Int, field: Array[Array[Char]]): Boolean = {
    for (i <- 0 until n) {
      for (j <- 0 until m) {
        val mask: Array[Array[Boolean]] = Array.ofDim[Boolean](n, m)
        if (runFoo(i, j, field, mask, n, m))
          return true
      }
    }

    false
  }

  solve()

}


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

    val e = a(0)
    val a1 = a.drop(1).map(_.zip(e))
    val a2 = a1.map(_.takeWhile(t => t._1 == t._2).size)
    val r = a2.min

    println(r)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val str = in.next()
  val r = (2 to n).foldLeft(str.toSeq) {
    case (s, _) => s.zip(in.next()).takeWhile(i => i._1 == i._2).map(_._1)
  }
  println(r.length)
}

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

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

  val N = sc.nextInt
  sc.nextLine

  val res = List.fill(N)(sc.nextLine.toList).transpose.takeWhile(_.distinct.size == 1).size

  out.println(res)
  out.close
}

import java.io._

object Solution {
  def main(args: Array[String]) {
    val in = new BufferedReader(new InputStreamReader(System.in))
    val n = in.readLine().toInt
    def commonPrefix(s: String, t: String) = {
      var i = 0
      while(i < s.length && i < t.length && s(i) == t(i)) i = i + 1
      s.substring(0, i)
    }
    val x = (for(i <- 1 to n) yield in.readLine).reduceLeft(commonPrefix(_, _))
    println(x.length)
  }
}


// codeforces 190B

object Okrushenie extends App {
  val t1 = (Console.readLine.split(" ")) map (_.toInt)
  val t2 = (Console.readLine.split(" ")) map (_.toInt)
  val (x0, y0, r0) = (t1(0), t1(1), t1(2))
  val (x1, y1, r1) = (t2(0), t2(1), t2(2))
  val dx = (x0.toDouble - x1.toDouble)
  val dy = (y0.toDouble - y1.toDouble)
  val d = Math.sqrt(dx*dx + dy*dy)
  if (d > r0+r1) println((d-r0-r1)/2)
  else {
    val rmx = Math.max(r0,r1)
    val rmn = Math.min(r0,r1)
    if (rmn + d >= rmx) println(0)
    else println((rmx - d - rmn) / 2)
  }
}

object Solution {
  class Point(xin: Long, yin: Long) {
    val x = xin;
    val y = yin;
  }

  def sqr(x: Long): Long = x*x

  def sqrDist(p1: Point, p2: Point): Long = {
    return sqr(p1.x - p2.x) + sqr(p1.y - p2.y)
  }

  class Circle(centerin: Point, radiusin: Long) {
    val center = centerin;
    val radius = radiusin;

    def contains(p: Point): Boolean = sqrDist(p, center) <= sqr(radius)

    def intersects(other: Circle): Boolean = {
      sqr(radius) + 2*radius*other.radius + sqr(other.radius) >= sqrDist(center, other.center)
    }

    def contains(other: Circle): Boolean = {
      val d = math.sqrt(sqrDist(center, other.center))
      d + other.radius <= radius
    }
  }

  def readCircle(): Circle = {
    val tokens = readLine().split(" ").map(_.toInt)
    new Circle(new Point(tokens(0), tokens(1)), tokens(2))
  }

  def solve(c1: Circle, c2: Circle): Double = {
    val d = math.sqrt(sqrDist(c1.center, c2.center))
    if (c1 contains c2) {
      c1.radius - (d + c2.radius)
    } else if (c2 contains c1) {
      c2.radius - (d + c1.radius)
    } else if (c1 intersects c2) {
      0
    } else {
      d - (c1.radius + c2.radius)
    }
  }

  def main(args: Array[String]) {
    printf("%.12f\n", solve(readCircle(), readCircle()) / 2)
  }
}

object Solution {
  class Point(xin: Long, yin: Long) {
    val x = xin;
    val y = yin;
  }

  def sqr(x: Long): Long = x*x

  def sqrDist(p1: Point, p2: Point): Long = {
    return sqr(p1.x - p2.x) + sqr(p1.y - p2.y)
  }

  class Circle(centerin: Point, radiusin: Long) {
    val center = centerin;
    val radius = radiusin;

    def contains(p: Point): Boolean = sqrDist(p, center) <= sqr(radius)

    def intersects(other: Circle): Boolean = {
      sqr(radius) + 2*radius*other.radius + sqr(other.radius) >= sqrDist(center, other.center)
    }

    def contains(other: Circle): Boolean = {
      val d = math.sqrt(sqrDist(center, other.center))
      d + other.radius <= radius
    }
  }

  def readCircle(): Circle = {
    val tokens = readLine().split(" ").map(_.toInt)
    new Circle(new Point(tokens(0), tokens(1)), tokens(2))
  }

  def solve(c1: Circle, c2: Circle): Double = {
    val d = math.sqrt(sqrDist(c1.center, c2.center))
    if (c1 contains c2) {
      c1.radius - (d + c2.radius)
    } else if (c2 contains c1) {
      c2.radius - (d + c1.radius)
    } else if (c1 intersects c2) {
      c1.radius + c2.radius - d
    } else {
      d - (c1.radius + c2.radius)
    }
  }

  def main(args: Array[String]) {
    printf("%.12f\n", solve(readCircle(), readCircle()) / 2)
  }
}


import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val s = readString()
        if (n > 2) {
            writer.println("NO")
        } else if (n == 1) {
            writer.println("YES")
        } else {
            if (s(0) == s(1)) {
                writer.println("NO")
            } else {
                writer.println("YES")
            }
        }
        def check(kk: Long, fi: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long, fi:Long): Long = {
            if (en - st <= 1L) {
                if (check(st, fi))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid, fi))
                return bs(st, mid, fi)
            else
                return bs(mid, en, fi)
        }
    }
    writer.flush()
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val string = readLine()
    val answer = size match {
      case 1 => "YES"
      case 2 => if (string(0) != string(1)) "YES" else "NO"
      case _ => "NO"
    }
    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

object _1632AScala {
  import scala.io.StdIn.{readInt, readLine}
  def main(args: Array[String]): Unit = {
    var t = readInt
    while(t > 0){
      t -= 1
      val n = readInt
      val ch = readLine.toCharArray
      if(n == 1)println("YES")
      else if(n >= 3) println("NO")
      else{
        if(ch(0) != ch(1))println("YES")
        else println("NO");
      }
    }
  }
}

import scala.collection.mutable.ArrayBuffer
import scala.io.Source

object Main extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val n = input.next().toInt
  val res = new ArrayBuffer[String](n)
  for (i <- 0 until n) {
    val ls = input.next().toInt
    val s = input.next()
    if (ls == 1 || "01".equals(s) || "10".equals(s)) res.append("YES")
    else res.append("NO")
  }
  res.foreach(println)
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val size = readInt()
    val string = readLine()
    val answer = if (size < 3) "YES" else "NO"
    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


object A extends App {

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    def isSorted: Boolean = (0 until (n - 1)).forall(i => an(i) <= an(i + 1))

    @annotation.tailrec
    def go(i: Int): Int =
      if (isSorted) i
      else {
        ((i % 2) until (n - 1, 2)).foreach {
          case i if an(i) > an(i + 1) =>
            val ai = an(i)
            an(i) = an(i + 1)
            an(i + 1) = ai
          case _                      =>
        }
        go(i + 1)
      }

    println(go(0))
  }

}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val count = {
      @annotation.tailrec
      def go(i: Int): Int =
        if (an.isSorted) i
        else {
          ((i % 2) until (n - 1, 2)).foreach {
            case i if an(i) > an(i + 1) => an.swap(i, i + 1)
            case _                      =>
          }
          go(i + 1)
        }
      go(0)
    }

    println(count)
  }

  implicit final class ArrayOps[T](private val xs: Array[T]) extends AnyVal {
    def swap(i: Int, j: Int): Unit = {
      val xi = xs(i)
      xs(i) = xs(j)
      xs(j) = xi
    }

    def isSorted(implicit ord: Ordering[T]): Boolean =
      (0 until (xs.length - 1)).forall(i => ord.lteq(xs(i), xs(i + 1)))
  }

}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()
    def readArrayInt(n: Int = 0): Array[Int] = {
        if (n == 0)
            return reader.readLine().split(" ").map(_.toInt)

        val a = new Array[Int](n)
        for (i <- 0 until n) {
            a(i) = readInt()
        }
        a
    }

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def solve(t: Int = 0): Unit = {
        val n = readInt()
        val a = readArrayInt(n)

        var c = 0
        while ({
            var i = 0
            while (i < n && a(i) == i + 1) i +=1
            i != n
        }) {
            c += 1
            if (c % 2 > 0) {
                for (i <- 0 until n - 1 by 2 if a(i) > a(i + 1)) {
                    val k = a(i)
                    a(i) = a(i + 1)
                    a(i + 1) = k
                }
            } else {
                for (i <- 1 until n - 1 by 2 if a(i) > a(i + 1)) {
                    var k = a(i)
                    a(i) = a(i + 1)
                    a(i + 1) = k
                }
            }
        }

        writer.println(c)
    }

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

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

object A extends App {

  def count: Seq[Int] => Int = _.zipWithIndex.sorted.zipWithIndex.foldLeft(0) {
    case (c, ((_, i), j)) if i == j => c
    case (c, ((_, i), j))           => c max (math.abs(i - j) + (i + 1) % 2)
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    println(count(an))
  }

}


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

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
}


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

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


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

  }

}


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