Zane the wizard is going to perform a magic show shuffling the cups.There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.The problematic bone is initially at the position x = 1. Zane will confuse the audience by swapping the cups k times, the i-th time of which involves the cups at the positions x = ui and x = vi. If the bone happens to be at the position where there is a hole at any time, it will fall into the hole onto the ground and will not be affected by future swapping operations.Do not forget that Zane is a wizard. When he swaps the cups, he does not move them ordinarily. Instead, he teleports the cups (along with the bone, if it is inside) to the intended positions. Therefore, for example, when he swaps the cup at x = 4 and the one at x = 6, they will not be at the position x = 5 at any moment during the operation.  Zane’s puppy, Inzane, is in trouble. Zane is away on his vacation, and Inzane cannot find his beloved bone, as it would be too exhausting to try opening all the cups. Inzane knows that the Codeforces community has successfully helped Zane, so he wants to see if it could help him solve his problem too. Help Inzane determine the final position of the bone.

The first line contains three integers n, m, and k (2 ≤ n ≤ 106, 1 ≤ m ≤ n, 1 ≤ k ≤ 3·105) — the number of cups, the number of holes on the table, and the number of swapping operations, respectively. The second line contains m distinct integers h1, h2, ..., hm (1 ≤ hi ≤ n) — the positions along the x-axis where there is a hole on the table. Each of the next k lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the positions of the cups to be swapped.

Print one integer — the final position along the x-axis of the bone.

NoteIn the first sample, after the operations, the bone becomes at x = 2, x = 5, x = 7, and x = 1, respectively.In the second sample, after the first operation, the bone becomes at x = 2, and falls into the hole onto the ground.

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, m, k = read[Int]
    val isHole = Array.ofDim[Boolean](n+1)
    repeat(m) {
      isHole(read[Int]) = true
    }
    var bone = 1
    try {
      repeat(k) {
        require(!isHole(bone))
        val u, v = read[Int]
        if (bone == u) {
          bone = v
        } else if (bone == v) {
          bone = u
        }
      }
    } catch {
      case _: Throwable =>
    }
    write(bone)
  }
}
/****************************[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 in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    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 = assuming(t.size == 1)(t.head)
    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 maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def 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)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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

/**
  * Created by ruslan on 3/29/17.
  */
object ProblemA extends App {
    import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
import java.util.StringTokenizer

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val n = in.nextInt()
  val m = in.nextInt()
  var k = in.nextInt()

  val a = new Array[Boolean](n)

  for (i <- 1 to m)
    a(in.nextInt() - 1) = true

  var currentPos = 1

  while (!a(currentPos - 1) && k > 0) {
    val move1 = in.nextInt()
    val move2 = in.nextInt()
    if (move1 == currentPos)
      currentPos = move2
    else if (move2 == currentPos)
      currentPos = move1

    k -= 1
  }

