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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    val N = ni()
    REP(N) { _ =>
      val c, s = ni()
      val ans = if (c >= s) {
        s
      } else {
        if (s % c == 0) {
          val unit = s / c
          unit.toLong * unit * c
        } else {
          val unit1 = (s + c - 1) / c
          val unit2 = s / c
          val r = s % c
          unit1.toLong * unit1 * r + unit2.toLong * unit2 * (c - r)
        }
      }
      out.println(ans)
    }
  }
}

import scala.io.StdIn._

object Main extends App {

    val n = readLine().toInt

    for (i <- 0 until n) {
        val Array(c, sum) = readLine().split(" ").map(_.toInt)
        var arr = Seq.fill(c)(1)
        var res: Long = 0
        if (c > sum) {
            res = sum
        } else {
            val del: Int = sum / c
            val needUp = sum - del * c
            res = Math.pow(del, 2).asInstanceOf[Long] * (c-needUp) +
                    Math.pow(del+1, 2).asInstanceOf[Long] * needUp
        }
        println(res)
    }

}

import scala.io.StdIn._
object Main{
  def main(args: Array[String]): Unit ={
    val N = readInt()
    val C = Array.ofDim[Int](N)
    val SUM = Array.ofDim[Int](N)
    for(i <- 0 until N){
      val line = readLine().split(" ").map(_.toInt)
      val c = line(0)
      val sum = line(1)
      val result =
      if(sum % c == 0){
        val k = sum / c
        k * k * c
      }else{
        val extra = sum % c
        val k = sum / c
        k * k * (c - extra) + (k+1) * (k+1) * extra
      }
      println(result)
    }
  }
}

import scala.io.StdIn._

object Main extends App {

    val n = readLine().toInt

    for (i <- 0 until n) {
        val Array(c, sum) = readLine().split(" ").map(_.toInt)
        var arr = Seq.fill(c)(1)
        var res: Long = 0
        if (c > sum) {
            res = 1
        } else {
            var del: Int = sum / c
            val needUp = sum - del * c
            res = Math.pow(del, 2).asInstanceOf[Long] * (c-needUp) +
                    Math.pow(del+1, 2).asInstanceOf[Long] * needUp
        }
        println(res)
    }

}


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

object Template {

  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }

  import Lazy._

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val A = for (i <- 0.until(N)) yield sc.nextInt()
    val valueToMaxIndex = A.zipWithIndex.groupBy(_._1).mapValues(list => list.map(_._2).max)
    val minIndex = valueToMaxIndex.map{case (v, index) => index}.min
    val answer = A(minIndex)

    println(answer)

  }
}

object B extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)
  val last = Array.fill(as.max + 1)(Int.MaxValue / 2)

  for (i <- as.indices) last(as(i)) = i

  val min = as.minBy(last)

  println(min)
}

/**
  * @see http://codeforces.com/contest/890/problem/B
  */

object BVladAndCafes extends App {
  val n = scala.io.StdIn.readLine().toInt
  val as = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val last = Array.fill(as.max + 1)(20000)

  for (i <- as.indices) last(as(i)) = i

  println(as minBy last)
}

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

object Template {

  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }

  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }

  import Lazy._

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val N = sc.nextInt()
    val A = for (i <- 0.until(N)) yield sc.nextInt()
    val valueToMaxIndex = A.zipWithIndex.groupBy(_._2).mapValues(list => list.map(_._2).max)
    val minIndex = valueToMaxIndex.map{case (v, index) => index}.min
    val answer = A(minIndex)

    println(answer)

  }
}


object CF340C_198 extends App{
  def gcd (x : Long, y : Long) : Long = {
    if (x % y == 0) y else gcd (y, x % y)
  }
  val n = Console.readLine.toInt
  val a = Console.readLine.split(' ').map(_.toLong).sorted.zip(1 to n).map{case (x, i) =>
    (4 * i - 2 * n - 1) * x
  }.reduce(_ + _)
  val d = gcd(a, n)
  printf("%d %d\n", a/d, n/d)
}

object CF340C_198 extends App{
  def gcd (x : Long, y : Long) : Long = {
    if (x % y == 0) y else gcd (y, x % y)
  }
  val n = Console.readLine.toInt
  val a = Console.readLine.split(' ').map(_.toLong).sorted.zip(1 to n).map{case (x, i) =>
    (4 * i - 2 * n - 1) * x
  }.reduce(_ + _)
  val d = gcd(a, n)
  println((a/d).toString + " " + (n/d).toString)
}

object CF340C_198 extends App{
  def gcd (x : Long, y : Long) : Long = {
    if (x % y == 0) y else gcd (y, x % y)
  }
  val n = Console.readLine.toInt
  val a = Console.readLine.split(' ').map(_.toLong).zip(1 to n).map{case (x, i) =>
    (4 * i - 2 * n - 1) * x
  }.reduce(_ + _)
  val d = gcd(a, n)
  printf ("%d %d", a/d, n/d)
}


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


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

}

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: _*))
  }

}


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

}

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


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

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

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

  }
}


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

//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
    else go(n, i + 1)
  }

  val t = readInt()

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

    println(ans)
  }
}


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

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


import scala.math._
object C
{
    def main(args: Array[String])
    {
        val n = readInt
        val stairs = readLine split(" ") map(_.toInt)
        val m = readInt
        var height = 0L
        (0 until m) foreach
        {
            i =>
            val Array(w,h) = readLine split(" ") map(_.toInt)
            val hh = max(height, stairs(w-1))
            println(hh)
            height = h + hh
        }
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong).scanLeft(0l){Math.max}
  val m = in.next().toInt
  println((1 to m).map { _ =>
    val Array(w, h) = in.next().split(' ').map(_.toInt)
    val res = Math.max(data(1), data(w))
    data(1) = res + h
    res
  }.mkString("\n"))
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val m=readInt
    var height:Long=0
    for(_<-1 to m){
        val Array(w,h)=readLine.split(" ").map(_.toInt)
        val hh=math.max(height,a(w-1))
        println(hh)
        height=hh+h
    }
}

object Main272C {

  def main(args: Array[String]) {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val m = readInt
    var currentH = 0L
    for (i <- 1 to m) {
      val Array(w, h) = readLine.split(" ").map(_.toInt)
      val fallingH = currentH max a(w-1)
      println(fallingH)
      currentH = fallingH + h
    }
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).scanLeft(0){Math.max}
  val m = in.next().toInt
  println((1 to m).map { _ =>
    val Array(w, h) = in.next().split(' ').map(_.toInt)
    val res = Math.max(data(1), data(w))
    data(1) = res + h
    res
  }.mkString("\n"))
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer

object test6 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)
    val m=readInt
    var height=0
    for(_<-1 to m){
        val Array(w,h)=readLine.split(" ").map(_.toInt)
        val hh=math.max(height,a(w-1))
        println(hh)
        height=hh+h
    }
}

object Main272C {

  def main(args: Array[String]) {
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val m = readInt
    var currentH = 0
    for (i <- 1 to m) {
      val Array(w, h) = readLine.split(" ").map(_.toInt)
      val fallingH = currentH max a(w-1)
      println(fallingH)
      currentH = fallingH + h
    }
  }

}