You received a notebook which is called Death Note. This notebook has infinite number of pages. A rule is written on the last page (huh) of this notebook. It says: "You have to write names in this notebook during $$$n$$$ consecutive days. During the $$$i$$$-th day you have to write exactly $$$a_i$$$ names.". You got scared (of course you got scared, who wouldn't get scared if he just receive a notebook which is named Death Note with a some strange rule written in it?).Of course, you decided to follow this rule. When you calmed down, you came up with a strategy how you will write names in the notebook. You have calculated that each page of the notebook can contain exactly $$$m$$$ names. You will start writing names from the first page. You will write names on the current page as long as the limit on the number of names on this page is not exceeded. When the current page is over, you turn the page. Note that you always turn the page when it ends, it doesn't matter if it is the last day or not. If after some day the current page still can hold at least one name, during the next day you will continue writing the names from the current page.Now you are interested in the following question: how many times will you turn the page during each day? You are interested in the number of pages you will turn each day from $$$1$$$ to $$$n$$$.

The first line of the input contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of days you will write names in the notebook and the number of names which can be written on each page of the notebook. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ means the number of names you will write in the notebook during the $$$i$$$-th day.

Print exactly $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$, where $$$t_i$$$ is the number of times you will turn the page during the $$$i$$$-th day.

NoteIn the first example pages of the Death Note will look like this $$$[1, 1, 1, 2, 2], [2, 2, 2, 2, 2], [3, 3, 3, 3, 3], [3, 3, 3, 3]$$$. Each number of the array describes during which day name on the corresponding position will be written. It is easy to see that you should turn the first and the second page during the second day and the third page during the third day.

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


Cowboy Vlad has a birthday today! There are $$$n$$$ children who came to the celebration. In order to greet Vlad, the children decided to form a circle around him. Among the children who came, there are both tall and low, so if they stand in a circle arbitrarily, it may turn out, that there is a tall and low child standing next to each other, and it will be difficult for them to hold hands. Therefore, children want to stand in a circle so that the maximum difference between the growth of two neighboring children would be minimal possible.Formally, let's number children from $$$1$$$ to $$$n$$$ in a circle order, that is, for every $$$i$$$ child with number $$$i$$$ will stand next to the child with number $$$i+1$$$, also the child with number $$$1$$$ stands next to the child with number $$$n$$$. Then we will call the discomfort of the circle the maximum absolute difference of heights of the children, who stand next to each other.Please help children to find out how they should reorder themselves, so that the resulting discomfort is smallest possible.

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the number of the children who came to the cowboy Vlad's birthday. The second line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) denoting heights of every child.

Print exactly $$$n$$$ integers — heights of the children in the order in which they should stand in a circle. You can start printing a circle with any child. If there are multiple possible answers, print any of them.

NoteIn the first example, the discomfort of the circle is equal to $$$1$$$, since the corresponding absolute differences are $$$1$$$, $$$1$$$, $$$1$$$ and $$$0$$$. Note, that sequences $$$[2, 3, 2, 1, 1]$$$ and $$$[3, 2, 1, 1, 2]$$$ form the same circles and differ only by the selection of the starting point.In the second example, the discomfort of the circle is equal to $$$20$$$, since the absolute difference of $$$10$$$ and $$$30$$$ is equal to $$$20$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    sort(A)

    val ix = ArrayBuffer[Int]()
    REP(N) { i =>
      if (i % 2 == 0) ix += i
    }

    REP_r(N) { i =>
      if (i % 2 == 1) ix += i
    }

//    debug(ix.mkString(" "))
    out.println(ix.map(A).mkString(" "))
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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


Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is:Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the set, or v is in the set, or both are in the set. Mahmoud has found the following algorithm:  Root the tree at node 1.  Count the number of nodes at an even depth. Let it be evenCnt.  Count the number of nodes at an odd depth. Let it be oddCnt.  The answer is the minimum between evenCnt and oddCnt. The depth of a node in a tree is the number of edges in the shortest path between this node and the root. The depth of the root is 0.Ehab told Mahmoud that this algorithm is wrong, but he didn't believe because he had tested his algorithm against many trees and it worked, so Ehab asked you to find 2 trees consisting of n nodes. The algorithm should find an incorrect answer for the first tree and a correct answer for the second one.

The only line contains an integer n (2 ≤ n ≤ 105), the number of nodes in the desired trees.

The output should consist of 2 independent sections, each containing a tree. The algorithm should find an incorrect answer for the tree in the first section and a correct answer for the tree in the second. If a tree doesn't exist for some section, output "-1" (without quotes) for that section only. If the answer for a section exists, it should contain n - 1 lines, each containing 2 space-separated integers u and v (1 ≤ u, v ≤ n), which means that there's an undirected edge between node u and node v. If the given graph isn't a tree or it doesn't follow the format, you'll receive wrong answer verdict. If there are multiple answers, you can print any of them.

NoteIn the first sample, there is only 1 tree with 2 nodes (node 1 connected to node 2). The algorithm will produce a correct answer in it so we printed  - 1 in the first section, but notice that we printed this tree in the second section.In the second sample:In the first tree, the algorithm will find an answer with 4 nodes, while there exists an answer with 3 nodes like this:  In the second tree, the algorithm will find an answer with 3 nodes which is correct:

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

    if (n < 6) {
      println(-1)
    } else {
      println(tree(n - 2))
      println(s"2 ${n - 1}\n2 $n")
    }

    println(tree(n))
  }

  lazy val ones: Stream[Int] = 1 #:: ones
  lazy val N: Stream[Int] = 1 #:: N.map(_ + 1)

  def tree(n: Int) =
    ones.zip(N.tail).take(n - 1).map {
      case (x, y) => s"$x $y"
    }.mkString("\n")
}