  println(currentPos)

}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, m, k = read[Int]
    val isHole = read[Set, Int](m)
    val cups = Array.tabulate[Int](n+1)(identity)
    var bonePosition = 1
    repeat(k) {
      val u, v = read[Int]
      if (u == bonePosition && !isHole(bonePosition)) {
        bonePosition = v
      }
      val t = cups(u)
      cups(u) = cups(v)
      cups(v) = t
      //debug(u, v, cups.toList, bonePosition)
    }

    write(bonePosition)
  }
}
/****************************[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 in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    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 = assuming(t.size == 1)(t.head)
    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 maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def 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)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, m, k = read[Int]
    val isHole = read[Set, Int](m)
    var bone = 1
    repeat(k) {
      val u, v = read[Int]
      //debug(u, v, bone, isHole(bone))
      if (u == bone && !isHole(bone)) {
        bone = v
      }
    }

    write(bone)
  }
}
/****************************[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 in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    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 = assuming(t.size == 1)(t.head)
    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 maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def 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)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

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


You are given an array of $$$n$$$ integers $$$a_1,a_2,\dots,a_n$$$.You have to create an array of $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$ such that:   The array $$$b$$$ is a rearrangement of the array $$$a$$$, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets $$$\{a_1,a_2,\dots,a_n\}$$$ and $$$\{b_1,b_2,\dots,b_n\}$$$ are equal.For example, if $$$a=[1,-1,0,1]$$$, then $$$b=[-1,1,1,0]$$$ and $$$b=[0,1,-1,1]$$$ are rearrangements of $$$a$$$, but $$$b=[1,-1,-1,0]$$$ and $$$b=[1,0,2,-3]$$$ are not rearrangements of $$$a$$$.  For all $$$k=1,2,\dots,n$$$ the sum of the first $$$k$$$ elements of $$$b$$$ is nonzero. Formally, for all $$$k=1,2,\dots,n$$$, it must hold $$$$$$b_1+b_2+\cdots+b_k\not=0\,.$$$$$$ If an array $$$b_1,b_2,\dots, b_n$$$ with the required properties does not exist, you have to print NO.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t \le 1000$$$) — the number of test cases. The description of the test cases follows. The first line of each testcase contains one integer $$$n$$$ ($$$1\le n\le 50$$$)  — the length of the array $$$a$$$. The second line of each testcase contains $$$n$$$ integers $$$a_1,a_2,\dots, a_n$$$ ($$$-50\le a_i\le 50$$$)  — the elements of $$$a$$$.

For each testcase, if there is not an array $$$b_1,b_2,\dots,b_n$$$ with the required properties, print a single line with the word NO. Otherwise print a line with the word YES, followed by a line with the $$$n$$$ integers $$$b_1,b_2,\dots,b_n$$$.  If there is more than one array $$$b_1,b_2,\dots,b_n$$$ satisfying the required properties, you can print any of them.

NoteExplanation of the first testcase: An array with the desired properties is $$$b=[1,-2,3,-4]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$-1$$$.  The sum of the first three elements of $$$b$$$ is $$$2$$$.  The sum of the first four elements of $$$b$$$ is $$$-2$$$. Explanation of the second testcase: Since all values in $$$a$$$ are $$$0$$$, any rearrangement $$$b$$$ of $$$a$$$ will have all elements equal to $$$0$$$ and therefore it clearly cannot satisfy the second property described in the statement (for example because $$$b_1=0$$$). Hence in this case the answer is NO.Explanation of the third testcase: An array with the desired properties is $$$b=[1, 1, -1, 1, -1]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$1$$$.  The sum of the first two elements of $$$b$$$ is $$$2$$$.  The sum of the first three elements of $$$b$$$ is $$$1$$$.  The sum of the first four elements of $$$b$$$ is $$$2$$$.  The sum of the first five elements of $$$b$$$ is $$$1$$$. Explanation of the fourth testcase: An array with the desired properties is $$$b=[-40,13,40,0,-9,-31]$$$. For this array, it holds:   The first element of $$$b$$$ is $$$-40$$$.  The sum of the first two elements of $$$b$$$ is $$$-27$$$.  The sum of the first three elements of $$$b$$$ is $$$13$$$.  The sum of the first four elements of $$$b$$$ is $$$13$$$.  The sum of the first five elements of $$$b$$$ is $$$4$$$.  The sum of the first six elements of $$$b$$$ is $$$-27$$$.

import scala.collection.immutable
object Main extends App {

  def parseInt(str: String, count: Int): Seq[Int] = {
    val scanner = new java.util.Scanner(str)
    val res = (1 to count) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def scanInts(count: Int): Seq[Int] = parseInt(scala.io.StdIn.readLine(), count)
  def readMatrix(row: Int, col: Int) = (1 to row) map (x => scanInts(col))

  def solve(nums: immutable.Seq[Int]) = {
    val sum = nums.fold(0)(_ + _)

    if (sum == 0) {
      println("NO")
    } else {
      println("YES")
      var res = Seq(1,2,3)

      if (sum > 0){
        res = nums.sortWith(_ > _)
      } else {
        res = nums.sortWith(_ < _)
      }

      res.foreach(x => print(x+" "))
      println()
    }

  }

  //System.setIn(new java.io.FileInputStream("data.in"))

  val nCases = scanInts(1)(0)

  for (nCase <- 1 to nCases) {
    val nNums = scanInts(1)(0)
    val nums = scanInts(nNums)

    solve(collection.immutable.Seq(nums: _*))
  }

}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Base extends App {

  sealed trait ArraySum
  case object Zero extends ArraySum
  case object Negative extends ArraySum
  case object Positive extends ArraySum

  sealed trait CaseResult
  case object Impossible extends CaseResult{
    override def toString = "NO"
  }
  case class Possible(val res: Array[Int]) extends CaseResult{
    override def toString = s"YES\n${res.mkString(" ")}"
  }

  def inputSum(x: Array[Int]): ArraySum = {
    val s = x.sum

    (s compare 0) match {
      case 0 => Zero
      case 1 => Positive
      case -1 => Negative
    }
  }

  def calculateResultArr(x: Array[Int], nature: ArraySum) = {
    val negatives = x.filter(_ < 0)
    val positives = x.filter(_ > 0)
    val zeroes = x.filter(_ == 0)

    nature match {
      case Positive => positives ++ negatives ++ zeroes
      case Negative => negatives ++ positives ++ zeroes
    }
  }

  def processInputCase(): CaseResult = {
    val digits = readInt()
    val input: Array[Int] = readLine().split(" ").toArray.map(_.toInt)

    inputSum(input) match {
      case Zero => Impossible
      case x => Possible(calculateResultArr(input, x))
    }
  }

  val n = readInt()

  (1 to n).foreach(_ => println(processInputCase()))

}


Valera wanted to prepare a Codesecrof round. He's already got one problem and he wants to set a time limit (TL) on it.Valera has written n correct solutions. For each correct solution, he knows its running time (in seconds). Valera has also wrote m wrong solutions and for each wrong solution he knows its running time (in seconds).Let's suppose that Valera will set v seconds TL in the problem. Then we can say that a solution passes the system testing if its running time is at most v seconds. We can also say that a solution passes the system testing with some "extra" time if for its running time, a seconds, an inequality 2a ≤ v holds.As a result, Valera decided to set v seconds TL, that the following conditions are met:  v is a positive integer;  all correct solutions pass the system testing;  at least one correct solution passes the system testing with some "extra" time;  all wrong solutions do not pass the system testing;  value v is minimum among all TLs, for which points 1, 2, 3, 4 hold. Help Valera and find the most suitable TL or else state that such TL doesn't exist.

The first line contains two integers n, m (1 ≤ n, m ≤ 100). The second line contains n space-separated positive integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the running time of each of the n correct solutions in seconds. The third line contains m space-separated positive integers b1, b2, ..., bm (1 ≤ bi ≤ 100) — the running time of each of m wrong solutions in seconds.

If there is a valid TL value, print it. Otherwise, print -1.

import java.util.StringTokenizer

object _350A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val m = next.toInt
  val good = (1 to n).map(i => next.toInt)
  val bad = (1 to m).map(i => next.toInt)
  val goodMin = good.min
  val cb = (good.max until bad.min).filter(i => goodMin * 2 <= i)
  if (cb.size == 0) println(-1)
  else println(cb.min)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val right = in.next().split(" ").map(_.toInt)
  val minWrong = in.next().split(" ").map(_.toInt).min
  val proposal = Math.max(right.min * 2, right.max)
  if (minWrong > proposal)
    println(proposal)
  else
    println(-1)
}

object A350 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m).sorted
    val min = a.max
    val max = b.min
    var break = false
    for(i <- min until max if !break) {
      if(a.head*2 <= i) {
        println(i)
        break = true
      }
    }
    if(!break)
      println("-1")
  }

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

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

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

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

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

}

object A350 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m).sorted
    if(math.max(a.head*2, a.last) < b.head) {
      println(math.max(a.head*2, a.last))
    } else {
      println("-1")
    }
  }

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

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

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

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

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

}

object A350 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m).sorted
    val min = a.max
    val max = b.min
    var break = false
    for(i <- min until max if !break) {
      if(a.forall(_ <= i) && b.forall(_ > i) && a.head*2 <= i) {
        println(i)
        break = true
      }
    }
    if(!break)
      println("-1")
  }

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

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

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

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

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

}

object A350 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m).sorted
    val min = a.max
    val max = b.min
    var break = false
    for(i <- math.max(a.head*2,min) until max if !break) {
      println(i)
      break = true
    }
    if(!break)
      println("-1")
  }

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

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

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

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

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

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P350A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  val as = List.fill(N)(sc.nextInt)
  val bs = List.fill(M)(sc.nextInt)
  val bMin = bs min
  val aMin = as min
  val aMax = as max

  def solve(): Int = {
    if (aMax <= aMin * 2 && aMin * 2 < bMin) aMin * 2
    else if (aMin * 2 <= aMax && aMax < bMin) aMax
    else -1
  }

  out.println(solve)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val s1 = readLine()
    val a1 = readLine().split(" ").map(_.toInt)
    val a2 = readLine().split(" ").map(_.toInt)
    val min = (a1.min * 2).max(a1.max)
    val max = a2.min
    if (max <= min) println("-1")
    else println(min)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val right = in.next().split(" ").map(_.toInt)
  val minWrong = in.next().split(" ").map(_.toInt).min
  val proposal = minWrong - 1
  if (right.min * 2 <= proposal && right.max <= proposal)
    println(proposal)
  else
    println(-1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val right = in.next().split(" ").map(_.toInt)
  val minWrong = in.next().split(" ").map(_.toInt).min
  val proposal = Math.max(right.min * 2, right.max)
  if (minWrong < proposal)
    println(proposal)
  else
    println(-1)
}

object A350 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m).sorted
    val min = a.max
    val max = b.min
    if(math.max(a.head*2, a.last) <= b.last) {
      println(math.max(a.head*2,min))
    } else {
      println("-1")
    }
  }

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

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

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

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

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

}

object A350 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m).sorted
    val min = a.max
    val max = b.min
    var break = false
    for(i <- a.head*2 until max if !break) {
      println(i)
      break = true
    }
    if(!break)
      println("-1")
  }

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

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

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

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

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

}

object A350 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m).sorted
    if(math.max(a.head*2, a.last) < b.last) {
      println(math.max(a.head*2, a.last))
    } else {
      println("-1")
    }
  }

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

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

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

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

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

}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P350A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  val as = List.fill(N)(sc.nextInt)
  val bs = List.fill(M)(sc.nextInt)

  def solve(): Int = {
    val bMin = bs min
    val aMin = as min
    val aMax = as max

    if (bMin <= aMax) -1
    else if (0.5 * aMax < aMin) -1
    else aMax
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P350A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  val as = List.fill(N)(sc.nextInt)
  val bs = List.fill(M)(sc.nextInt)
  val bMin = bs min
  val aMin = as min
  val aMax = as max

  def solve1(): Int = if (2 * aMin < bMin) 2 * aMin else -1

  def solveM(): Int = if (bMin <= aMax) -1
                      else if (0.5 * aMax < aMin) -1
                      else aMax

  def solve(): Int = if (as.size == 1) solve1 else solveM

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P350A extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  val N, M = sc.nextInt

  val as = List.fill(N)(sc.nextInt).distinct
  val bs = List.fill(M)(sc.nextInt)
  val bMin = bs min
  val aMin = as min
  val aMax = as max

  def solve1(): Int = if (2 * aMin < bMin) 2 * aMin else -1

  def solveM(): Int = if (bMin <= aMax) -1
                      else if (0.5 * aMax < aMin) -1
                      else aMax

  def solve(): Int = if (as.size == 1) solve1 else solveM

  out.println(solve)
  out.close
}


Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.  Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.

Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).

NoteIn the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val signs = in.next()
  val values = in.next().split(' ').map(_.toInt).zip(signs).map{
    case(v, ch) => if (ch == '<') -v else v
  }
  val visited = Array.ofDim[Boolean](n)

  var i = 0

  while (i >= 0 && i < n && !visited(i)) {
    visited(i) = true
    i = i + values(i)
  }
  if (i < 0 || i >= n)
    println("FINITE")
  else
    println("INFINITE")
}

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

object _669B extends CodeForcesApp {
  override def apply(io: IO): io.type = {
    val (n, strip) = io[(Int, String)]
    val dir = strip map {c => if (c == '<') -1 else 1}
    val dist = io[Vector, Int](n)
    var pos = 1
    val seen = mutable.Set.empty[Int]
    while(true) {
      pos += dist(pos-1) * dir(pos-1)
      if (pos < 1 || pos > n) {
        return io += "FINITE"
      }
      if (!(seen add pos)) {
        return io += "INFINITE"
      }
    }
    io += "INFINITE"
  }
}
/****************************[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
  }
  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[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = 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
  val newLine: String = "\n"
}
/***********************************[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(): this.type = {
    println()
    this
  }

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

import java.util.Scanner

import scala.collection.mutable

object LittleArtemAndGrasshopper {

  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def parseString(str: String): String = {
    val scanner = new Scanner(str)
    val res = scanner.nextLine()
    scanner.close()
    res
  }

  def main(args: Array[String]) {
    val stripLen = parseInts(Console.readLine(), 1)(0)
    val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }
    val jumpLens = parseInts(Console.readLine(), stripLen)

    val visited = mutable.Set.empty[Int]
    visited add 0

    @annotation.tailrec
    def jump(pos: Int): String = {
      val newPos = pos + jumpLens(pos) * directions(pos)
      if (newPos < 0 || newPos > stripLen - 1) {
        return "FINITE"
      } else if (visited.contains(newPos)) {
        return "INFINITE"
      }
      visited add newPos
      jump(newPos)
    }

    println(jump(0))
  }
}

import java.util.Scanner

import scala.collection.mutable

object LittleArtemAndGrasshopper {

  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def parseString(str: String): String = {
    val scanner = new Scanner(str)
    val res = scanner.nextLine()
    scanner.close()
    res
  }

  def main(args: Array[String]) {
    val stripLen = parseInts(Console.readLine(), 1)(0)
    val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }
    val jumpLens = parseInts(Console.readLine(), stripLen)

    val visited = mutable.Set.empty[Int]
    visited add 0

    def someMethod(): String = {
      var pos = 0
      while (true) {
        pos = pos + jumpLens(pos) * directions(pos)
        if (pos < 0 || pos > stripLen - 1) {
          return "FINITE"
        } else if (visited.contains(pos)) {
          return "INFINITE"
        }
        visited add pos
      }

      "Messed up"
    }

    println(someMethod)

  }
}

import java.util.Scanner

import scala.collection.mutable

object LittleArtemAndGrasshopper {

  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def parseString(str: String): String = {
    val scanner = new Scanner(str)
    val res = scanner.nextLine()
    scanner.close()
    res
  }

  def main(args: Array[String]) {
    val stripLen = parseInts(Console.readLine(), 1)(0)
    val directions = parseString(Console.readLine()).toCharArray map {dir => if (dir == '<') -1 else 1}
    val jumpLens = parseInts(Console.readLine(), stripLen)

    val visited = mutable.Set.empty[Int]
    visited add 0

    @annotation.tailrec
    def jump(pos: Int): String = {
      val newPos = pos + jumpLens(pos) * directions(pos)
      if (newPos < 0 || newPos > stripLen - 1) {
        return "FINITE"
      } else if (visited.contains(newPos)) {
        return "INFINITE"
      }
      visited.add(newPos)

      jump(newPos)
    }

    println(jump(0))
  }
}

import java.util.Scanner

import scala.collection.mutable

object LittleArtemAndGrasshopper {

  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def parseString(str: String): String = {
    val scanner = new Scanner(str)
    val res = scanner.nextLine()
    scanner.close()
    res
  }

  def main(args: Array[String]) {
    val stripLen = parseInts(Console.readLine(), 1)(0)
    val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }
    val jumpLens = parseInts(Console.readLine(), stripLen)

    val visited = mutable.Set.empty[Int]
    visited add 0

    def jump(pos: Int): String = {
      val newPos = pos + jumpLens(pos) * directions(pos)
      if (newPos < 0 || newPos > stripLen - 1) {
        return "FINITE"
      } else if (visited.contains(newPos)) {
        return "INFINITE"
      }
      visited add newPos
      jump(newPos)
    }

    println(jump(0))
  }
}

import java.util.Scanner

import scala.collection.mutable

object LittleArtemAndGrasshopper {

  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def parseString(str: String): String = {
    val scanner = new Scanner(str)
    val res = scanner.nextLine()
    scanner.close()
    res
  }

  def main(args: Array[String]) {
    val stripLen = parseInts(Console.readLine(), 1)(0)
    val directions = parseString(Console.readLine()).toCharArray map {dir => if (dir == '<') -1 else 1}
    val jumpLens = parseInts(Console.readLine(), stripLen)

    val visited = mutable.Set.empty[Int]

    @annotation.tailrec
    def jump(pos: Int): String = {
      val newPos = pos + jumpLens(pos) * directions(pos)
      if (newPos < 1 || newPos > stripLen - 1) {
        return "FINITE"
      } else if (visited.contains(newPos)) {
        return "INFINITE"
      }
      visited.add(newPos)

      jump(newPos)
    }

    println(jump(0))
  }
}

import java.util.Scanner

import scala.collection.mutable

object LittleArtemAndGrasshopper {

  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def parseString(str: String): String = {
    val scanner = new Scanner(str)
    val res = scanner.nextLine()
    scanner.close()
    res
  }

  def main(args: Array[String]) {
    val stripLen = parseInts(Console.readLine(), 1)(0)
    val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }
    val jumpLens = parseInts(Console.readLine(), stripLen)

    val visited = mutable.Set.empty[Int]
    visited add 0
    var pos = 0

    while (true) {
      pos = pos + jumpLens(pos) * directions(pos)
      if (pos < 0 || pos > stripLen - 1) {
        return "FINITE"
      } else if (visited.contains(pos)) {
        return "INFINITE"
      }
      visited add pos
    }

  }
}

import java.util.Scanner

import scala.collection.mutable

object LittleArtemAndGrasshopper {

  def parseInts(str: String, numIterations: Integer) = {
    val scanner = new Scanner(str)
    val res = (0 until numIterations) map (_ => scanner.nextInt())
    scanner.close()
    res
  }

  def parseString(str: String): String = {
    val scanner = new Scanner(str)
    val res = scanner.nextLine()
    scanner.close()
    res
  }

  def main(args: Array[String]) {
    val stripLen = parseInts(Console.readLine(), 1)(0)
    val directions = parseString(Console.readLine()).toCharArray map { dir => if (dir == '<') -1 else 1 }
    val jumpLens = parseInts(Console.readLine(), stripLen)

    val visited = mutable.Set.empty[Int]
    visited add 0

    def jump(pos: Int): String = {
      val newPos = pos + jumpLens(pos) * directions(pos)
      if (newPos < 0 || newPos > stripLen - 1) {
        return "FINITE"
      } else if (visited.contains(newPos)) {
        return "INFINITE"
      }
      visited add newPos
      jump(newPos)
    }

  }
}


Initially, you have the array $$$a$$$ consisting of one element $$$1$$$ ($$$a = [1]$$$).In one move, you can do one of the following things:  Increase some (single) element of $$$a$$$ by $$$1$$$ (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and increase $$$a_i$$$ by one);  Append the copy of some (single) element of $$$a$$$ to the end of the array (choose some $$$i$$$ from $$$1$$$ to the current length of $$$a$$$ and append $$$a_i$$$ to the end of the array). For example, consider the sequence of five moves:  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [1, 1]$$$.  You take the first element $$$a_1$$$, increase it by $$$1$$$ and get $$$a = [2, 1]$$$.  You take the second element $$$a_2$$$, append its copy to the end of the array and get $$$a = [2, 1, 1]$$$.  You take the first element $$$a_1$$$, append its copy to the end of the array and get $$$a = [2, 1, 1, 2]$$$.  You take the fourth element $$$a_4$$$, increase it by $$$1$$$ and get $$$a = [2, 1, 1, 3]$$$. Your task is to find the minimum number of moves required to obtain the array with the sum at least $$$n$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$) — the lower bound on the sum of the array.

For each test case, print the answer: the minimum number of moves required to obtain the array with the sum at least $$$n$$$.

//package codeforces.contests._1426

/*
https://codeforces.com/contest/1426/problem/C
 */
