import java.util.Scanner

/**
 * Created by lurker on 2014. 7. 20..
 */
object CF256_C extends App {

  def Process(values:Array[Int]):Int = {
    case class WaitingCall(l:Int, r:Int, h:Int,var v:Option[Int] = None)
    case class Visited(minh:Int, left:WaitingCall, right:WaitingCall, me:WaitingCall)

    val waitingQueue = scala.collection.mutable.Queue[WaitingCall]()
    val visited      = scala.collection.mutable.Stack[Visited]()

    waitingQueue.enqueue(WaitingCall(0, values.length-1, 0))

    while(waitingQueue.nonEmpty) {
      val v = waitingQueue.dequeue()
      if(v.l > v.r) {
        v.v = Some(0)
      } else {
        var minvalue = Integer.MAX_VALUE
        var mini: Int = -1
        for (i <- (v.l to v.r)) {
          if (values(i) < minvalue) {
            minvalue = values(i)
            mini = i
          }
        }
        val left = WaitingCall(v.l, mini - 1, minvalue)
        val right = WaitingCall(mini + 1, v.r, minvalue)
        visited.push(Visited(minvalue, left, right, v))
        waitingQueue.enqueue(left, right)
      }
    }

    var v:Visited = null
    while(visited.nonEmpty) {
      v = visited.pop()
      for(leftv <- v.left.v; rightv <- v.right.v){
        v.me.v = Some(Seq(v.me.r - v.me.l + 1, leftv + rightv + v.minh - v.me.h ).min)
      }
    }
    v.me.v.getOrElse(-1)
  }
  val input = new Scanner(System.in)

  val n = input.nextInt()
  val values = (1 to n).map(_ => input.nextInt())
  println(Process(values.toArray))

}

import scala.util.control.TailCalls._

object Fence {

  def splitter(as: String) = as.split("\\s+").toVector.map(_.toInt)

  def splitOn[A](xs: Vector[A], delim: A): Vector[Vector[A]] = {
    val builder = Vector.newBuilder[Vector[A]]
    var i = 0
    var start = 0

    while (i < xs.size) {
      if (xs(i) == delim) {
        if (i != start) {
          builder += xs.slice(start, i)
        }
        start = i + 1
      }
      i += 1
    }

    if (i != start) builder += xs.slice(start, i)
    builder.result
  }

  def solve(xs: Vector[Int]): Int = {
    def go(xs: Vector[Int], previous: Int): TailRec[Int] = {
      val min = xs.min

      splitOn(xs, min).foldLeft(done(min - previous)) {
        case (acc, part) => for {
          total <- acc
          cost  <- go(part, min)
        } yield total + cost
      }.map(math.min(xs.size, _))
    }

    go(xs, 0).result
  }

  def main(args: Array[String]) {
    val List(ns, as) = io.Source.stdin.getLines.take(2).toList
    val aVec = splitter(as)
    println(solve(aVec))
  }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next()
  val icount = data.count(_ == 'I')
  val acount = data.count(_ == 'A')
  val fcount = data.count(_ == 'F')
  var result = if (icount == 1) 1 else if (icount == 0) acount else 0
  println(result)
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val s = readLine()

    val i = s.count(_ == 'I')
    val a = s.count(_ == 'A')
    val f = s.count(_ == 'F')

    if (i == 1) println("1")
    else if (i > 1) println("0")
    else println(a)
  }
}

/**
 * Created by slie742 on 9/09/2015.
 */

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

import Math.abs
import Math.max
import Math.min

object CowsPoker {

  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 s = readLine().groupBy(c => c).mapValues(s => s.length).withDefaultValue(0)
    if (s('I') >= 2) println(0)
    else if (s('I') == 1) println(1)
    else println(s('A'))
  }

}

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

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

  def solve(): Int = {
    val N = sc.nextInt
    sc.nextLine
    val Cows = sc.nextLine.groupBy(identity).map(x => (x._1, x._2.size))

    Cows.get('I') match {
      case None    => Cows.getOrElse('A', 0)
      case Some(1) => 1
      case Some(_) => 0
    }
  }

  out.println(solve)
  out.close
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

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

  readInt
  val pl = reader.readLine().filterNot(_ == 'F')
  val in = pl.count(_ == 'I')
  val allin = pl.length - in
  val ans = if(in > 1) 0 else if(in == 1) 1 else allin

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next()
  val icount = data.count(_ == 'I')
  val acount = data.count(_ == 'A')
  val fcount = data.count(_ == 'F')
  var result = if (icount == 1) 1 else acount
  println(result)
}


import annotation.tailrec
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

  readInt
  val a = readInts
  readInt
  val b = readInts
  val gears = a.flatMap(x => b.filter(_ % x == 0).map(_ / x))
  def ans = gears.count(_ == gears.max)

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

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a1 = readLine().split(" ").map(_.toInt)
    val m = readInt()
    val a2 = readLine().split(" ").map(_.toInt)
    val a = a2.flatMap(b => a1.map(a => (b, a)))
    val pr = a.filter(t => t._1 % t._2 == 0).map(t => t._1 / t._2)
    val max = pr.max
    println(pr.count(_ == max))
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val f = StdIn.readLine.split(" ").map(_.toInt)
    val m = StdIn.readInt()
    val b = StdIn.readLine.split(" ").map(_.toInt)
    val values = for {
      i <- f
      j <- b
      if j % i == 0
    } yield {
      j / i
    }
    val maxRatio = values.max
    println(values.count(_ ==  maxRatio))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val m = in.next().toInt
  val data2 = in.next().split(' ').map(_.toInt)
  val res = data2.flatMap(i => data.map(j => if (i % j == 0) i / j else -1).filter(_ >= 0))
  val max = res.max
  println(res.count(_ == max))
}

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

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

  val N = sc.nextInt
  val A = List.fill(N)(sc.nextInt)
  val M = sc.nextInt
  val B = List.fill(M)(sc.nextInt)

  val rs = for {
      a <- A
      b <- B
      if b % a == 0
    }
    yield b / a

  val rsMax = rs.max

  out.println(rs.count(_ == rsMax))
  out.close
}

import io.Source
import java.util.StringTokenizer

object Runner extends App {

  val input = Source.fromInputStream(System.in).bufferedReader();
  var token: StringTokenizer = null;

  def TOKEN() = {
    while (token == null || !token.hasMoreTokens)
      token = new StringTokenizer(input.readLine());
    token.nextToken()
  }

  def INT() = TOKEN().toInt

  // Read Input
  val n = INT()
  val front = for (i <- 0 until n) yield INT()
  val m = INT()
  val rear = for (i <- 0 until m) yield INT()

  println(solve(front, rear))

  def solve(front : IndexedSeq[Int], rear: IndexedSeq[Int]) = {

    var count = 0
    var best = 0
    for (a <- front) {
      for(b <- rear) {
        if (b%a == 0) {
          val ratio = b / a
          if(ratio == best) {
            count += 1
          } else if (ratio > best) {
            count = 1
            best = ratio
          }
        }
      }
    }

    count

  }

}