You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.

The first line contains two integers, n and m (1 ≤ n ≤ 3000, 1 ≤ m ≤ 3000) — the number of words in the professor's lecture and the number of words in each of these languages. The following m lines contain the words. The i-th line contains two strings ai, bi meaning that the word ai belongs to the first language, the word bi belongs to the second language, and these two words have the same meaning. It is guaranteed that no word occurs in both languages, and each word occurs in its language exactly once. The next line contains n space-separated strings c1, c2, ..., cn — the text of the lecture. It is guaranteed that each of the strings ci belongs to the set of strings {a1, a2, ... am}. All the strings in the input are non-empty, each consisting of no more than 10 lowercase English letters.

Output exactly n words: how you will record the lecture in your notebook. Output the words of the lecture in the same order as in the input.

4 3
codeforces codesecrof
contest round
letter message
codeforces contest letter contest

5 3
joll wuqrd
euzf un
hbnyiyc rsoqqveh
hbnyiyc joll joll euzf joll

codeforces round letter round
hbnyiyc joll joll un joll

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

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

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

}


The teacher gave Anton a large geometry homework, but he didn't do it (as usual) as he participated in a regular round on Codeforces. In the task he was given a set of n lines defined by the equations y = ki·x + bi. It was necessary to determine whether there is at least one point of intersection of two of these lines, that lays strictly inside the strip between x1 < x2. In other words, is it true that there are 1 ≤ i < j ≤ n and x', y', such that:   y' = ki * x' + bi, that is, point (x', y') belongs to the line number i;  y' = kj * x' + bj, that is, point (x', y') belongs to the line number j;  x1 < x' < x2, that is, point (x', y') lies inside the strip bounded by x1 < x2. You can't leave Anton in trouble, can you? Write a program that solves the given task.

The first line of the input contains an integer n (2 ≤ n ≤ 100 000) — the number of lines in the task given to Anton. The second line contains integers x1 and x2 ( - 1 000 000 ≤ x1 < x2 ≤ 1 000 000) defining the strip inside which you need to find a point of intersection of at least two lines. The following n lines contain integers ki, bi ( - 1 000 000 ≤ ki, bi ≤ 1 000 000) — the descriptions of the lines. It is guaranteed that all lines are pairwise distinct, that is, for any two i ≠ j it is true that either ki ≠ kj, or bi ≠ bj.

Print "Yes" (without quotes), if there is at least one intersection of two distinct lines, located strictly inside the strip. Otherwise print "No" (without quotes).

NoteIn the first sample there are intersections located on the border of the strip, but there are no intersections located strictly inside it.

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

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

}

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


You are given a string $$$s$$$ consisting only of lowercase Latin letters.You can rearrange all letters of this string as you wish. Your task is to obtain a good string by rearranging the letters of the given string or report that it is impossible to do it.Let's call a string good if it is not a palindrome. Palindrome is a string which is read from left to right the same as from right to left. For example, strings "abacaba", "aa" and "z" are palindromes and strings "bba", "xd" are not.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of queries. Each of the next $$$t$$$ lines contains one string. The $$$i$$$-th line contains a string $$$s_i$$$ consisting only of lowercase Latin letter. It is guaranteed that the length of $$$s_i$$$ is from $$$1$$$ to $$$1000$$$ (inclusive).

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: -1 if it is impossible to obtain a good string by rearranging the letters of $$$s_i$$$ and any good string which can be obtained from the given one (by rearranging the letters) otherwise.