object IncreaseAndCopy {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readInt()

      val sqrt = math.sqrt(n).toInt

      val result = {
        if (sqrt * sqrt == n) {
          sqrt - 1 + sqrt - 1
        } else {
          sqrt - 1 + n / sqrt + (if (n % sqrt == 0) -1 else 0)

        }
      }
      println(result)
    }
  }
}

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

  @annotation.tailrec
  def go(n: Int, i: Int): Int = {
    val j = (n + i - 1) / i

    if (j <= i) i + j - 2
    else go(n, i + 1)
  }

  val t = readInt()

  (0 until t).foreach { _ =>
    val n   = readInt()
    val ans = go(n, 1)

    println(ans)
  }
}

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

  @annotation.tailrec
  def go(n: Int, i: Int): Int = {
    val j = (n + i - 1) / i

    if (j <= i) i + j
    else go(n, i + 1)
  }

  val t = readInt()

  (0 until t).foreach { _ =>
    val n   = readInt()
    val ans = go(n, 1)

    println(ans)
  }
}


When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.Let's define the simple prettiness of a word as the ratio of the number of vowels in the word to the number of all letters in the word.Let's define the prettiness of a word as the sum of simple prettiness of all the substrings of the word.More formally, let's define the function vowel(c) which is equal to 1, if c is a vowel, and to 0 otherwise. Let si be the i-th character of string s, and si..j be the substring of word s, staring at the i-th character and ending at the j-th character (sisi + 1... sj, i ≤ j).Then the simple prettiness of s is defined by the formula:The prettiness of s equals Find the prettiness of the given song title.We assume that the vowels are I, E, A, O, U, Y.