object B447 {

  import IO._

  def main(args: Array[String]): Unit = {
    val in = read
    val Array(k) = readInts(1)
    val cn = readInts(26)
    var res = 0
    for(i <- 0 until in.length){
      res += cn(in(i)-'a') * (i+1)
    }
    val cnSorted = cn.sorted
    for(i <- in.length+1 to in.length+k) {
      res += cnSorted(25)*i
    }
    println(res)
  }

  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

/**
 * Created by kshim on 17/07/2014.
 */
object FF_B extends App {
  def Process(s:String, k:Integer, w:List[Int]):Integer = {
    val seq = s.map(_.toLower - 'a')
    val orgScore = for(i <- 1 to s.length) yield {
      w(seq(i - 1)) * i
    }
    val maxVal = w.max
    val n = s.length
    orgScore.sum + (( (n+k)*(n+k+1) / 2 - (n * (n + 1) / 2) ) * maxVal)
  }
  val input = new Scanner(System.in)
  val s = input.nextLine().trim
  val k = input.nextInt()
  val w = (1 to 26).map(_ => input.nextInt())
  println(Process(s,k,w.toList))
}

/**
 * @author pvasilyev
 * @since 12 Jun 2016
 */
object B447 extends App {

  val s: String = scala.io.StdIn.readLine()
  val k: Int = scala.io.StdIn.readInt()
  val weights: Array[Long] = scala.io.StdIn.readLine().split(" ").map(_.toLong)

  def solve(s: String, k: Int, weights: Array[Long]) = {
    val currentFuncValue: Long = s.toCharArray.foldLeft((1L, 0L))((pair, c) => {
      val index: Int = c.toInt - 'a'.toInt
      (pair._1 + 1, pair._2 + pair._1 * weights(index))
    })._2
    val max: Long = weights.max
    var answer = currentFuncValue
    if (k > 0) {
      val addition = max * k * (s.length() + s.length() + k + 1) / 2
      answer += addition
    }
    println(answer)
  }

  solve(s, k, weights)

}

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

/**
 * Created by arseny on 13.07.14.
 */
object B extends App {

  val home = true
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val s = nextString
    val k = nextInt
    val ws = new Array[Int](26)
    var max: Int = Int.MinValue
    for (i <- 0 until 26) {
      val x = nextInt
      ws(i) = x
      if (x > max) {
        max = x
      }
    }
    var S = 0
    for (i <- 0 until s.length) {
      S += (i + 1) * ws(s(i).toInt - 'a'.toInt)
    }
    S += max * (s.length * k + (k * (k + 1)) / 2)
    out.println(S)
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

}

import java.util.StringTokenizer

object _447B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val s = next
  val k = next.toInt
  val w = (1 to 26).map(i => next.toInt).toArray
  val ans = (0 until s.length + k).map(i => if (i < s.length) (i + 1) * w(s(i) - 'a') else (i + 1) * w.max).sum
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val k = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).zipWithIndex.map{case(value, index) => ((index + 'a').toChar, value)}.toMap
  val max = data.maxBy(_._2)
  val count = str.map(data).zipWithIndex.map{case(value, index) => value * (index + 1)}.sum
  println(count + str.length * max._2 * k + (k) * (k + 1) / 2 * max._2)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val k = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).zipWithIndex.map{case(value, index) => ((index + 'a').toChar, value)}.toMap
  val max = data.maxBy(_._2)
  val count = str.map(data).zipWithIndex.map{case(value, index) => value * (index + 1)}.sum
  println(count + k * (k + 2) * max._2)
}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val r = (n / 7 to 0 by -1).find(i => (n - 7 * i) % 4 == 0)
  if (r.isEmpty)
    println(-1)
  else {
    println("4" * ((n - 7 * r.get) / 4) + "7" * r.get)
  }
}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val n = StdIn.readInt()

    for(i <- 0 to n / 4) {
      if((n - i * 4) % 7 == 0) {
        println(Array.fill(i)(4).mkString+Array.fill((n - i * 4) / 7)(7).mkString)
        return
      }
    }

    println(-1)

  }

}

object A109 {

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

  def main(args: Array[String]): Unit = {
    var Array(n) = readInts(1)
    var str = cu.ArrayBuffer.empty[Char]
    var break = false
    while(!break && n > 0) {
      if(n%7 == 0){
        str.appendAll(Array.fill(n/7)('7'))
        n = 0
      } else if(n >= 4){
        str.append('4')
        n -= 4
      } else {
        break = true
      }
    }
    if(break)
      println("-1")
    else
      println(str.sorted.mkString(""))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.StdIn

object  LuckySumOfDigitsTest{

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

    val luckyNumber = StdIn.readInt()

    // proccess
    var y= luckyNumber / 7
    var b= luckyNumber % 7
    var x= b / 4

    while ( (b % 4)!= 0 &&  y > 0 ){
      b = b + 7
      y = y - 1
      x = b / 4
    }
    if ( ( (x+y) >0) && ( ( (7 * y)  +  (4 * x)) == luckyNumber) ){
      var i=0
      while( i < (x+y) ){
        if( i < x) print(4)
        else print(7)
        i = i + 1
      }
    } else  print(-1)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val r = (0 to n / 7).find(i => (n - 7 * i) % 4 == 0)
  if (r.isEmpty)
    println(-1)
  else {
    println("4" * ((n - 7 * r.get) / 4) + "7" * r.get)
  }
}

object A109 {

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

  def main(args: Array[String]): Unit = {
    var Array(n) = readInts(1)
    var str = cu.ArrayBuffer.empty[Char]
    var break = false
    while(!break && n > 0) {
      if(n%7 == 0){
        str.appendAll(Array.fill(n/7)('7'))
        n = 0
      } else if(n%4 == 0){
        str.appendAll(Array.fill(n/4)('4'))
        n = 0
      } else if (n > 7){
        n -= 7
        str.append('7')
      } else {
        break = true
      }
    }
    if(break)
      println("-1")
    else
      println(str.sorted.mkString(""))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

    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 _1316A extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val n, m = io.read[Int]
    val scores = io.read[List, Int](n)
    val ans = m min scores.sum
    io.write(ans)
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

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

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

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

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

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

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

  implicit class IntExtensions(val x: Int) extends AnyVal {
    def nonNegative = when(x >= 0)(x)
    def ceilDiv(y: Int) = (x + y - 1)/y
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

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

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

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

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val (n,m) = (in.nextInt(),in.nextInt())
      val a = (1 to n).map{_ => in.nextInt()}.toArray
      if(n == 1){
        out.println(a(0))
      }else{
        var res = a(0)
        a.tail.foreach{ ai =>
          if(ai>=0 && res<m){
            if(ai+res>m){
              res = m
            }else{
              res += ai
            }
          }
        }
        out.println(res)
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Problem1 extends App {
    def getMaxScore(n : Int, max : Int, sumScore : Int): Int = {
        Math.min(max, sumScore)
    }
    var n = Console.readInt()
    while( n > 0){
        n = n -  1
        val arr = Console.readLine().trim.split(" ").map( x => x.toInt)
        val num = arr(0)
        val max = arr(1)
        val sum = Console.readLine().trim.split(" ").foldLeft(0)( (x, y)  => x + y.toInt )
        println(getMaxScore(num, max , sum ))

    }

}


object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, M = ni()
    val A = na(N)
    var pre = 0
    rep(N) { i =>
      if (i > 0) out.print(" ")
      val a  = A(i)
      val m = a % M
      val q = a / M
      val ans = q + (m + pre) / M
      pre = (m + pre) % M
      out.print(ans)
    }

    out.println()
  }

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

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

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

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

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

import scala.io.StdIn

object EDU48A extends App {
  val Array(n, m) = StdIn.readLine.split(' ').map(_.toInt)
  val as = StdIn.readLine.split(' ').map(_.toInt).toArray

  var remainder = 0
  var first = true
  for (i <- 0 until n) {
    val currentPage = remainder + as(i)

    if (!first)
      print(" ")
    else
      first = false

    print(currentPage/m)
    remainder = currentPage%m
  }
}

object test{
  def main(args: Array[String]){
    val t = readLine().split(" ")
    val n = Integer.parseInt(t(0))
    val m = Integer.parseInt(t(1))
    val a = readLine().split(" ")
    var sum = 0
    var page = 0
    for(i <- 0 to n-1){
      sum += a(i).toInt
      if(i != 0 )
        print(" ")
      print(sum/m)
      sum %= m
    }
  }
}

object Main {
    import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val m = nextInt
        var cur = 0
        for(i <- 1 to n) {
            val a = nextInt
            cur += a
            print(s"${cur/m} ")
            cur %= m
        }
    }

  }

}


object B499 {
  @inline def read = scala.io.StdIn.readLine

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

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

  def readWords(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken)
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val dic = Array.fill(m){
      val str = tokenizeLine
      val res = (str.nextToken, str.nextToken)
      (res._1, if(res._2.length < res._1.length) res._2 else res._1)
    }.toMap
    val lec = readWords(n)
    println(lec.map(dic).mkString(" "))
  }
}

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

  val words = List.fill(m)(readLine split ' ').map(l => l(0) -> l(1)).toMap
  println(readLine split ' ' map (w => if(w.length <= words(w).length) w else words(w)) mkString " ")
}

import java.util.StringTokenizer

object _499B 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 dict = (1 to m).map(i => {val a = next; val b = next; (a, if (a.length <= b.length) a else b)}).toMap