NoteIn the first query we cannot rearrange letters to obtain a good string.Other examples (not all) of correct answers to the second query: "ababaca", "abcabaa", "baacaba".In the third query we can do nothing to obtain a good string.

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

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

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
}


A flowerbed has many flowers and two fountains.You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, the distance between the flower and the first fountain doesn't exceed r1, or the distance to the second fountain doesn't exceed r2. It's OK if some flowers are watered by both fountains.You need to decrease the amount of water you need, that is set such r1 and r2 that all the flowers are watered and the r12 + r22 is minimum possible. Find this minimum value.

The first line of the input contains integers n, x1, y1, x2, y2 (1 ≤ n ≤ 2000,  - 107 ≤ x1, y1, x2, y2 ≤ 107) — the number of flowers, the coordinates of the first and the second fountain. Next follow n lines. The i-th of these lines contains integers xi and yi ( - 107 ≤ xi, yi ≤ 107) — the coordinates of the i-th flower. It is guaranteed that all n + 2 points in the input are distinct.

Print the minimum possible value r12 + r22. Note, that in this problem optimal answer is always integer.

NoteThe first sample is (r12 = 5, r22 = 1):  The second sample is (r12 = 1, r22 = 32):

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

}


Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.

The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors. Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000). The total number of balls doesn't exceed 1000.

A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.

NoteIn the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are: 1 2 1 2 31 1 2 2 32 1 1 2 3

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

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

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


Igor is in 11th grade. Tomorrow he will have to write an informatics test by the strictest teacher in the school, Pavel Denisovich. Igor knows how the test will be conducted: first of all, the teacher will give each student two positive integers $$$a$$$ and $$$b$$$ ($$$a < b$$$). After that, the student can apply any of the following operations any number of times:   $$$a := a + 1$$$ (increase $$$a$$$ by $$$1$$$),  $$$b := b + 1$$$ (increase $$$b$$$ by $$$1$$$),  $$$a := a \ | \ b$$$ (replace $$$a$$$ with the bitwise OR of $$$a$$$ and $$$b$$$). To get full marks on the test, the student has to tell the teacher the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.Igor already knows which numbers the teacher will give him. Help him figure out what is the minimum number of operations needed to make $$$a$$$ equal to $$$b$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line for each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a < b \le 10^6$$$). It is guaranteed that the sum of $$$b$$$ over all test cases does not exceed $$$10^6$$$.

For each test case print one integer — the minimum required number of operations to make $$$a$$$ and $$$b$$$ equal.

NoteIn the first test case, it is optimal to apply the third operation.In the second test case, it is optimal to apply the first operation three times.In the third test case, it is optimal to apply the second operation and then the third operation.

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(a, b) = readInts()
    val answers = a.to(2 * b).map{ desiredA =>
      (desiredA - a) + ((desiredA | b) - b) +
        (if (desiredA != (desiredA | b)) 1 else 0)
    }

    val answer2 = {
      val increasingBStep = b.until(2 * b).find { desiredB =>
        (desiredB | a) == desiredB
      }.get - b + 1
      val increasingAStep = b - a
      Math.min(increasingBStep, increasingAStep)
    }

    println(Math.min(answers.min, answer2))
  }

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

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

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(a, b) = readInts()
    val answer = {
      val increasingBStep = b.until(2 * b).find { desiredB =>
        (desiredB | a) == desiredB
      }.get - b + 1
      val increasingAStep = b - a
      Math.min(increasingBStep, increasingAStep)
    }

    println(answer)
  }

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

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


A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.Subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.You are given a regular bracket sequence $$$s$$$ and an integer number $$$k$$$. Your task is to find a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$.It is guaranteed that such sequence always exists.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le k \le n \le 2 \cdot 10^5$$$, both $$$n$$$ and $$$k$$$ are even) — the length of $$$s$$$ and the length of the sequence you are asked to find. The second line is a string $$$s$$$ — regular bracket sequence of length $$$n$$$.

Print a single string — a regular bracket sequence of length exactly $$$k$$$ such that it is also a subsequence of $$$s$$$. It is guaranteed that such sequence always exists.

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

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