The input contains a single string s (1 ≤ |s| ≤ 5·105) — the title of the song.

Print the prettiness of the song with the absolute or relative error of at most 10 - 6.

NoteIn the first sample all letters are vowels. The simple prettiness of each substring is 1. The word of length 7 has 28 substrings. So, the prettiness of the song equals to 28.

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

object E {

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

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

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

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

  def solve: Int = {
    val chars = next.toCharArray
    val n = chars.length
    val vowels = Set('A', 'Y', 'E', 'U', 'I', 'O')
    var ans = 0.0d
    val sum1 = new Array[Double](n + 1)
    for (i <- 1 until n + 1) {
      sum1(i) = sum1(i - 1) + (1.0d / i)
    }
    val sum2 = new Array[Double](n + 1)
    sum2(n) = 1.0d / n
    for (i <- n - 1 to 0 by - 1) {
      sum2(i) = sum2(i + 1) + (1.0d * n - i + 1) / i
    }
    (1 to n).foreach(i => {
      if (vowels.contains(chars(i - 1))) {
        val min = Math.min(i, n - i + 1)
        val max = Math.max(i, n - i + 1)
        ans += min - 1
        ans += min * (sum1(max - 1) - sum1(min - 1))
        ans += sum2(max)
      }
    })
    out.println(ans)
    return 1
  }

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

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

object E {

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

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

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

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