  val input = (1 to n).map(i => next)
  val ans = input.map(str => dict(str))
  println(ans.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val r = Range(0, m).map(_ => in.next().split(" ")).map {
    case(a) if a.head.length > a.last.length => a.head -> a.last
    case(a) => a.last -> a.head
  }.toMap
  println(in.next().split(" ").map(t => r.getOrElse(t, t)).mkString(" "))
}

import scala.collection.mutable

object P499B {
	@inline def readTokens() = scala.io.StdIn.readLine.split(" ")
	@inline def readInts() = readTokens.map(_.toInt)

	def main(args: Array[String]) {
		val Array(n, m) = readInts()
		val words = mutable.Map[String, String]()
		for (i <- 1 to m) {
			val Array(a, b) = readTokens()
			words += (a -> (if (a.length <= b.length) a else b))
		}
		val dict = words.toMap
		println(readTokens().map(dict(_)).mkString(" "))
	}
}

import scala.io.StdIn

object B extends App {
  def readIntPair() = {
    val a = StdIn.readLine() split " " map { _.toInt }
    (a(0), a(1))
  }

  def readPair() = {
    val a = StdIn.readLine() split " "
    (a(0), a(1))
  }

  val (n, m) = readIntPair()
  var dict = Map[String, String]()
  for (i <- 1 to m) {
    val (f, s) = readPair()

    val used = if (f.size <= s.size) f else s
    dict = dict + (f -> used)
  }

  val text = StdIn.readLine() split " "
  Console.println(text map dict mkString " ")
}

  object Lecture extends App {
  	val lines = io.Source.stdin.getLines.toList
  	val (nWordsLecture, nWordsLanguage) = {
  		val tokens = lines.head.split(" ")
  		(tokens(0).toInt, tokens(1).toInt)
  	}

  	var map = Map[String, String]()

  	for (line <- lines.tail.init) {
  		val tokens = line.split(" ")
  		map = map + (tokens(0) -> tokens(1))
  	}

  	val lecture = (for (word <- lines.last.split(" ").toList) yield if (word.length <= map(word).length) word else map(word)).mkString(" ")

  	println(lecture)

  }

object Main extends App {

  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val lang: Map[String,String] = (1 to m).map({ _ =>
    val Array(from, to) = readLine.split(" ", 2)
    (from, to)
  }).toMap
  println(readLine.split(" ").map({s =>
    val s1 = lang.getOrElse(s, "")
    if(s1.size < s.size) s1 else s
  }).mkString(" "))

}

import java.io._
import scala.collection.mutable

object Problem499 extends App {
  val problem = new Problem499(
    new InputStreamReader(System.in),
    new OutputStreamWriter(System.out)
  )

  problem.run()
}

class Problem499(input: Reader, output: Writer) {
  private val tokenizer = new StreamTokenizer(new BufferedReader(input))

  def run(): Unit = {
    tokenizer.eolIsSignificant(true)

    var n = readInt()
    var m = readInt()
    tokenizer.nextToken()

    val dictionary = new mutable.HashMap[String, String]()
    while (m > 0) {
      dictionary += addTranslation()

      m -= 1
    }

    while (n > 0) {
      translate(dictionary)

      n -= 1
    }

    output.flush()
  }

  private def translate(dictionary: mutable.Map[String, String]): Unit = {
    var isFirst = true

    while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
      if (isFirst) {
        isFirst = false
      } else {
        output.write(' ')
      }

      val translation = dictionary.get(tokenizer.sval)
      output.write(translation getOrElse " ")
    }
  }

  private def addTranslation(): (String, String) = {
    if (tokenizer.nextToken() != StreamTokenizer.TT_WORD) {
      throw new RuntimeException("Word expected")
    }

    val original = tokenizer.sval
    var translation = original

    while (tokenizer.nextToken() == StreamTokenizer.TT_WORD) {
      if (translation.length() > tokenizer.sval.length()) {
        translation = tokenizer.sval
      }
    }

    original -> translation
  }

  private def readInt(): Int = {
    if (tokenizer.nextToken() != StreamTokenizer.TT_NUMBER) {
      throw new RuntimeException("Integer expected")
    }

    tokenizer.nval.toInt
  }
}

import java.util.StringTokenizer

