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

  override def apply(implicit io: IO): io.type = {
    repeat {
      val a, b = io.read[Long]
      io.writeLine(if (gcd(a, b) == 1L) "Finite" else "Infinite")
    }
  }

  @tailrec
  final def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)
}
/****************************[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(implicit io: IO): io.type
  def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import java.util

import scala.collection.mutable
import scala.io.StdIn._

object Main extends App {

  def nod(a: Int, b: Int) = {
    var x = a
    var y = b
    while (x != 0 && y != 0) {
      if (x > y)
        x = x % y
      else
        y = y % x
    }
    x+y
  }

  val n = readLine().toInt

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    if (a % 2 == 0) {
      if ( nod(a,b) > 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    } else {
      //if (b % a == 0 && a != 1) {
      if ( nod(a,b) > 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    }

  }

/*

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    var st = "w"
    for (j <- 1 to (a max b)*12) {
      if ( (j >= a) && (j-a >= 0) && (st.charAt(j-a) == 'w') ) {
        st += 'w'
      } else if ( (j >= b) && (j-b >= 0) && (st.charAt(j-b) == 'w') ) {
        st += 'w'
      } else {
        st += 'b'
      }

    }

    print(a,b,st)
    if (st.charAt(st.length-1) == 'b' || st.charAt(st.length-2) == 'b')
      println("Infinite")
    else
      println("Finite")
  }
*/

}

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._

  def gcd(a: Int, b: Int): Int = {
    if (b == 0) a
    else gcd(b, a % b)
  }
}

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

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

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val a, b = ni()
      if (gcd(a, b) == 1) {
        out.println("Finite")
      } else {
        out.println("Infinite")
      }
    }
  }
}

import java.util

import scala.collection.mutable
import scala.io.StdIn._

object Main extends App {

  def nod(a: Int, b: Int) = {
    var x = a
    var y = b
    while (x != 0 && y != 0) {
      if (x > y)
        x = x % y
      else
        y = y % x
    }
    x+y
  }

  val n = readLine().toInt

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    if (a % 2 == 0) {
      if ( nod(a,b) > 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    } else {
      if (b % a == 0 && a != 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    }

  }

/*

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    var st = "w"
    for (j <- 1 to (a max b)*12) {
      if ( (j >= a) && (j-a >= 0) && (st.charAt(j-a) == 'w') ) {
        st += 'w'
      } else if ( (j >= b) && (j-b >= 0) && (st.charAt(j-b) == 'w') ) {
        st += 'w'
      } else {
        st += 'b'
      }

    }

    print(a,b,st)
    if (st.charAt(st.length-1) == 'b' || st.charAt(st.length-2) == 'b')
      println("Infinite")
    else
      println("Finite")
  }
*/

}


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

  val f = readInt()

  (0 until f).foreach { _ =>
    val t = readLong()

    val res = ((t max 6) + 1) / 2 * 5

    println(res)
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]) = {
    def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }

    rep(readInt) {
      var in = BigDecimal(readLine)
      in = in.max(6)

      //so can get only 2,4,8,10,12
      //and for < 6 we want 6 slices either way
      in += (if (in % 2 != 0) 1 else 0)
      println((in * 2.5).toBigInt)
    }
  }
}

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

object Solution {
  def solve(input: Long): Long = {
    // a b c
    // 2*(a*3 + b*4 + c*5) >= input
    // 5*(a*3 + b*4 + c*5) = min
    // so you want to closest amount to input
    // actually we want to get exactly input or input * 2 most likely?

    //    val covered: Array[Boolean] = Array.fill(30000)(false)
    //    (0 to 1000).foreach { a =>
    //      (0 to 1000).foreach { b =>
    //        (0 to 1000).foreach { c =>
    //          covered(a*6+b*8+c*10) = true
    //        }
    //      }
    //    }
    //
    //    (0 to 3000).foreach { i =>
    //      if (!covered(i*2)) {
    //        println(s"not covered ${i*2}")
    //      }
    //    }
    //
    //    input

    // not covered 2
    // not covered 4
    val toCover = if (input < 6) 6 else if (input % 2 == 0) input else (input + 1)
    (toCover / 2) * 5
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    output.println(solve(input.nextLong()))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

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

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

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

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0 && rs > 0) {
                if (n <= 2)
                    rs = rs - 25 + 30
                else if (n <= 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 8)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            } else if (n > 8) rs = 25
            else if (n > 6) rs = 20
            else if (n > 0) rs = 15