  def solve: Int = {
    val chars = next.toCharArray
    val n = chars.length
    val vowels = Set('A', 'Y', 'E', 'U', 'I', 'O')
    var ans = 0.0f
    val sum1 = new Array[Float](n + 1)
    for (i <- 1 until n + 1) {
      sum1(i) = sum1(i - 1) + (1.0f / i)
    }
    val sum2 = new Array[Float](n + 1)
    sum2(n) = 1.0f / n
    for (i <- n - 1 to 0 by - 1) {
      sum2(i) = sum2(i + 1) + (1.0f * n - i + 1) / i
    }
    (1 to n).foreach(i => {
      if (vowels.contains(chars(i - 1))) {
        val min = Math.min(i, n - i + 1)
        val max = Math.max(i, n - i + 1)
        ans += min - 1
        ans += min * (sum1(max - 1) - sum1(min - 1))
        ans += sum2(max)
      }
    })
    out.println(ans)
    return 1
  }

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

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

object E {

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

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

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

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

  def solve: Int = {
    val chars = next.toCharArray
    val n = chars.length
    val vowels = Set('A', 'Y', 'E', 'U', 'I', 'O')
    var ans = 0.0f
    val sum1 = new Array[Float](n + 1)
    for (i <- 1 until n + 1) {
      sum1(i) = sum1(i - 1) + (1.0f / i)
    }
    val sum2 = new Array[Float](n + 1)
    for (i <- 1 until n + 1) {
      sum2(i) = sum2(i - 1) + (1.0f * n - i + 1) / i
    }
    (1 to n).foreach(i => {
      if (vowels.contains(chars(i - 1))) {
        val min = Math.min(i, n - i + 1)
        val max = Math.max(i, n - i + 1)
        ans += min - 1
        ans += min * (sum1(max) - sum1(min - 1))
        ans += sum2(n) - sum2(max)
      }
    })
    out.println(ans)
    return 1
  }

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


Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately. Valera is very greedy, so he wants to serve all n customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe. Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.

The first line contains a single integer n (1 ≤ n ≤ 105), that is the number of cafe visitors. Each of the following n lines has two space-separated integers hi and mi (0 ≤ hi ≤ 23; 0 ≤ mi ≤ 59), representing the time when the i-th person comes into the cafe.  Note that the time is given in the chronological order. All time is given within one 24-hour period.

Print a single integer — the minimum number of cashes, needed to serve all clients next day.

NoteIn the first sample it is not enough one cash to serve all clients, because two visitors will come into cafe in 8:10. Therefore, if there will be one cash in cafe, then one customer will be served by it, and another one will not wait and will go away.In the second sample all visitors will come in different times, so it will be enough one cash.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(Range(0, n).map{ _ => in.next()}.groupBy(t => t).map(t => t._2.length).max)
}

import collection.mutable
import java.util.Scanner

object A extends App {
	val in = new Scanner(System.in)
	val n = in.nextInt()
	val t = new mutable.HashMap[(Int, Int), Int]().withDefaultValue(0)
	for (i <- 0 until n) {
		val h = in.nextInt()
		val m = in.nextInt()
		t((h, m)) += 1
	}
	println(t.values.max)
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

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