object _499B 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 dict = (1 to m).map(i => {val a = next; val b = next; (a, if (a.length < b.length) a else b)}).toMap

  val input = (1 to n).map(i => next)
  val ans = input.map(str => dict(str))
  println(ans.mkString(" "))
}

  object Lecture extends App {
  	val lines = io.Source.stdin.getLines.toList
  	val (nWordsLecture, nWordsLanguage) = {
  		val tokens = lines.head.split(" ")
  		(tokens(0).toInt, tokens(1).toInt)
  	}

  	var map = Map[String, String]()

  	for (line <- lines.tail.init) {
  		val tokens = line.split(" ")
  		map = map + (tokens(0) -> tokens(1))
  	}

  	val lecture = (for (word <- lines.last.split(" ").toList) yield if (word.compareTo(map(word)) <= 0) word else map(word)).mkString(" ")

  	println(lecture)

  }

object Main extends App {

  val Array(n, m) = readLine.split(" ").map(_.toInt)
  val lang: Map[String,String] = (1 to m).map({ _ =>
    val Array(from, to) = readLine.split(" ", 2)
    (from, to)
  }).toMap
  println(readLine.split(" ").map({s =>
    val s1 = lang.getOrElse(s, "")
    if(s1.size > s.size) s else s1
  }).mkString(" "))

}


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

object B {

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

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

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

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

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

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

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  def solve: Int = {
    val n = nextInt
    val x1 = nextLong
    val x2 = nextLong
    val arr = new Array[(Long, Long)](n)
    for (i <- 0 until n) {
      arr(i) = (nextLong, nextLong)
    }
    val left = new Array[(Long, Long)](n)
    val right = new MultiTreeSet[Long]
    for (i <- 0 until n) {
      left(i) = (arr(i)._1 * x1 + arr(i)._2, arr(i)._1 * x2 + arr(i)._2)
      right.add(arr(i)._1 * x2 + arr(i)._2)
    }
    val sorted = left.sorted
    var i = 0
    while (i < n) {
      var j = i
      var y1 = sorted(i)._2
      while (j < n && sorted(j)._1 == sorted(i)._1) {
        y1 = Math.max(y1, sorted(j)._2)
        right.remove(sorted(j)._2)
        j += 1
      }
      if (right.map.isEmpty) {
        out.print("NO")
        return 0
      }
      val min = right.map.firstKey()
      val max = right.map.lastKey()
      if (y1 > min) {
        out.print("YES")
        return 0
      }
      i = j
    }
    out.print("NO")
    return 0
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val Array(x1, x2) = in.next().split(' ').map(_.toLong)
  val data = (1 to n).map { _ =>
    val Array(a, b) = in.next().split(' ').map(_.toLong)
    (a * x1 + b, a * x2 + b)
  }.sorted
  if (data.map(_._2).sliding(2).exists(t => t.last < t.head)) {
    println("YES")
  } else {
    println("NO")
  }

}

import scala.collection._

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 Array(x1, x2) = readLongs(2)

  val _by2 = Array.ofDim[(Long, Long)](n)
  val by1 = new mutable.TreeSet[(Long, Long)]()
  //val by2 = new mutable.TreeSet[(Long, Long)]()(Ordering.by { case (a, b) => (b, a) })

  for (i <- 0 until n) {
    val Array(k, b) = readInts(2)
    val l = (k * x1 + b, k * x2 + b)
    _by2(i) = l
    by1 += l
  }

  val by2 = _by2.sortBy(l => (l._2, l._1))

  for (l <- by2) {
    by1 -= l
    if (by1.nonEmpty && l._1 > by1.head._1) {
      println("YES")
      System.exit(0)
    }
  }

  println("NO")
}

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

object _593B extends CodeForcesApp {
  import CodeForcesApp._
  override type Result = Boolean

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val (x1, x2) = (nextLong(), nextLong())
    val lines = Seq.fill(n)((nextLong(), nextLong()))

    def eval(x: Double)(line: (Long, Long)): Double = {
      val (k, b) = line
      k*x + b
    }
    val a = lines.sortBy(eval(x1 + 1e-9))
    val b = lines.sortBy(eval(x2 - 1e-9))
    a != b
  }

  override def format(result: Result) = if (result) "YES" else "NO"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

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

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

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

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

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

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

object _593B extends CodeForcesApp {
  override type Result = Boolean

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val (x1, x2) = (nextLong(), nextLong())
    val lines = Seq.fill(n)((nextLong(), nextLong()))
    def eval(x: Double)(line: (Long, Long)): Double = {
      val (k, b) = line
      k*x + b
    }
    val a = lines.sortBy(eval(x1 + 1e-9))
    val b = lines.sortBy(eval(x2 - 1e-9))
    debug(a, b)
    a != b
  }

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

import scala.io.Codec

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

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

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

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

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

//package round329.b

import java.util.Scanner

object Main extends App {

  case class Line(k: Int, b: Int) {
    def compute(x: Int): Long = k.toLong * x.toLong + b.toLong
  }

  val sc = new Scanner(System.in)

  val n = sc.nextInt
  val (x1, x2) = (sc.nextInt, sc.nextInt)

  val lines = (0 until n).map(_ => Line(sc.nextInt, sc.nextInt)).toArray

  val yX1 = lines.view.map { line => line.compute(x1) }.zipWithIndex.sortBy(-_._1).toArray
  val yX2 = lines.view.map { line => line.compute(x2) }.zipWithIndex.sortBy(-_._1).toArray

//  println(yX1.toList)
//  println(yX2.toList)

  var yX2_idx = 0

  (0 until n).foreach { i =>

    val (yX1L1, idx1) = yX1(i)
    val line1 = lines(idx1)
    val yX2L1 = line1.compute(x2)

    while(yX2_idx < n && yX2(yX2_idx)._1 > yX2L1) {
      val (yX2L2, idx2) = yX2(yX2_idx)
      val line2 = lines(idx2)
      val yX1L2 = line2.compute(x1)
      if(yX1L1 > yX1L2) {
        println("YES")
        System.exit(0)
      }
      yX2_idx += 1
    }
  }

  println("NO")
}

//package round329.b

import java.util.Scanner

object Main extends App {

  case class Line(k: Int, b: Int) {
    def compute(x: Int): Long = k.toLong * x.toLong + b.toLong
  }

  val sc = new Scanner(System.in)

  val n = sc.nextInt
  val (x1, x2) = (sc.nextInt, sc.nextInt)

  val lines = (0 until n).map(_ => Line(sc.nextInt, sc.nextInt)).toArray

  val yX1 = lines.map { line => line.compute(x1) }.zipWithIndex.sortBy(-_._1)
  val yX2 = lines.map { line => line.compute(x2) }.zipWithIndex.sortBy(-_._1)

  var yX2_idx = 0

  (0 until n).foreach { i =>

    val (yX1L1, idx1) = yX1(i)
    val line1 = lines(idx1)
    val yX2L1 = line1.compute(x2)

    while(yX2_idx < n && yX2(yX2_idx)._1 < yX2L1) {
      val (yX2L2, idx2) = yX2(yX2_idx)
      val line2 = lines(idx2)
      val yX1L2 = line2.compute(x1)
      if(yX1L1 < yX1L2) {
        println("YES")
        System.exit(0)
      }
      yX2_idx += 1
    }
  }