            println(rs)
            t -= 1
        }

    }

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

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readLong()

    val ans = ((n max 6) + 1) / 2 * 5

    println(ans)
  }
}

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

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

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

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

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0) {
                if (n <= 2)
                    rs = rs - 25 + 30
                else if (n <= 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 8)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            }

            println(rs)
            t -= 1
        }

    }

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

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

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

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

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

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0) {
                if (n == 2)
                    rs = rs - 25 + 30
                else if (n == 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 8)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            }

            println(rs)
            t -= 1
        }

    }

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

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

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

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

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

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0) {
                if (n == 2)
                    rs = rs - 25 + 30
                else if (n == 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 6)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            }

            println(rs)
            t -= 1
        }

    }

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

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readLong()

    val ans = (n max 6) / 2 * 5

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readLong()

    val ans = ((n + 9) / 10 * 25) min ((n + 7) / 8 * 20) min ((n + 5) / 6 * 15)

    println(ans)
  }
}


import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)

  def getOneStepPrice(step: Long, ingStep:IngStep): Long = {
    if (step <= ingStep.lastStep)
      0L // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use is there is a reminder on this step
    } else {
      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {
    ingSteps.foldRight(0L)((ingStep, t) => {
      t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices
      .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))
      .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var startStep = 0L //Math.max(1, ingSteps.head.lastStep)

    val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over

    var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.round(p / fullPrice) else ingSteps.last.lastStep

    var stop = false
    var cookies = Math.max(startStep - 1, 0)

    while (!stop) {
//      println("Start " + startStep + " end " + endStep)
      val mid = startStep + Math.round((endStep - startStep) / 2)

      val stepPrice = getStepPrice(mid, ingSteps)
      cookies = mid

      if (stepPrice < p) {
        startStep = mid // Moving higher
      } else {
        endStep = mid // Moving lower
      }

      if (startStep == endStep) {
        stop = true
      } else if (startStep + 1 == endStep) {
        stop = true
        cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep
      }
    }
//114, 117
//    var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait
//    var cookies = Math.max(step - 1, 0)
//    var pRemainder = p

//
//    while(!stop) {
//      val stepPrice = getStepPrice(step, ingSteps)
//
//      if (stepPrice <= pRemainder) {
//        cookies += 1
//        step += 1
//      } else {
//        stop = true
//      }
//    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)

  def getOneStepPrice(step: Int, ingStep:IngStep): Int = {
    if (step <= ingStep.lastStep)
      0 // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use remainder only if we are on this step
    } else {

      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {
    ingSteps.foldRight(0)((ingStep, t) => {
     t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var step = 1
    var cookies = 0
    var pRemainder = p
    var stop = false

    while(!stop) {
      val stepPrice = getStepPrice(step, ingSteps)

//      if (stepPrice > 0) {
//          println("Step " + step + " cookies " + cookies + " remainder " + pRemainder + " price " + stepPrice)
//      }

      if (stepPrice <= pRemainder) {
        cookies += 1
        step += 1
      } else {
        stop = true
      }
    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)

  def getOneStepPrice(step: Int, ingStep:IngStep): Int = {
    if (step <= ingStep.lastStep)
      0 // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use remainder only if we are on this step
    } else {

      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {
    ingSteps.foldRight(0)((ingStep, t) => {
     t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait
    var cookies = Math.max(step - 1, 0)
    var pRemainder = p
    var stop = false

    while(!stop) {
      val stepPrice = getStepPrice(step, ingSteps)

      if (stepPrice <= pRemainder) {
        cookies += 1
        step += 1
      } else {
        stop = true
      }
    }

    print(cookies)

  }
}

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

object _670D1 extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, k = io[Int]
    val perCookie, has = io[Vector, Long](n)

    val upperBound = 10 + ((has.sum + k)/perCookie.sum)

    def canBake(c: Long) = (c <= upperBound) && {  //can bake c cookies?
      val missing = perCookie.indices.foldLeft(0L) {
        case (needed, i) => needed + (((perCookie(i)*c) - has(i)) max 0)
      }
      missing <= k
    }

    io += (bitBinSearch(canBake) getOrElse 0L) max 0L
  }

  def bitBinSearch(f: Long => Boolean): Option[Long] = {
    var p = 0L
    var n = Long.MinValue
    var t = n >>> 1
    while (t > 0) {
      if (f(p|t)) p |= t
      if (f(n|t)) n |= t
      t >>= 1
    }
    Seq(p, n) find f
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

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

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

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

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  var Array(n, k) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt)
  var b = in.next().split(' ').map(_.toInt)
  var can = true
  var answer = 0
  while (can) {
    var minus = 0
    (0 until n).foreach { i =>
      val value = b(i) - a(i)
      if (value < 0) {
        minus -= value
        b(i) = 0
      } else {
        b(i) = value
      }
    }
    if (k >= minus) {
      k -= minus
      answer += 1
      can = true
    } else {
      can = false
    }
  }
  println(answer)

}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)

    val a = readInts()
    val b = readInts()

    val minSteps = a.indices.map(i => (i, Math.floorDiv(b(i), a(i)))).sortBy(_._2) // we now have i, steps sorted from lowest

    var pRemainder = numberPowder(1)
    var cookies = if (minSteps.isEmpty) 0 else minSteps.head._2 // Initialise from minimum steps

    // println("Minimum: " + cookies)

    minSteps.indices.foreach(i => {
      val minStep = minSteps(i)
      val aI = a(minStep._1)
      val bI = b(minStep._1)
      val addOn = Math.floorMod(bI, aI)

//      println("i: " + minStep._1 +  " value " + aI + " steps " + minStep._2 + " addon " + addOn)

      val nextStep = if (i < minSteps.size - 1) minSteps(i + 1)._2 else -1

      if (pRemainder > 0) {
        val extraPowder = aI - addOn
        val extraStep = if ((pRemainder - extraPowder) > 0 && extraPowder > 0) {
          pRemainder -= extraPowder

          if (nextStep > minStep._2) {
            cookies += 1 // enough for 1 more at least
          }
          1
        } else {
          0
        }

        if (i < minSteps.size - 1 && nextStep > 0) {
          val eatHere = nextStep - (minStep._2 + extraStep) // this is how much more room we have to use powder
          // for this ingredient

          if (eatHere > 0) {
            val moreTooCook = Math.floorDiv(pRemainder, aI)
            pRemainder -= moreTooCook // eat as much as we can
            cookies += moreTooCook
          }
        }
      }
    })

    if (pRemainder >= a.sum) {
      cookies += Math.floorMod(pRemainder, a.sum) // finish the remainder
    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)

  def getOneStepPrice(step: Int, ingStep:IngStep): Int = {
    if (step <= ingStep.lastStep)
      0 // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use remainder only if we are on this step
    } else {

      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {
    ingSteps.foldRight(0)((ingStep, t) => {
     t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var step = ingSteps.head.lastStep - 1 // no need to wait
    var cookies = Math.max(step - 1, 0)
    var pRemainder = p
    var stop = false

    while(!stop) {
      val stepPrice = getStepPrice(step, ingSteps)

      if (stepPrice <= pRemainder) {
        cookies += 1
        step += 1
      } else {
        stop = true
      }
    }

    print(cookies)

  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  var Array(n, k) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt)
  var b = in.next().split(' ').map(_.toInt)
  var can = true
  var answer = 0
  while (can) {
    b = b.zip(a).map(i => i._1 - i._2)
    if (k > - b.filter(_ < 0).sum) {
      k -= b.filter(_ < 0).sum
      answer += 1
      b = b.map(i => Math.max(0, i))
      can = true
    } else {
      can = false
    }
  }
  println(answer)

}


import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try
import scala.util.hashing.MurmurHash3

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) { linksBuilder(i) += i }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map { ab =>
      val arr = ab.result()
      java.util.Arrays.sort(arr)
      arr
    }
    val linksXor: Array[Int] = links.map(_.foldLeft(0)(_ ^ _.hashCode()))
    var heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if links(i) sameElements links(j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    var ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) == INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try
import scala.util.hashing.MurmurHash3

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) {
      linksBuilder(i) += i
    }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map(_.result)
    links.foreach(java.util.Arrays.sort)
    val linksXor: Array[Int] = links.map(_.reduceLeft(_ ^ _.hashCode()))
    val heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if links(i) sameElements links(j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    val ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) == INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.Builder
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0
Try {
  var links = (0 until n).map(_ :: Nil).toArray

  (1 to m).foreach { i =>
    read()
    a = int() - 1
    b = int() - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  links = links.map(_.sorted)
  val ma = mutable.Map.empty[List[Int], List[Int]]
  for {
    (ls, i) <- links.zipWithIndex
  } {
    val list = ma.getOrElse(ls, Nil)
    ma.update(ls, i :: list)
  }

  val heads = ma.values.map(_.head).toSet

  val mb = for {
    (ls, group) <- ma
  } yield group.head -> ls.filter(heads.contains).filterNot(_ == group.head)

  var ans = Array.fill(n)(INF)

  val start = mb.find(_._2.size == 1).get._1

  val stack = new mutable.Stack[(Int, Int)]()
  stack.push((start, -1))
  while (stack.nonEmpty) {
    val (cur, prev) = stack.pop()
    val prevValue = if (prev == -1) 1000000 else ans(prev)
    ans(cur) = prevValue + 1
    mb(cur).filter(_ != prev).foreach(next => stack.push((next, cur)))
  }

  for (head <- heads) ma(links(head)).foreach { i =>
    ans(i) = ans(head)
  }
  assert(ans.forall(_ != INF))
  println("YES")
  println(ans.mkString(" "))
}.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) { linksBuilder(i) += i }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map { ab =>
      val arr = ab.result()
      java.util.Arrays.sort(arr)
      arr
    }
    val linksXor: Array[Int] = links.map(_.foldLeft(0)(_ ^ _.hashCode()))
    var heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if links(i) sameElements links(j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    var ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) != INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.Builder
import scala.util.Try

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0
Try {
  var links = (0 until n).map(_ :: Nil).toArray

  (1 to m).foreach { i =>
    read()
    a = int() - 1
    b = int() - 1
    links(a) = b :: links(a)
    links(b) = a :: links(b)
  }

  links = links.map(_.sorted)
  val ma = mutable.Map.empty[List[Int], List[Int]]
  for {
    (ls, i) <- links.zipWithIndex
  } {
    val list = ma.getOrElse(ls, Nil)
    ma.update(ls, i :: list)
  }

  val heads = ma.values.map(_.head).toSet

  val mb = for {
    (ls, group) <- ma
  } yield group.head -> ls.filter(heads.contains).filterNot(_ == group.head)

  var ans = Array.fill(n)(INF)

  val start = mb.find(_._2.size == 1).map(_._1).getOrElse(heads.head)

  val stack = new mutable.Stack[(Int, Int)]()
  stack.push((start, -1))
  while (stack.nonEmpty) {
    val (cur, prev) = stack.pop()
    val prevValue = if (prev == -1) 1000000 else ans(prev)
    ans(cur) = prevValue + 1
    mb(cur).filter(_ != prev).foreach(next => stack.push((next, cur)))
  }

  for (head <- heads) ma(links(head)).foreach { i =>
    ans(i) = ans(head)
  }
  assert(ans.forall(_ != INF))
  println("YES")
  println(ans.mkString(" "))
}.getOrElse(println("NO"))

}

import java.util.StringTokenizer

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Try
import scala.util.hashing.MurmurHash3

object D extends App {
  val INF = 1 << 30
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt

  read()
  val n = int()
  val m = int()

  var a = 0
  var b = 0

  Try {
    val linksBuilder: Array[mutable.ArrayBuilder[Int]] = Array.fill(n)(mutable.ArrayBuilder.make[Int])
    for (i <- 0 until n) {
      linksBuilder(i) += i
    }
    (1 to m).foreach { i =>
      read()
      a = int() - 1
      b = int() - 1
      linksBuilder(a) += b
      linksBuilder(b) += a
    }

    val links: Array[Array[Int]] = linksBuilder.map(_.result)
    val linksXor: Array[Int] = links.map(_.reduceLeft(_ ^ _.hashCode()))
    val heads: Array[Int] = (0 until n).toArray
    def isHead(i: Int): Boolean = heads(i) == i

    val sorted: Array[Boolean] = Array.fill(n)(false)
    def ensureSorted(i: Int): Unit = if (!sorted(i)) {
      java.util.Arrays.sort(links(i))
      sorted(i) = true
    }

    def haveSameElements(i: Int, j: Int): Boolean = {
      ensureSorted(i)
      ensureSorted(j)
      links(i) sameElements links(j)
    }

    for {
      i <- 0 until n
      if isHead(i)
      j <- links(i)
      if j > i
      if isHead(j)
      if linksXor(i) == linksXor(j)
      if haveSameElements(i, j)
    } heads(j) = i

    val headLinks: Array[Array[Int]] = (0 until n).map { i =>
      if (isHead(i)) {
        links(i).filter(j => isHead(j) && (j != i))
      } else Array.empty[Int]
    } (collection.breakOut)

    val ans = Array.fill(n)(INF)

    @tailrec
    def dfs(cur: Int, prev: Int): Unit = {
      val prevValue = if (prev == -1) 1000000 else ans(prev)
      assert(ans(cur) == INF)
      ans(cur) = prevValue + 1
      val nextOpt = headLinks(cur).find(_ != prev)
      if (nextOpt.nonEmpty) dfs(nextOpt.get, cur)
    }
    val start = (0 until n).filter(isHead).minBy(headLinks(_).length)
    dfs(start, -1)

    for (i <- 0 until n) ans(i) = ans(heads(i))
    assert(ans.forall(_ != INF))
    println("YES")
    println(ans.mkString(" "))
  }.getOrElse(println("NO"))

}


import java.util.StringTokenizer

import scala.collection.mutable
import scala.io.StdIn

object D extends App with Reader {
  read()
  val n = int()
  val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())

  for (i <- 1 until n) {
    read()
    val s = int()
    val f = int()
    links(s) += f
    links(f) += s
  }

  read()
  val queue = Array.fill(n)(int())

  def isCorrect(): Boolean = {
    val visited = Array.fill(n+1)(false)

    if (queue(0) != 1) return false
    var checked = 1
    visited(1) = true

    for (i <- queue) {
      val next = links(i).filterNot(visited).toSet
      for (i <- 1 to next.size) {
        if (!next.contains(queue(checked))) return false
        visited(queue(checked)) = true
        checked += 1
      }
    }
    return true
  }

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

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

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

object C extends App {

  case class Point(x: Int, segId: Int, isBegin: Boolean)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val edges = Array.fill(n)(new collection.mutable.ArrayBuffer[Int]())
    (1 until n).foreach { _ =>
      val x = in.nextInt - 1
      val y = in.nextInt - 1
      edges(x) += y
      edges(y) += x
    }
    val dist = Array.fill(n)(0)
    val pred = Array.fill(n)(0)
    val q = collection.mutable.Queue[Int]()
    dist(0) = 1
    q.enqueue(0)
    while (q.nonEmpty) {
      val c = q.dequeue()
      edges(c).foreach { e =>
        if (dist(e) == 0) {
          dist(e) = dist(c) + 1
          pred(e) = c
          q.enqueue(e)
        }
      }
    }
    //dist.foreach(println)
    var lastDist = 1
    var ok = true
    val qq = collection.mutable.Queue[Int]()
    Array.fill(n)(in.nextInt).foreach { i =>
      val d = dist(i - 1)
      if (lastDist > d)
        ok = false
      lastDist = d

      qq.enqueue(i - 1)
      while (qq.nonEmpty && qq.front != pred(i - 1)) {
        qq.dequeue()
      }
      if (qq.isEmpty) ok = false
    }

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

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object 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 sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)
    val o_i = Array.ofDim[Int](N)
    rep(N) { i =>
      o_i(o(i)) = i
    }

    val (d, p) = traceBfs(t)

    var ok = true
    rep(N - 1) { i =>
      ok &= d(o(i)) < d(o(i + 1)) || d(o(i)) == d(o(i + 1)) && o_i(p(o(i))) <= o_i(p(o(i + 1)))
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  /**
    * @return (depth, parent)
    */
  def traceBfs(g: Array[Array[Int]]): (Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    p(0) = -1
    val d = Array.fill[Int](n)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      rep(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p)
  }

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object 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 sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)

    val INF = 1e9.toInt
    val bfs = Array.ofDim[Int](N)
    val d = Array.fill[Int](N)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while(cur < last) {
      val v = bfs(cur)
      val us = t(v)
      rep(us.length) { i =>
        val u = us(i)
        if (d(u) == INF) {
          bfs(last) = u
          d(u) = d(v) + 1
          last += 1
        }
      }
      cur += 1
    }

    var ok = o.distinct.length == N
    rep(N - 1) { i =>
      ok &= d(o(i)) <= d(o(i + 1))
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object 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 sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)

    val INF = 1e9.toInt
    val bfs = Array.ofDim[Int](N)
    val d = Array.fill[Int](N)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while(cur < last) {
      val v = bfs(cur)
      val us = t(v)
      rep(us.length) { i =>
        val u = us(i)
        if (d(u) == INF) {
          bfs(last) = u
          d(u) = d(v) + 1
          last += 1
        }
      }
      cur += 1
    }

    var ok = true
    rep(N - 1) { i =>
      ok &= o(i) <= o(i + 1)
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object 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 sc = new InputReader(System.in)

  def solve(): Unit = {
    val N = ni()
    val F, T = Array.ofDim[Int](N)
    rep(N - 1) { i =>
      F(i) = ni() - 1
      T(i) = ni() - 1
    }
    val t = packTree(N, F, T)
    val o = map(N)(_ => ni() - 1)

    val INF = 1e9.toInt
    val bfs = Array.ofDim[Int](N)
    val d = Array.fill[Int](N)(INF)
    d(0) = 0
    var cur = 0
    var last = 1
    while(cur < last) {
      val v = bfs(cur)
      val us = t(v)
      rep(us.length) { i =>
        val u = us(i)
        if (d(u) == INF) {
          bfs(last) = u
          d(u) = d(v) + 1
          last += 1
        }
      }
      cur += 1
    }

    var ok = o.distinct.length == N
    rep(N - 1) { i =>
      ok &= o(i) <= o(i + 1)
    }

    val ans = if (ok) "Yes" else "No"

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

  def packTree(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    rep(m)(i => p(from(i)) += 1)
    rep(m)(i => p(to(i)) += 1)
    rep(n)(i => t(i) = new Array(p(i)))
    rep(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.io.StdIn

object D extends App with Reader {
  read()
  val n = int()
  val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())

  for (i <- 1 until n) {
    read()
    val s = int()
    val f = int()
    links(s) += f
    links(f) += s
  }

  read()
  val queue = Array.fill(n)(int())

  def isCorrect(): Boolean = {
    val visited = Array.fill(n+1)(false)
    val rank = Array.fill(n+1)(0)
    val q = new mutable.Queue[Int]()
    var currentRank = 0

    for (i <- queue) {
      if (visited(i)) return false
      if (i != 1) {
        val prevs = links(i).filter(visited(_))
        if (prevs.isEmpty) return false
        val ranks = prevs.map(rank(_))
        val min = ranks.min
        val max = ranks.max
        if (max == min) {
          if (currentRank == min) {
            currentRank += 1
          } else if (currentRank != min + 1) {
            return false
          }
        } else if (max == min + 1) {
          if (currentRank != max) {
            return false
          }
        } else {
          return false
        }
      }
      rank(i) = currentRank
      visited(i) = true
    }
    return true
  }

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

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

import java.util.StringTokenizer

import scala.collection.mutable
import scala.io.StdIn

object D extends App with Reader {
  read()
  val n = int()
  val links = Array.fill(n+1)(new mutable.ArrayBuffer[Int]())

  for (i <- 1 until n) {
    read()
    val s = int()
    val f = int()
    links(s) += f
    links(f) += s
  }

  read()
  val queue = Array.fill(n)(int())

  def isCorrect(): Boolean = {
    val visited = Array.fill(n+1)(false)
    val rank = Array.fill(n+1)(0)
    val q = new mutable.Queue[Int]()
    var currentRank = 0

    for (i <- queue) {
      if (visited(i)) return false
      if (i != 1) {
        val prevs = links(i).filter(visited(_))
        if (prevs.isEmpty) return false
        val ranks = prevs.map(rank(_))
        val min = ranks.min
        val max = ranks.max
        if (max == min) {
          if (currentRank == min) {
            currentRank += 1
          } else if (currentRank != min + 1) {
            return false
          }
        } else if (max == min + 1) {
          if (currentRank != max) {
            return false
          }
        } else {
          return false
        }
      }
      rank(i) = currentRank
      visited(i) = true
    }
    return true
  }

  println(if (isCorrect()) "YES" else "NO")
}

trait Reader {
  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(StdIn.readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong
}

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

object C extends App {

  case class Point(x: Int, segId: Int, isBegin: Boolean)

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val edges = Array.fill(n)(new collection.mutable.ArrayBuffer[Int]())
    (1 until n).foreach { _ =>
      val x = in.nextInt - 1
      val y = in.nextInt - 1
      edges(x) += y
      edges(y) += x
    }
    val dist = Array.fill(n)(0)
    val q = collection.mutable.Queue[Int]()
    dist(0) = 1
    q.enqueue(0)
    while (q.nonEmpty) {
      val c = q.dequeue()
      edges(c).foreach { e =>
        if (dist(e) == 0) {
          dist(e) = dist(c) + 1
          q.enqueue(e)
        }
      }
    }
    //dist.foreach(println)
    var lastDist = 1
    var ok = true
    Array.fill(n)(in.nextInt).foreach { i =>
      val d = dist(i - 1)
      if (lastDist > d)
        ok = false
      lastDist = d
    }

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

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

object D extends App {

  def countLen(x: Long): Int = {
    var l = 0
    var xx = x
    while (xx > 0) {
      xx = xx / 10
      l += 1
    }
    l
  }

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val t = 123
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Long = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val x = ni()
      out.println(s"1 ${x-1}")
    }
  }
}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val x = in.nextInt()
      out.println(s"1 ${x-1}")
    }

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

import java.io.PrintWriter

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

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

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

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

    def solve(): Unit = {
        val x = readInt()
        println(s"1 ${x - 1}")

    }

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


object P039F extends App {
  readLine()
  val frog = readLine().split(' ').map(_.toInt)
  val mosq = readLine().split(' ').map(_.toInt)
  val killed = frog.map(x => (mosq.count(_ % x == 0)))
  val minValue = killed.min
  val cand = killed.zipWithIndex.filter(_._1 == minValue)
  println(cand.size)
  cand.foreach(x => printf("%d ", x._2+1))
}

object PacifistFrogs39F  extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val n = scanner.nextInt()
    val m = scanner.nextInt()
    val k = scanner.nextInt()
    val distances = (1 to m).map(_ => scanner.nextInt()).toArray
    val mosquitos = (1 to k).map(_ => scanner.nextInt())
    val result = (0 until m).map{ frog =>
      val d = distances(frog)
      (frog,mosquitos.count(place => place % d == 0))
    }
    val minCount = result.minBy(_._2)._2
    val bestFrogs = result.filter(_._2 == minCount)
    out.println(bestFrogs.length)
    out.println(bestFrogs.map{case (frog,count) =>  frog+1}.mkString(" "))
  }
}

object P039F extends App {
  readLine()
  val frog = readLine().split(' ').map(_.toInt)
  val mosq = readLine().split(' ').map(_.toInt)
  val killed = frog.map(x => (mosq.count(_ % x == 0)))
  val maxValue = killed.min
  killed.zipWithIndex.filter(_._1 == maxValue).foreach(x=>printf("%d ",x._2+1))
}


import scala.io._

object A1 {
  def main(args: Array[String]): Unit = {
    var lines = Source.stdin.getLines().take(3).toArray
    lines(0) = lines(0) + lines(0).toUpperCase() + "0123456789"
    lines(1) = lines(1) + lines(1).toUpperCase() + "0123456789"
    println(lines(2).map(p=>lines(1).charAt(lines(0).indexOf(p))))
  }
}

//package vandit

import java.util.Scanner

/**
  * Created by vjain on 13/07/17.
  */
object Solution {
  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val firstLayout : String = sc.next
    val secondLayout : String = sc.next
    val word : String = sc.next
    var transform : collection.mutable.Map[Char,Char] = collection.mutable.Map()

    for(pos <- 0 to firstLayout.size-1){
      transform.put(firstLayout.charAt(pos),secondLayout.charAt(pos))
      transform.put((firstLayout.charAt(pos)-32).toChar,(secondLayout.charAt(pos)-32).toChar)
    }
    for(pos <- 0 to word.size-1)
      print(transform.get(word.charAt(pos)).getOrElse(word.charAt(pos)))

  }
}

object B 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 _a, _b, t = readLine

  val a = _a + _a.toUpperCase
  val b = _b + _b.toUpperCase

  val res = new StringBuilder

  for (c <- t) {
    val i = a.indexOf(c)
    res += (if (i < 0) c else b(i))
  }

  println(res.toString())
}

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

/**
  * @author Aydar Gizatullin a.k.a. lightning95 on 30.05.17.
  */

object Main2 {

  def main(args: Array[String]) {
    val in = scala.io.StdIn
    val s1 = in readLine
    val s2 = in readLine
    val t = in readLine()
    println(t.map(x =>
      if (Character.isDigit(x))
        x
      else {
        val up = Character.isUpperCase(x)
        val pos = s1.indexOf(Character.toLowerCase(x))
        val res = if (up)
          Character.toUpperCase(s2.charAt(pos))
        else
          s2.charAt(pos)
        res
      }))
  }

}


//package codeforces

object SmallestWord {

  def main(args: Array[String]): Unit = {
    val input = io.StdIn.readLine

    for (i <- 0 to input.length - 2) {
      if (input(i) == input(i+1)) print("0 ")
      else print("1 ")
    }

    if(input.last == 'a') print("1") else print("0")
  }

}

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 S = ns()
    val N = S.length
    val ans = Array.fill[List[Int]](N + 1, 2)(Nil) // 0: 左寄せ, 1: 右寄せ
    rep(N) { i =>
      S(i) match {
        case 'a' =>
          ans(i + 1)(0) = 1 :: ans(i)(1)
          ans(i + 1)(1) = 0 :: ans(i)(1)

        case 'b' =>
          ans(i + 1)(0) = 0 :: ans(i)(0)
          ans(i + 1)(1) = 1 :: ans(i)(0)
      }
    }

    out.println(ans(N)(0).toArray.reverse.mkString(" "))
  }

  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 java.io._
import java.util
import java.util.StringTokenizer

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  def solve(in: InputReader): Unit = {
    val s = in.next.toCharArray
    (0 until s.size - 1).foreach { i =>

      if (s(i) != s(i + 1)) {
        (0 to (i / 2)).foreach { j =>
          val t = s(j)
          s(j) = s(i - j)
          s(i - j) = t
        }
        print("1 ")
      } else {
        print("0 ")
      }
    }

    if (s(s.size - 1) == 'a')
      println("1")
    else
      println("0")
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


import scala.collection.Set

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

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

import scala.collection.Set

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

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

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

import scala.collection.Set

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

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