  val N = sc.nextLine.toInt

  val answer: Int = List.fill(N)(sc.nextLine).groupBy(identity[String]).map(_._2.length).max

  out.println(answer)
  out.close
}

// codeforces problem 237A

object Kassa extends App {

  def readMinutes(n:Int) : List[Int] = {
    def readLines(n:Int) : List[String] = n match {
      case 0 => List()
      case _ => Console.readLine() :: readLines(n-1)
    }

    def strToMinutes(s:String) : Int = {
      val shm = s.split(" ")
      val hr = shm(0) toInt;
      val mn = shm(1) toInt;
      hr * 60 + mn
    }

    val lines = readLines(n)
    val minutes = lines map strToMinutes
    minutes
  }

  def maxSeq(l:List[Int], lastMn:Int, lastRep:Int, maxRep:Int) : (Int, Int, Int) = l match {
    case List() => (lastMn, lastRep, maxRep)
    case hd :: tl => {
      val lr = if (hd == lastMn) lastRep+1 else 1
      val mxr = if (lr > maxRep) lr else maxRep
      maxSeq(tl, hd, lr, mxr)
    }
  }

  val n = Console.readInt()
  val minutes = readMinutes(n)
  val smin = minutes sorted;
  val (mxMin, lr, maxr) = maxSeq(smin, -1, 0, 0)
  Console.println(maxr)
}

import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  def ans = (for(_ <- 1 to readInt) yield readInts.foldLeft(0)((a, b) => 60 * a + b)).groupBy(x => x).foldLeft(0) {
    case (a, (_, b)) => a max b.size
  }