  println("NO")
}

import scala.collection._

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

  case class Line(y1: Long, y2: Long)

  val Array(n) = readInts(1)
  val Array(x1, x2) = readInts(2)

  val _by1 = Array.ofDim[Line](n)
  val by2 = new mutable.TreeSet[Line]()(Ordering.by(l => (l.y2, l.y1)))

  for (i <- 0 until n) {
    val Array(k, b) = readInts(2)
    val l = Line(k * x1 + b, k * x2 + b)
    _by1(i) = l
    by2 += l
  }

  val by1 = _by1.sortBy(l => (l.y1, l.y2))

  for (l <- by1) {
    by2 -= l
    if (by2.nonEmpty && l.y2 > by2.head.y2) {
      println("YES")
      System.exit(0)
    }
  }

  println("NO")
}

import scala.collection._

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

  case class Line(y1: Long, y2: Long)

  val Array(n) = readInts(1)
  val Array(x1, x2) = readLongs(2)

  val _by2 = Array.ofDim[(Long, Long)](n)
  val by1 = new mutable.TreeSet[(Long, Long)]()

  for (i <- 0 until n) {
    val Array(k, b) = readInts(2)
    val l = (k * x1 + b, k * x2 + b)
    _by2(i) = l
    by1 += l
  }

  val by2 = _by2.sortBy(l => l._2)

  for (l <- by2) {
    by1 -= l
    if (by1.nonEmpty && l._1 > by1.head._1) {
      println("YES")
      System.exit(0)
    }
  }

  println("NO")
}

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

object _593B extends CodeForcesApp {
  import CodeForcesApp._
  override type Result = Boolean

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val (x1, x2) = (nextLong(), nextLong())
    val lines = Seq.fill(n)((nextLong(), nextLong()))
    def eval(x: Double)(line: (Long, Long)): Double = {
      val (k, b) = line
      k*x + b
    }
    val a = lines.sortBy(eval(x1 + 1e-3))
    val b = lines.sortBy(eval(x2 - 1e-3))
    //debug(a, b, (a map (eval(x1 + 1e-3))).toList, (b map (eval(x2 - 1e-3))).toList)
    a != b
  }

  override def format(result: Result) = if (result) "YES" else "NO"
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

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

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

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

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

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


import scala.io.StdIn

object LettersRearranging extends App {

  val t = StdIn.readLine().toInt
  for {
    _ <- 1 to t
  } println(findSol(StdIn.readLine()))

  def findSol(s: String): String = {
    if (s.length == 1) return "-1"

    val zip = s.zipWithIndex

    val dislen = zip.map(_._1).distinct.length

    if (dislen == 1) return "-1"

    val first = zip.head

    val x = zip.find(x => x._1 != first._1).get
    val last = zip.last

    val newzip = zip.updated(zip.length - 1, x).updated(x._2, last)

    newzip.map(_._1).mkString
  }
}

import scala.io.StdIn

object T1093B {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()

    for (_<-1 to n){
      val s = StdIn.readLine()
      val st = s.toCharArray.toSet
      if (st.size==1){
        println(-1)
      }else{
        println(s.toCharArray.sorted.mkString)
      }
    }
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    REP(ni()) { _ =>
      val S = ns()
      val grouped = S.groupBy(identity)
      if (grouped.size == 1) out.println(-1)
      else {
        out.println(grouped.values.mkString)
      }
    }
  }

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

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

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

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

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

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

object b1093 {
  def main(args: Array[String]): Unit = {
    scala.io.Source.stdin.getLines().drop(1).map { i: String => val j = i.sorted; if (j.head == j.last) "-1" else j } foreach println
  }
}

object EDU_56_B {
  def solve(t: Int, ss: Seq[String]): Seq[String] = ss map { s =>
    val letters = s.toSet
    if(letters.size == 1) "-1"
    else s.sorted
  }

  // Specify Input and Output formats here:
  def formatIn(i: Input) = (i.int, i.getLines)
  def formatOut(out: Seq[String]): String = out.mkString("\n")

//     ~~~ Boilerplate & utility methods that don't change ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  def main(args: Array[String]) = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // Remember to call nextLine to advance past the newline character (if required) before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq = collect(_.toInt)
    def doubleSeq = collect(_.toDouble)
    def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty else sc.nextLine +: getLines
    def solveVal = (solve _).tupled(formatIn(this))
    def solveStr = formatOut(solveVal)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
  val modulo = 1000000007

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }
}

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.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(t) = readInts(1)

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  for (_ <- 1 to t) {
    val s = readLine
    if (s.forall(_ == s.head)) println(-1)
    else println(s.sorted)
  }

  Console.flush
}


import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn
import scala.util.control.Breaks

object Main {
  def main(args: Array[String]) {
    val Array(n, x1, y1, x2, y2) = StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)({
      val Array(x, y) = StdIn.readLine().split(" ").map(_.toLong)
      (x, y)
    })
    val a1 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x1) * (x - x1) + (y - y1) * (y - y1), i)).sorted
    val a2 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x2) * (x - x2) + (y - y2) * (y - y2), i)).sorted
    val s1 = mutable.HashSet[Int]()
    var ans = Long.MaxValue
    val s2 = mutable.HashSet[Int]()
    for ((r2, i2) <- a2) {
      s2.add(i2)
      if (s2.size == n) ans = math.min(ans, r2)
    }
    for ((r1, i1) <- a1) {
      s1.add(i1)
      val s2 = s1.clone()
      for ((r2, i2) <- a2) {
        s2.add(i2)
        if (s2.size == n) ans = math.min(ans, r1 + r2)
      }
      if (s1.size == n) ans = math.min(ans, r1)
    }
    println(ans)
  }
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn
import scala.util.control.Breaks

object Main {
  def main(args: Array[String]) {
    val Array(__n, x1, y1, x2, y2) = StdIn.readLine().split(" ").map(_.toLong)
    val _n = __n.toInt
    val a = Array.fill(_n)({
      val Array(x, y) = StdIn.readLine().split(" ").map(_.toLong)
      (x, y)
    }) ++ Array((x1, y1), (x2, y2))
    val n = _n + 2
    val a1 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x1) * (x - x1) + (y - y1) * (y - y1), i)).sorted.toList
    val a2 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x2) * (x - x2) + (y - y2) * (y - y2), i)).sorted.toList

    def f(xs: List[(Long, Int)], s: Set[Int], acc: Long): Long = {
      def g(xs: List[(Long, Int)], s: Set[Int]): Long = {
        xs match {
          case (r, i)::ys => {
            val t = s + i
            if (t.size == n) r else g(ys, t)
          }
        }
      }
      xs match {
        case (r, i)::ys => {
          val t = s + i
          if (t.size == n) math.min(r, acc) else f(ys, t, math.min(acc, r + g(a2, t)))
        }
      }
    }
    println(f(a1, Set[Int](), Long.MaxValue))
  }
}

import math.pow
import math.max

object C340{
  def dist(x1: Long, x2: Long, y1:Long, y2: Long): Double ={
    pow(x1 - x2, 2) + pow(y1 - y2, 2)
  }
  def main(args: Array[String]){

    val Array(n, x1, y1, x2, y2)=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val flowers = (1 to n).map(x => scala.io.StdIn.readLine.split(" ").map(_.toInt)).toList
    val dists = (0.0, 0.0) :: flowers.map(x => (dist(x(0), x1, x(1), y1), dist(x(0), x2, x(1), y2))).sortBy(_._1)
    var temp = 0.0
    val maxy = dists.reverse.map(b => {
      val tt = temp + b._1
      temp = max(b._2, temp)
      tt
    })
    print(maxy.min.toLong)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)
  val data = (1l to n).map { _ =>
    val Array(x3, y3) = in.next().split(' ').map(_.toLong)
    ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3), (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))
  }
  val first = 0l :: data.map(_._1).toList
  println(first.foldLeft(Long.MaxValue) {
    case (acc, r1) =>
      val filtered = data.filter(_._1 > r1)
      if (filtered.isEmpty)
        Math.min(acc, r1)
      else
        Math.min(acc, r1 + filtered.maxBy(_._2)._2)
  })

}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.StdIn
import scala.util.control.Breaks

object Main {
  def main(args: Array[String]) {
    val Array(n, x1, y1, x2, y2) = StdIn.readLine().split(" ").map(_.toInt)
    val a = Array.fill(n)({
      val Array(x, y) = StdIn.readLine().split(" ").map(_.toLong)
      (x, y)
    })
    val a1 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x1) * (x - x1) + (y - y1) * (y - y1), i)).sorted
    val a2 = (for (((x, y), i) <- a.zipWithIndex) yield ((x - x2) * (x - x2) + (y - y2) * (y - y2), i)).sorted
    val s1 = mutable.HashSet[Int]()
    var ans = Long.MaxValue
    val s2 = mutable.HashSet[Int]()
    for ((r2, i2) <- a2) {
      s2.add(i2)
      if (s2.size == n) ans = math.min(ans, r2)
    }
    for ((r1, i1) <- a1) {
      s1.add(i1)
      val s2 = s1.clone()
      for ((r2, i2) <- a2) {
        s2.add(i2)
        if (s2.size == n) ans = math.min(ans, r1 + r2)
      }
    }
    println(ans)
  }
}

import math.pow
import math.max

object C340{
  def dist(x1: Int, x2: Int, y1:Int, y2: Int): Double ={
    pow(x1 - x2, 2) + pow(y1 - y2, 2)
  }
  def main(args: Array[String]){

    val Array(n, x1, y1, x2, y2)=scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val flowers = (1 to n).map(x => scala.io.StdIn.readLine.split(" ").map(_.toInt)).toList
    val dists = flowers.map(x => (dist(x(0), x1, x(1), y1), dist(x(0), x2, x(1), y2))).sortBy(_._1)
    var temp = 0.0
    val maxy = dists.reverse.map(b => {
      val tt = temp + b._1
      temp = max(b._2, temp)
      tt
    })
    print(maxy.min.toInt)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, x1, y1, x2, y2) = in.next().split(' ').map(_.toLong)
  val data = (1l to n).map { _ =>
    val Array(x3, y3) = in.next().split(' ').map(_.toLong)
    ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3), (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))
  }
  val first = data.map(_._1)
  println(first.foldLeft(Long.MaxValue) {
    case (acc, r1) =>
      val filtered = data.filter(_._1 > r1)
      if (filtered.isEmpty)
        Math.min(acc, r1)
      else
        Math.min(acc, r1 + filtered.maxBy(_._2)._2)
  })

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, x1, y1, x2, y2) = in.next().split(' ').map(_.toInt)
  val data = (1 to n).map { _ =>
    val Array(x3, y3) = in.next().split(' ').map(_.toInt)
    ((x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3), (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))
  }
  val first = data.map(_._1)
  println(first.foldLeft(Int.MaxValue) {
    case (acc, r1) =>
      val filtered = data.filter(_._1 > r1)
      if (filtered.isEmpty)
        Math.min(acc, r1)
      else
        Math.min(acc, r1 + filtered.maxBy(_._2)._2)
  })

}


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

import scala.collection.mutable

object C {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def query(p: Int) = ???

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

  private val MOD = (1e9 + 7).toInt

  def binomialCoefficient(n: Int, k: Int): Long = {
    var c = 1L
    for (i <- 0 until k) {
      val x = (c * (n - i)) / (i + 1)
    }
    return c
  }

  def solve: Int = {
    val k = nextInt
    val c = new Array[Int](k)
    for (i <- 0 until k) {
      c(i) = nextInt
    }
    val coeff = new Array[Array[Long]](1010)
    for (i <- 0 until coeff.length)
      coeff(i) = new Array[Long](1010)
    coeff(0)(0) = 1
    for (i <- 1 until 1010) {
      coeff(i)(0) = 1
      for (j <- 1 to i) {
        coeff(i)(j) = (coeff(i - 1)(j) + coeff(i - 1)(j - 1)) % MOD
      }
    }
    val ans = new Array[Long](k)
    ans(0) = 1
    var sum = c(0)
    for (i <- 1 until k) {
      ans(i) = ((ans(i - 1) % MOD) * coeff(sum + c(i) - 1)(sum) % MOD) % MOD
      sum += c(i)
    }
    out.println(ans(k - 1))
    return 0
  }
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

object CF553A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

  def next():String = {
      while (!st.hasMoreTokens()){
        val currentLine = reader.readLine
            st=new StringTokenizer(currentLine)
      }
      return st.nextToken
  }

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

  def nextLong():Long = {
      return next.toLong
  }
  def nextDouble:Double = {
          return next.toDouble
      }
  }
  val MOD = 1000000007L

  def main(args: Array[String]): Unit = {
    val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
    var in = new InputReader(System.in)
    var out = System.out
    if ( !isOnlineJudge ) {
      in = new InputReader(new FileInputStream("input.txt"))
      out = new PrintStream(new FileOutputStream("output.txt"))
    }
    solve(in,out)
  }

  def solve(in: InputReader, out: PrintStream): Unit = {
    val n = in.nextInt()
    val a = List.fill(n)(in.nextLong()).reverse
    val dim = sum(a).toInt
    val comb = Array.ofDim[Long](dim, dim)
    for(i <- 0 until dim) {
     comb(0)(i) = 1
     comb(i)(0) = 1
    }
    comb(0)(0) = 0
    for(num <- 1 until dim)
      for(k <- 1 to num) comb(k)(num) = (comb(k-1)(num-1) + comb(k)(num-1)) % MOD
    out.println(count(a,comb))
  }