  def main(args: Array[String]) {
    println(ans)
  }
}

object Main {
  def read(): (Int, Int) = {
    val a = readLine().split(" ").map(_.toInt)
    (a(0), a(1))
  }

  def main(args: Array[String]) {
    val num = readInt
    var prev: (Int, Int) = (-1, -1)
    var max, curn = 1
    for(i <- 1 to num) {
      val curr = read()
      if (curr == prev) {
        curn += 1
      } else {
        if (curn > max) max = curn
        curn = 1
        prev = curr
      }
    }
    println(max.max(curn))
  }
}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object FreeCash {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val n = readInt
     val hms = for {
       i <- 1 to n
       (h,m) = readTuple
     } yield 60*h+m
     val sim = hms.tail.foldLeft( (hms.head,1,1)){
       case ((prev, streak, max),cur) =>
         if (cur == prev) {
           (cur, streak+1, Math.max(max,streak+1))
         } else {
           (cur,1,max)
         }
     }
     println(sim._3)
   }

}

object Kassa extends App {

  def readMinutes(n:Int) : List[Int] = {
    def readLines(n:Int) : List[String] = n match {
      case 0 => List()
      case _ => Console.readLine() :: readLines(n-1)
    }

    def strToMinutes(s:String) : Int = {
      val shm = s.split(" ")
      val hr = shm(0) toInt;
      val mn = shm(1) toInt;
      hr * 60 + mn
    }

    val lines = readLines(n)
    val minutes = lines map strToMinutes
    minutes
  }