//  def count(a: List[Long]): Long = {
//  }

  def sum(arg: List[Long]): Long = {
   return arg.foldLeft(0L)((s,x) => s + x)
  }

  def count(a: List[Long], comb: Array[Array[Long]]): Long = {
    if ( a.length == 1) return 1
    val k = a.head - 1
    val n = sum(a) - 1
    val combi = comb(k.toInt)(n.toInt)
    //printf("k = %d, n = %d, combi(k,n) = %d\n", k,n, comb(k.toInt)(n.toInt))
    return (count(a.tail, comb) * combi ) % MOD
  }

}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

object CF553A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

  def next():String = {
      while (!st.hasMoreTokens()){
        val currentLine = reader.readLine
            st=new StringTokenizer(currentLine)
      }
      return st.nextToken
  }

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

  def nextLong():Long = {
      return next.toLong
  }
  def nextDouble:Double = {
          return next.toDouble
      }
  }
  val MOD = 1000000007L

  def main(args: Array[String]): Unit = {
    val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
    var in = new InputReader(System.in)
    var out = System.out
    if ( !isOnlineJudge ) {
      in = new InputReader(new FileInputStream("input.txt"))
      out = new PrintStream(new FileOutputStream("output.txt"))
    }
    solve(in,out)
  }

  def solve(in: InputReader, out: PrintStream): Unit = {
    val a = List.fill(in.nextInt())(in.nextInt()).reverse
    val dim = sum(a)
    val comb = Array.ofDim[Long](dim, dim)
    for(i <- 0 until dim) {
     comb(0)(i) = 1
     comb(i)(0) = 0
    }
    comb(0)(0) = 1
    for(num <- 1 until dim)
      for(k <- 1 to num) comb(k)(num) = (comb(k-1)(num-1) + comb(k)(num-1)) % MOD
    out.println(count(a,comb))
  }

  def sum(arg: List[Int]): Int = {
   return arg.foldLeft(0)((s,x) => s + x)
  }

  def count(a: List[Int], comb: Array[Array[Long]]): Long = {
    if ( a.length == 1) return 1
    return (count(a.tail, comb) * comb(a.head- 1)(sum(a)-1) ) % MOD
  }

}

import java.util.StringTokenizer

object _553A extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val mod = 1000000007L
  var choose = Array.fill(1111, 1111)(0L)
  for (i <- 0 until choose.length) {
    choose(i)(0) = 1
    choose(i)(i) = 1
    for (j <- 1 until i)
      choose(i)(j) = (choose(i - 1)(j) + choose(i - 1)(j - 1)) % mod
  }

  val k = next.toInt
  val a = (1 to k).map(i => next.toInt)
  var sum = a.sum
  var ans = 1L
  var i = k - 1
  while(i >= 0) {
    ans = (ans * choose(sum - 1)(a(i) - 1)) % mod
    sum -= a(i)
    i -= 1
  }

  println(ans)
}

import scala.io.Source

object Solution extends App {
  val mod = 1000000007
  val maxN = 1010
  val in = Source.stdin.getLines()
  val comb = Array.ofDim[Long](maxN, maxN)
  comb(0)(0) = 1
  (1 until maxN).foreach { i =>
    comb(i)(0) = 1
    (1 to i).foreach { j =>
      comb(i)(j) = (comb(i - 1)(j) + comb(i - 1)(j - 1)) % mod
    }
  }
  val k = in.next().toInt
  val color = (1 to k).map(_ => in.next().toInt)
  val r = (0 until k).foldLeft(1l, 0) {
    case ((res, total), i) =>
      val nRes = res * comb(total + color(i) - 1)(color(i)- 1) % mod
      (nRes, total + color(i))
  }
  println(r._1)
}

object A{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val m=1000000007L
    val mI=m.toInt
    val C=Array.ofDim[Int](1001,1001)
    for(i<-0 to 1000){
      C(i)(0)=1
      C(i)(i)=1
      for(j<-1 until i){
        C(i)(j)=(C(i-1)(j)+C(i-1)(j-1))%mI
      }
    }

    val k=nextInt

    var sum=0
    var ans=1L
    for(i<-0 until k){
      val c=nextInt
      sum+=c
      ans=(ans*C(sum-1)(c-1))%m
    }
    out.println(ans)
    //code ends here
    out.flush
    out.close
  }
}

object _554C extends CodeForcesApp {
  import CodeForcesApp._, scala.annotation.tailrec, scala.collection.mutable

  override type Input = List[Int]
  override type Output = BigInt

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    def f(balls: Int, colors: List[Int]): BigInt = colors match {
      case Nil => 1
      case (c1 :: cs) => (c(balls - 1, c1 - 1) * f(balls - c1, cs)) % modulus
    }
    f(input.sum, input.reverse)
  }

  lazy val c: (Int, Int) ==> BigInt = Memo {
    case (_, 0) => 1
    case (n, r) if r > n/2 => c(n, n - r)
    case (n, r) => c(n - 1, r - 1) + c(n - 1, r)
  }

  override def format(result: Output) = super.format(result)
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  import CodeForcesApp._
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
}
/********************************[ lib ]************************************/
object CodeForcesApp {
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = collection.mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type ==>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /********************************[ constants ]************************************/
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  val modulus = 1000000007
}

import java.io.InputStream
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.PrintWriter
import java.io.FileInputStream
import java.io.PrintStream
import java.io.FileOutputStream

object CF553A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

  def next():String = {
      while (!st.hasMoreTokens()){
        val currentLine = reader.readLine
            st=new StringTokenizer(currentLine)
      }
      return st.nextToken
  }

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

  def nextLong():Long = {
      return next.toLong
  }
  def nextDouble:Double = {
          return next.toDouble
      }
  }
  val MOD = 1000000007L

  def main(args: Array[String]): Unit = {
    val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
    var in = new InputReader(System.in)
    var out = System.out
    if ( !isOnlineJudge ) {
      in = new InputReader(new FileInputStream("input.txt"))
      out = new PrintStream(new FileOutputStream("output.txt"))
    }
    solve(in,out)
  }

  def solve(in: InputReader, out: PrintStream): Unit = {
    val n = in.nextInt()
    val a = List.fill(n)(in.nextLong()).reverse
    val dim = sum(a).toInt
    val comb = Array.ofDim[Long](dim, dim)
    for(i <- 0 until dim) {
     comb(0)(i) = 1
     comb(i)(0) = 1
    }
    comb(0)(0) = 0
    for(num <- 1 until dim)
      for(k <- 1 to num) comb(k)(num) = comb(k-1)(num-1) + comb(k)(num-1)
    out.println(count(a,comb))
  }

//  def count(a: List[Long]): Long = {
//  }

  def sum(arg: List[Long]): Long = {
   return arg.foldLeft(0L)((s,x) => s + x)
  }

  def count(a: List[Long], comb: Array[Array[Long]]): Long = {
    if ( a.length == 1) return 1
    val k = a.head - 1
    val n = sum(a) - 1
    val combi = comb(k.toInt)(n.toInt)
    //printf("k = %d, n = %d, combi(k,n) = %d\n", k,n, comb(k.toInt)(n.toInt))
    return (count(a.tail, comb) * combi ) % MOD
  }

}