  val n = Console.readInt()
  val minutes = readMinutes(n)
  val smin = minutes sorted;
  val su = Set(smin)
  Console.println(su size)
}

object Kassa extends App {

  def readMinutes(n:Int) : List[Int] = {
    def readLines(n:Int) : List[String] = n match {
      case 0 => List()
      case _ => Console.readLine() :: readLines(n-1)
    }

    def strToMinutes(s:String) : Int = {
      val shm = s.split(" ")
      val hr = shm(0) toInt;
      val mn = shm(1) toInt;
      hr * 60 + mn
    }

    val lines = readLines(n)
    val minutes = lines map strToMinutes
    minutes
  }

  def maxSeq(l:List[Int], lastMn:Int, lastRep:Int, maxRep:Int) : (Int, Int, Int) = l match {
    case List() => (lastMn, lastRep, maxRep)
    case hd :: tl => {
      val mxr = if (hd == lastMn && lastRep >= maxRep) lastRep+1 else maxRep
      val lr = if (hd == lastMn) lastRep+1 else 1
      maxSeq(tl, hd, lr, mxr)
    }
  }

  val n = Console.readInt()
  val minutes = readMinutes(n)
  val smin = minutes sorted;
  val (mxMin, lr, maxr) = maxSeq(smin, -1, 0, 0)
  Console.println(maxr)
}

object Kassa extends App {
  val n = Console.readInt()
  Console.println("n = " + n)

  def readMinutes(n:Int) : List[Int] = {
    def readLines(n:Int) : List[String] = n match {
      case 0 => List()
      case _ => Console.readLine() :: readLines(n-1)
    }

    def strToMinutes(s:String) : Int = {
      val shm = s.split(" ")
      val hr = shm(0) toInt;
      val mn = shm(1) toInt;
      hr * 60 + mn
    }

    val lines = readLines(n)
    val minutes = lines map strToMinutes
    minutes
  }

  val minutes = readMinutes(n)
  val smin = minutes sorted;
  val su = Set(smin)
  Console.println(su size)
}

object Main {
  def read(): (Int, Int) = {
    val a = readLine().split(" ").map(_.toInt)
    (a(0), a(1))
  }

  def main(args: Array[String]) {
    val num = readInt
    var prev: (Int, Int) = (-1, -1)
    var max, curn = 1
    for(i <- 1 to num) {
      val curr = read()
      if (curr == prev) {
        curn += 1
      } else {
        if (curn > max) max = curn
        curn = 1
        prev = curr
      }
    }
    println(max)
  }
}