object A{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val m=1000000007L
    val mI=m.toInt
    val C=Array.ofDim[Int](1001,1001)
    for(i<-0 to 1000){
      C(i)(0)=1
      C(i)(i)=1
      for(j<-1 until i){
        C(i)(j)=(C(i-1)(j)+C(i-1)(j-1))%mI
      }
    }

    val k=nextInt

    var sum=0
    val c=Array.ofDim[Int](k)
    for(i<-0 until k){c(i)=nextInt;sum+=c(i)}
    val dp=Array.ofDim[Long](k,sum)
    var cs=c(0)
    for(j<-cs-1 until sum){
      dp(0)(j)=C(j)(cs-1)
    }

    for(i<-1 until k){
      cs+=c(i)
      for(j<-cs-1 until sum){
        for(l<-cs-1-c(i) until j){
          dp(i)(j)=(dp(i)(j)+dp(i-1)(l)*C(j-(cs-c(i)))(c(i)-1))
        }
      }
    }
    out.println(dp(k-1)(sum-1))
    //code ends here
    out.flush
    out.close
  }
}


import java.util.Scanner

object C extends App {
  val sc = new Scanner(System.in)

  val (n, k) = {
    val string = sc.nextLine()
    val spaceIndex = string.indexOf(' ')
    (string.take(spaceIndex).toInt, string.drop(spaceIndex + 1).toInt)
  }

  val s = sc.nextLine()

  val (_, pairs) = s.zipWithIndex.foldLeft((Stack(Nil), Seq.empty[Pair])) {
    case ((stack, pairz), ('(', openingIndex)) =>
      (stack.push(openingIndex), pairz)
    case ((stack, pairz), (')', closingIndex)) =>
      val (openIndex, remainingStack) = stack.pop()
      (remainingStack, Pair(openIndex, closingIndex) +: pairz)
  }

  val pairsToDrop = (n - k) / 2

  val idsToDrop = pairs.take(pairsToDrop).flatMap(p => Seq(p.l, p.r)).toSet

  val sb = StringBuilder.newBuilder

  s.zipWithIndex.foreach { case (char, index) =>
    if (!idsToDrop.contains(index)) sb.append(char)
  }

  println(sb.toString())

  case class Pair(l: Int, r: Int)

  case class Stack(underlying: List[Int]) {
    def pop(): (Int, Stack) = (underlying.head, Stack(underlying.tail))
    def push(v: Int): Stack = Stack(v :: underlying)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = ni()
    val S = ns(N)

    var stack = 0 // Sに対して+1index
    val last = Array.fill[Int](N / 2 + 1)(-1)
    last(0) = 0
    val pair = Array.ofDim[Int](N) // '('のついになる')'がどこにあるか
    // ループするのはstackのindex
    rep(N, 1) { i =>
      val c = S(i - 1)
      stack += (if (c == '(') 1 else -1)
      if (c == ')' && last(stack) != -1) {
        pair(last(stack)) = i - 1 // stackのindexからSのindexにする
      }
      last(stack) = i
    }

    def remove(i: Int, cnt: Int): Unit = {
      if (cnt == 0) ()
      else if (S(i) == '(') {
        S(i) = 0
        S(pair(i)) = 0
        remove(i + 1, cnt - 1)
      } else {
        remove(i + 1, cnt)
      }
    }

    // 対になるかっこを必要分消す
    remove(0, (N - K) / 2)

    rep(N) { i =>
      if (S(i) != 0) out.print(S(i))
    }

    out.println()
  }

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

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

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

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

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

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_504_C {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa2)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val k = l1.int
    val ss = readLine.string.toCharArray()

    var toRemove = n - k
    debug(s"toRemove=$toRemove")
    var toRemoveCl = 0
    var toClose = 0
    var res = new Array[Char](k)
    var resInd = 0
    for (i <- 0 until n) {
      val ch = ss(i)

      if (ch == '(') {
        if (toRemove > 0) {
          toRemove -= 2
          toRemoveCl += 1
        } else {
          res(resInd) = ch; resInd += 1
          toClose += 1
        }
      } else {
        if (toRemoveCl > 0 && toClose == 0) {
          toRemoveCl -= 1
        } else {
          res(resInd) = ch; resInd += 1
          toClose -= 1
        }
      }
      debug(s"d $ch toRemove=$toRemove toRemoveCl=$toRemoveCl toClose=$toClose")
    }
    outLn( new String(res) )

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
6 4
()(())
"""

val sa2 = """
8 8
(()(()))
"""

val t1 = """
12 8
(()()(())())
"""

}

}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = ni()
    val S = ns(N)

    val D = Array.ofDim[Int](N  + 1)
    rep(N) { i =>
      D(i + 1) = D(i) + (if(S(i) == '(') 1 else -1)
    }

    def show(l: Int, len: Int): Unit = {
      rep(len, l) { i =>
        out.print(S(i))
      }
    }

    def show2(i: Int, len: Int, k: Int): Unit = {
      val pre = Array.fill[Int](len)(-1)
      rep(len) { j =>
        val l = i + j
        val p = pre(D(l + 1)) // pre
        if (p != -1 && l - p == k) {
          show(p + 1, k)
          return
        } else {
          pre(D(l + 1)) = l
        }
      }
    }

    var k = K
    var zero = 0
    var i = 1
    while (k > 0) {
      if (D(i) == 0) {
        val len = i - zero
        if (len <= k) {
          show(zero, i - zero)
          k -= len
          zero = i
        } else {
          show2(zero, i - zero, k)
          k = 0
        }
      }
      i += 1
    }

    out.println()
  }

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

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

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

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

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

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = ni()
    val S = ns()

    val stack = Array.ofDim[Int](N + 1) // Sとはindexが1ずれてる
    rep(N) { i =>
      stack(i + 1) = stack(i) + (if (S(i) == '(') 1 else -1)
    }

    def show(i: Int, len: Int): Int = {
      out.print(S.substring(i, i + len))
      len
    }

    /**
      * @param l 左の0
      * @param r 右の0
      */
    def find(l: Int, r: Int, k: Int): Int = {
      val last = Array.fill[Int](N / 2 + 1)(-1)
      var found: Int = -1
      rep(r - l + 1) { i =>
        val j = l + i
        val d = stack(j)
        if (last(d) != -1 && j - last(d) == k) {
          found = last(d)
        }
        last(d) = j
      }
      found
    }

    var k = K
    var prev = 0
    var i = 1
    while (k > 0) {
      if (stack(i) == 0) {
        val len = i - prev
        if (k >= len) {
          // stack上で0-0 == 左のindex+1からはじめて右のindexまででちょうどスタックが0になる
          // stack-1でちょうどSのindexと同じになる
          k -= show(prev, len)
        } else {
          val l = find(prev, i, k)
          k -= show(l, k)
        }
        prev = i
      }
      i += 1
    }

    out.println()
  }

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

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

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

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

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