The problem describes the properties of a command line. The description somehow resembles the one you usually see in real operating systems. However, there are differences in the behavior. Please make sure you've read the statement attentively and use it as a formal document.In the Pindows operating system a strings are the lexemes of the command line — the first of them is understood as the name of the program to run and the following lexemes are its arguments. For example, as we execute the command " run.exe one, two . ", we give four lexemes to the Pindows command line: "run.exe", "one,", "two", ".". More formally, if we run a command that can be represented as string s (that has no quotes), then the command line lexemes are maximal by inclusion substrings of string s that contain no spaces.To send a string with spaces or an empty string as a command line lexeme, we can use double quotes. The block of characters that should be considered as one lexeme goes inside the quotes. Embedded quotes are prohibited — that is, for each occurrence of character """ we should be able to say clearly that the quotes are opening or closing. For example, as we run the command ""run.exe o" "" " ne, " two . " " ", we give six lexemes to the Pindows command line: "run.exe o", "" (an empty string), " ne, ", "two", ".", " " (a single space).It is guaranteed that each lexeme of the command line is either surrounded by spaces on both sides or touches the corresponding command border. One of its consequences is: the opening brackets are either the first character of the string or there is a space to the left of them.You have a string that consists of uppercase and lowercase English letters, digits, characters ".,?!"" and spaces. It is guaranteed that this string is a correct OS Pindows command line string. Print all lexemes of this command line string. Consider the character """ to be used only in order to denote a single block of characters into one command line lexeme. In particular, the consequence is that the given string has got an even number of such characters.

The single line contains a non-empty string s. String s consists of at most 105 characters. Each character is either an uppercase or a lowercase English letter, or a digit, or one of the ".,?!"" signs, or a space. It is guaranteed that the given string is some correct command line string of the OS Pindows. It is guaranteed that the given command line string contains at least one lexeme.

In the first line print the first lexeme, in the second line print the second one and so on. To make the output clearer, print the "<" (less) character to the left of your lexemes and the ">" (more) character to the right. Print the lexemes in the order in which they occur in the command. Please, follow the given output format strictly. For more clarifications on the output format see the test samples.

"RUn.exe O" "" "   2ne, " two! . " "
firstarg   second   ""

object B {
  def main(args: Array[String]) {
    val s = readLine()
    var inside = false
    var token = ""
    for (x <- s) {
      if (inside) {
        if (x == '\"') {
          println("<" + token + ">")
          token = ""
          inside = false
        } else {
          token += x
        }
      } else {
        if (x == '\"') {
          inside = true
        } else if (x == ' ') {
          if (token != "") {
            println("<" + token + ">")
          }
          token = ""
        } else {
          token += x
        }
      }
    }
    if (token != "") {
      println("<" + token + ">")
    }
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val (list, _, soFar) = in.next().foldLeft(List.empty[String], false, List.empty[Char]) {
    case ((list, true, soFar), '"') => (soFar.reverse.mkString :: list, false, List.empty[Char])
    case ((list, true, soFar), ch) => (list, true, ch :: soFar)
    case ((list, false, Nil), '"') => (list, true, List.empty[Char])
    case (acc@(list, false, Nil), ' ') => acc
    case (acc@(list, false, something), ' ') => (something.reverse.mkString :: list, false, List.empty[Char])
    case (acc@(list, false, something), ch) => (list, false, ch :: something)
  }

  val res = if (soFar.nonEmpty) soFar.reverse.mkString :: list else list

  println(res.reverse.map(i => s"<$i>").mkString("\n"))

}

/*
B. Аргументы командной строки
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

В данной задаче используется описание свойств командной строки, близкое к тому, что вы привыкли видеть в настоящих операционных системах. Однако, в деталях существуют отличия в поведении. Внимательно прочтите условие, используйте его как формальный документ при разработке решения.

В операционной системе Pindows лексемами командной строки являются строки — первая из них трактуется как имя запускаемой программы, а последующие как ее аргументы. Например, выполняя команду « run.exe one, two . », мы передаем командной строке Pindows четыре лексемы: «run.exe», «one,», «two», «.». Более формально, если мы выполняем команду, которая представима строкой s (и не содержит кавычек), то лексемами командной строки являются максимальные по включению подстроки строки s, которые не содержат пробелов.

Для того, чтобы передать в качестве лексемы командной строки строку с пробелами или пустую строку, используются двойные кавычки. Блок символов, который должен рассматриваться как одна лексема, берется в кавычки. При этом вложенные кавычки запрещаются — то есть про каждое вхождение символа «"» можно однозначно сказать — что это, открывающие кавычки или закрывающие. Например, выполняя команду «"run.exe o" "" " ne, " two . " " », мы передаем командной строке Pindows шесть лексем: «run.exe o», «» (пустая строка), « ne, », «two», «.», « » (единичный пробел).

Гарантируется, что каждая из лексем командной строки окружена с обеих сторон пробелами или упирается в соответствующий край командной строки. Из этого, например, следует, что открывающие кавычки либо являются первым символом строки, либо слева от них находится пробел.

Вам задана строка, состоящая из прописных, строчных букв латинского алфавита, цифр, символов «.,?!"» и пробелов. Гарантируется, что эта строка — корректная командная строка OS Pindows. Выведите все лексемы этой командной строки. Считайте, что символ «"» используется в команде только для выделения единого блока символов в одну лексему командной строки, в частности, из этого следует, что таких символов в заданной строке четное количество.
Входные данные

В единственной строке задана непустая строка s. Строка s состоит из не более чем 105 символов. Каждый символ — это либо прописная, либо строчная буква латинского алфавита, либо цифра, либо один из символов «.,?!"», либо пробел.

Гарантируется, что заданная строка — некоторая корректная командная строка OS Pindows. Гарантируется, что в заданной командной строке есть хотя бы одна лексема.
Выходные данные

В первой строке выведите первую лексему, во второй строке — вторую, и так далее. Для наглядности слева от каждой лексемы выведите символ «<» (меньше), а справа — символ «>» (больше). Выводите лексемы в том порядке, в котором они встречаются в команде.

Строго следуйте описанному формату вывода. Для лучшего понимания формата вывода посмотрите тестовые примеры.
Примеры тестов
Входные данные

"RUn.exe O" "" "   2ne, " two! . " "

Выходные данные

<RUn.exe O>
<>
<   2ne, >
<two!>
<.>
< >

Входные данные

   firstarg   second   ""

Выходные данные

<firstarg>
<second>
<>
 */
import scala.collection.JavaConversions._

object Task2 extends App {

  def clear(s: StringBuilder) = {
    s.clear
    s
  }

  def add(l: java.util.List[String], s: String) = {
    l add s
    l
  }
  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(l: String): Seq[String] = {
    val acc = new java.util.ArrayList[String]
    def solveRec(s: String, i: Int, curr: StringBuilder, quoted: Boolean): Unit =
      if (i >= s.length) {
        assert(!quoted)
        if (!curr.isEmpty) add(acc, curr.toString)
      } else s(i) match {
        // Open quotes
        case '"' if !quoted                  => solveRec(s, i + 1, curr, true)
        // Add and close quotes
        case '"' if quoted                   =>  {
          add(acc, curr.toString)
          solveRec(s, i + 1, clear(curr), false)
        }
        // Ignore
        case ' ' if !quoted && curr.isEmpty  => solveRec(s, i + 1, curr, quoted)
        // Add and clear
        case ' ' if !quoted && !curr.isEmpty => {
          add(acc, curr.toString)
          solveRec(s, i + 1, clear(curr), quoted)
        }
        // Append
        case ' ' if quoted                   => solveRec(s, i + 1, curr += ' ', quoted)
        // Append
        case c                               => solveRec(s, i + 1, curr += c, quoted)
      }
    solveRec(l, 0, new StringBuilder, false)
    acc
  }

  val line = readLine
  val res = solve(line)
  res map (s => println("<" + s + ">"))
}

import io.Source
import java.io.PrintWriter

object CF291B {

  def solve(in: In, out: PrintWriter) {
    in.tokenIterator.toSeq.foreach { s => println("<" + s + ">") }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      var q = false
      var stop = false
      while (!stop && iter.hasNext && (q || delims.indexOf(iter.head) == -1)) {
        val c = iter.next()
        if (c == '"') {
          if (q) {
            stop = true
          } else {
            q = true
          }
        } else {
          sb.append(c)
        }
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object B {
  def main(args: Array[String]) {
    var s = readLine()
    var opened = false;
    var arr:Array[Char] = s.toCharArray
    for (i <- 0 until s.length) {
      if (arr(i) == '\"') opened = !opened;
      if (arr(i) == ' ' && !opened)  arr(i) = '#';
    }
    new String(arr).split("#") filter (!_.isEmpty) foreach {ss => println("<" + ss.replaceAll("\"", "") + ">" )}
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = readLine();
    var i = 0
    while(i < s.size) {
      if (s(i) == '"') {
        val j = s.indexOf('"', i + 1)
        println("<" + s.substring(i + 1, j) + ">")
        i = j + 2
      } else if (s(i) == ' ') {
        i += 1
      } else {
        val j = s.indexOf(' ', i + 1) match {
          case -1 => s.size
          case int: Int => int
        }
        println("<" + s.substring(i, j).trim + ">")
        i = j + 1
      }
    }
  }
}

object B {
  def main(args: Array[String]) {
    val s = readLine()
    var inside = false
    var token = ""
    for (x <- s) {
      if (inside) {
        if (x == '\"') {
          println("<" + token + ">")
          token = ""
          inside = false
        } else {
          token += x
        }
      } else {
        if (x == '\"') {
          inside = true
        } else if (x == ' ') {
          if (token != "") {
            println("<" + token + ">")
          }
          token = ""
        } else {
          token += x
        }
      }
    }
    if (token != "") {
      println(token)
    }
  }
}

import io.Source
import java.io.PrintWriter

object CF291B {

  def solve(in: In, out: PrintWriter) {
    in.tokenIterator.toSeq.foreach { s => println("<" + s + ">")}
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext && iter.head != '\n' && iter.head != '\r'
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      var q = false
      var stop = false
      while (!stop && iter.hasNext && (q || delims.indexOf(iter.head) == -1)) {
        val c = iter.next()
        if (c == '"') {
          if (q) {
            stop = true
          } else {
            q = true
          }
        } else {
          sb.append(c)
        }
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " ")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = readLine();
    var i = 0
    while(i < s.size) {
      if (s(i) == '"') {
        val j = s.indexOf('"', i + 1)
        println("<" + s.substring(i + 1, j) + ">")
        i = j + 2
      } else {
        val j = s.indexOf(' ', i + 1)
        if (j != i + 1) println("<" + s.substring(i, j).trim + ">")
        i = j + 1
      }
    }
  }
}


Daniel is watching a football team playing a game during their training session. They want to improve their passing skills during that session.The game involves $$$n$$$ players, making multiple passes towards each other. Unfortunately, since the balls were moving too fast, after the session Daniel is unable to know how many balls were involved during the game. The only thing he knows is the number of passes delivered by each player during all the session.Find the minimum possible amount of balls that were involved in the game.

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of players. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 10^9$$$), where $$$a_i$$$ is the number of passes delivered by the $$$i$$$-th player. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case print a single integer — the answer to the problem.

NoteIn the first test case, with the only ball, the game can go like this:$$$2 \rightarrow 1 \rightarrow 3 \rightarrow 4 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 4 \rightarrow 2 \rightarrow 3 \rightarrow 2$$$.In the second test case, there is no possible way to play the game with only one ball. One possible way to play with two balls:$$$2 \rightarrow 1 \rightarrow 2 \rightarrow 3 \rightarrow 2 \rightarrow 1$$$.$$$2 \rightarrow 3 \rightarrow 2 \rightarrow 1$$$In the third example, there were no passes, so $$$0$$$ balls are possible.

import scala.io.StdIn.readLine

object Solution {

  def f(i: Int, xs: Array[Long]) = {
    val (sum, max) = xs.foldLeft(0L, None:Option[Long])(
      (acc, elem) => acc match {
        case (q, Some(o)) => (q + elem, if (o > elem) Some(o) else Some(elem))
        case (_, None) => (elem, Some(elem))
      }
    )

    val rem = sum - max.get
    if (sum == 0) 0
    else if (rem >= max.get - 1) 1
    else max.get - rem

  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt
    for (
      c <- 0 until cases;
      i = readLine().toInt;
      j = readLine().split("\\s+").map(_.toLong)
    ) println(f(i, j))

  }
}

import scala.io.StdIn.readLine

object Solution {

  def f(i: Int, xs: Array[Long]) = {
    val (sum, max) = xs.foldLeft(0L, None:Option[Long])(
      (acc, elem) => acc match {
        case (q, Some(o)) => (q + elem, if (o > elem) Some(o) else Some(elem))
        case (_, None) => (elem, Some(elem))
      }
    )

    val rem = sum - max.get
    if (rem > max.get) 1
    else max.get - rem

  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt
    for (
      c <- 0 until cases;
      i = readLine().toInt;
      j = readLine().split("\\s+").map(_.toLong)
    ) println(f(i, j))

  }
}

import scala.io.StdIn.readLine

object Solution {

  def f() = {
    val players = readLine().toInt
    val arr = readLine().split("\\s+").map(_.toLong)

    val sum = arr.sum
    val fil = arr.filterNot(_ == 0)
    if (fil.length == 0) 0 else {
      val avg = sum / fil.length
      val max = arr.max

      if (sum == 0) 0
      else max / avg
    }

  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt
    for (
      i <- 0 until cases
    ) println(f())
  }
}


Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of leaves Alyona has found. The next n lines contain the leaves' descriptions. Each leaf is characterized by the species of the tree it has fallen from and by the color. The species of the trees and colors are given in names, consisting of no more than 10 lowercase Latin letters. A name can not be an empty string. The species of a tree and the color are given in each line separated by a space.

Output the single number — the number of Alyona's leaves.

5
birch yellow
maple red
birch yellow
maple yellow
maple green

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  println(in.take(n).toSet.size)
}


Let's suppose you have an array a, a stack s (initially empty) and an array b (also initially empty).You may perform the following operations until both a and s are empty:  Take the first element of a, push it into s and remove it from a (if a is not empty);  Take the top element from s, append it to the end of array b and remove it from s (if s is not empty). You can perform these operations in arbitrary order.If there exists a way to perform the operations such that array b is sorted in non-descending order in the end, then array a is called stack-sortable.For example, [3, 1, 2] is stack-sortable, because b will be sorted if we perform the following operations:  Remove 3 from a and push it into s;  Remove 1 from a and push it into s;  Remove 1 from s and append it to the end of b;  Remove 2 from a and push it into s;  Remove 2 from s and append it to the end of b;  Remove 3 from s and append it to the end of b. After all these operations b = [1, 2, 3], so [3, 1, 2] is stack-sortable. [2, 3, 1] is not stack-sortable.You are given k first elements of some permutation p of size n (recall that a permutation of size n is an array of size n where each integer from 1 to n occurs exactly once). You have to restore the remaining n - k elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that p is lexicographically maximal (an array q is lexicographically greater than an array p iff there exists some integer k such that for every i < k qi = pi, and qk > pk). You may not swap or change any of first k elements of the permutation.Print the lexicographically maximal permutation p you can obtain.If there exists no answer then output -1.

The first line contains two integers n and k (2 ≤ n ≤ 200000, 1 ≤ k < n) — the size of a desired permutation, and the number of elements you are given, respectively. The second line contains k integers p1, p2, ..., pk (1 ≤ pi ≤ n) — the first k elements of p. These integers are pairwise distinct.

If it is possible to restore a stack-sortable permutation p of size n such that the first k elements of p are equal to elements given in the input, print lexicographically maximal such permutation. Otherwise print -1.

import java.io.FileReader
import java.util
import java.util.Comparator

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

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def doCase() : Unit = {
    val Array(n, k) = readIntLine()
    val prefix = readIntLine()
    var reserve = new mutable.TreeSet[Int]()(Ordering.Int.reverse)
    (1 to n).toSet.diff(prefix.toSet).foreach(reserve.add)

    val result = stacksort(prefix.toList, Nil, 1, reserve, Nil, n)
    if (result.isEmpty) {
      println(-1)
    } else {
      println((prefix ++: result.reverse).toArray.mkString(" "))
    }
  }

  def stacksort(nums : List[Int], stack : List[Int], out : Int, reserve : mutable.TreeSet[Int], result : List[Int], n : Int) : List[Int] = {
    if (out > n) {
      result
    } else if (nums.nonEmpty && nums.head == out) {
      stacksort(nums.tail, stack, out + 1, reserve, result, n)
    } else if (stack.nonEmpty && stack.head == out) {
      stacksort(nums, stack.tail, out + 1, reserve, result, n)
    } else if (nums.nonEmpty && (stack.isEmpty || (stack.head > nums.head))) {
      stacksort(nums.tail, nums.head :: stack, out, reserve, result, n)
    } else if (nums.isEmpty) {
      val bound = stack.headOption.getOrElse(n)
      val desiredIt = reserve.iteratorFrom(bound)
      if (desiredIt.hasNext) {
        val desired = desiredIt.next()
        reserve.remove(desired)
        stacksort(nums, desired :: stack, out, reserve, desired :: result, n)
      } else {
        Nil
      }
    } else {
      Nil
    }
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}


Chouti was tired of the tedious homework, so he opened up an old programming problem he created years ago.You are given a connected undirected graph with $$$n$$$ vertices and $$$m$$$ weighted edges. There are $$$k$$$ special vertices: $$$x_1, x_2, \ldots, x_k$$$.Let's define the cost of the path as the maximum weight of the edges in it. And the distance between two vertexes as the minimum cost of the paths connecting them.For each special vertex, find another special vertex which is farthest from it (in terms of the previous paragraph, i.e. the corresponding distance is maximum possible) and output the distance between them.The original constraints are really small so he thought the problem was boring. Now, he raises the constraints and hopes you can solve it for him.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \leq k \leq n \leq 10^5$$$, $$$n-1 \leq m \leq 10^5$$$) — the number of vertices, the number of edges and the number of special vertices. The second line contains $$$k$$$ distinct integers $$$x_1, x_2, \ldots, x_k$$$ ($$$1 \leq x_i \leq n$$$). Each of the following $$$m$$$ lines contains three integers $$$u$$$, $$$v$$$ and $$$w$$$ ($$$1 \leq u,v \leq n, 1 \leq w \leq 10^9$$$), denoting there is an edge between $$$u$$$ and $$$v$$$ of weight $$$w$$$. The given graph is undirected, so an edge $$$(u, v)$$$ can be used in the both directions. The graph may have multiple edges and self-loops. It is guaranteed, that the graph is connected.

The first and only line should contain $$$k$$$ integers. The $$$i$$$-th integer is the distance between $$$x_i$$$ and the farthest special vertex from it.

NoteIn the first example, the distance between vertex $$$1$$$ and $$$2$$$ equals to $$$2$$$ because one can walk through the edge of weight $$$2$$$ connecting them. So the distance to the farthest node for both $$$1$$$ and $$$2$$$ equals to $$$2$$$.In the second example, one can find that distance between $$$1$$$ and $$$2$$$, distance between $$$1$$$ and $$$3$$$ are both $$$3$$$ and the distance between $$$2$$$ and $$$3$$$ is $$$2$$$.The graph may have multiple edges between and self-loops, as in the first example.

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)

  case class Edge(v: Int, u: Int, w: Int)
  def solve(): Unit = {
    val N, M, K = ni()
    val X = na(K, -1)
    val E = Array.ofDim[Edge](M)
    REP(M) { i =>
      val u, v = ni() - 1
      val w = ni()
      E(i) = Edge(u, v, w)
    }
    Sorting.quickSort(E)(Ordering.by(_.w))

    var ans = -1
    val uf = new UnionFind(N)
    val flg = Array.ofDim[Boolean](N) // この集合がspecialを含んでいるか
    REP(K) { i =>
      flg(X(i)) = true
    }
    REP(M) { i =>
      val e = E(i)
      val fu = flg(uf.find(e.u))
      val fv = flg(uf.find(e.v))

      // 別の集合で、どっちもspecialを含んでいるならこの道を通らざるを得ない
      if (uf.find(e.u) != uf.find(e.v) && fu && fv) {
        ans = e.w
      }
      uf.unite(e.u, e.v)
      flg(uf.find(e.u)) = fu || fv
    }

    out.println(map(K)(_ => ans).mkString(" "))
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

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


It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array $$$a$$$. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices $$$x, y, z, w$$$ such that $$$a_x + a_y = a_z + a_w$$$.Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery?

The first line contains the single integer $$$n$$$ ($$$4 \leq n \leq 200\,000$$$) — the size of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 2.5 \cdot 10^6$$$).

Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices $$$x$$$, $$$y$$$, $$$z$$$ and $$$w$$$ ($$$1 \le x, y, z, w \le n$$$). If there are multiple answers, print any of them.

NoteIn the first example $$$a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6$$$. Note that there are other answer, for example, 2 3 4 6.In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that $$$a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3$$$

import java.util.Random

object C {
  import InOut._
  def main(args: Array[String]): Unit = {

      val n = nextInt
      val as = nextInts(n).zipWithIndex.sorted

    val finish = System.currentTimeMillis() + 1400
    val rnd = new Random()

      val aByD, bByD = Array.fill(2600000)(-1)

      var done = false
      while (System.currentTimeMillis() < finish && !done) {
        val _a, _b = rnd.nextInt(n)
        if (_a != _b) {
          val a = Math.min(_a, _b)
          val b = Math.max(_a, _b)
          val d = as(b)._1 - as(a)._1
//          println(a, b, d)
          if (aByD(d) >= 0 && aByD(d) != a && aByD(d) != b && bByD(d) != a && bByD(d) != b) {
            done = true
            out.println("YES")
            out.println(s"${as(a)._2 + 1} ${as(bByD(d))._2 + 1} ${as(b)._2 + 1} ${as(aByD(d))._2 + 1}")
          } else {
            aByD(d) = a
            bByD(d) = b
          }
        }
      }

//    out.println(aByD.take(10).mkString(" "))
//    out.println(bByD.take(10).mkString(" "))
    if (!done) out.println("NO")

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.

The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.

Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.

NoteThe second valid answer to the test from the statement is "heloo".

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val skipTriplets = str.tail.foldLeft((List(str.head), 1, str.head)) {
    case ((list, 2, prev), el) if prev == el => (list, 2, el)
    case ((list, count, prev), el) if prev == el =>
      (el :: list, count + 1, prev)
    case ((list, count, prev), el) =>
      (el :: list, 1, el)
  }._1.reverse
  val skip = skipTriplets.tail.foldLeft((List(str.head), false, str.head, 0)) {
    case((list, false, prev, n), el) if el == prev => (el :: list, true, el, 0)
    case((list, true, prev, 1), el) if el == prev => (list, false, el, 0)
    case((list, true, prev, 0), el) => (el :: list, true, el, 1)
    case((list, status, prev, n), el) => (el :: list, false, el, 0)
  }
  println(skip._1.reverse.mkString)
}

object FixingTypos extends App {
    val s = readLine

    def fix(str: String): String = {
        var ss: StringBuffer = new StringBuffer("")
        var now = 2
        for(i <- 0 until str.size if i==0 || str(i) != str(i-1)) {
            if(now == 2) ss.append(str(i))
            ss.append(str(i))
            now = 3 - now
        }
        ss.toString
    }

    var ret: StringBuffer = new StringBuffer("")
    var begin = 0
    for(i <- 0 until s.size) {
        var bb = false
        var ee = false
        if(i==0 || s(i) != s(i-1)) bb = true
        if(i== s.size - 1 || s(i) != s(i + 1)) ee = true
        if(ee && bb) {
            ret.append(fix(s.substring(begin, i)))
            ret.append(s(i))
            begin = i + 1
        } else if(i == s.size - 1) ret.append(fix(s.substring(begin, s.size)))
    }
    println(ret)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val skipTriplets = str.tail.foldLeft((List(str.head), 1, str.head)) {
    case ((list, 2, prev), el) if prev == el => (list, 2, el)
    case ((list, count, prev), el) if prev == el =>
      (el :: list, count + 1, prev)
    case ((list, count, prev), el) =>
      (el :: list, 1, el)
  }._1.reverse
  val skip = skipTriplets.tail.foldLeft((List(str.head), false, str.head, 0)) {
    case((list, false, prev, n), el) if el == prev => (el :: list, true, el, 0)
    case((list, false, prev, n), el) => (el :: list, false, el, 0)
    case((list, true, prev, 1), el) if el == prev => (list, false, el, 0)
    case((list, true, prev, 0), el) if el == prev => (el :: list, true, el, 1)
    case((list, true, prev, n), el) => (el :: list, false, el, 0)
  }
  println(skip._1.reverse.mkString)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val skipTriplets = str.tail.foldLeft((List(str.head), 1, str.head)) {
    case ((list, 2, prev), el) if prev == el => (list, 2, el)
    case ((list, count, prev), el) if prev == el =>
      (el :: list, count + 1, prev)
    case ((list, count, prev), el) =>
      (el :: list, 1, el)
  }._1.reverse
  val skip = skipTriplets.tail.foldLeft((List(str.head), false, str.head, 0)) {
    case((list, false, prev, n), el) if el == prev => (el :: list, true, el, 0)
    case((list, false, prev, n), el) => (el :: list, false, el, 0)
    case((list, true, prev, 1), el) if el == prev => (list, false, el, 0)
    case((list, true, prev, 0), el) if el == prev => (el :: list, true, el, 1)
    case((list, true, prev, n), el) => (list, false, el, 0)
  }
  println(skip._1.reverse.mkString)
}


You have $$$r$$$ red and $$$b$$$ blue beans. You'd like to distribute them among several (maybe, one) packets in such a way that each packet:   has at least one red bean (or the number of red beans $$$r_i \ge 1$$$);  has at least one blue bean (or the number of blue beans $$$b_i \ge 1$$$);  the number of red and blue beans should differ in no more than $$$d$$$ (or $$$|r_i - b_i| \le d$$$) Can you distribute all beans?

The first line contains the single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains three integers $$$r$$$, $$$b$$$, and $$$d$$$ ($$$1 \le r, b \le 10^9$$$; $$$0 \le d \le 10^9$$$) — the number of red and blue beans and the maximum absolute difference in each packet.

For each test case, if you can distribute all beans, print YES. Otherwise, print NO. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, you can form one packet with $$$1$$$ red and $$$1$$$ blue bean. The absolute difference $$$|1 - 1| = 0 \le d$$$.In the second test case, you can form two packets: $$$1$$$ red and $$$4$$$ blue beans in the first packet and $$$1$$$ red and $$$3$$$ blue beans in the second one.In the third test case, since $$$b = 1$$$, you can form only one packet with $$$6$$$ red and $$$1$$$ blue beans. The absolute difference $$$|6 - 1| = 5 > d$$$.In the fourth test case, since $$$d = 0$$$ so each packet should contain the same number of red and blue beans, but $$$r \neq b$$$.

object A {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
//  val input = new InputReader(new StringReader(
//      """8
//1 1 0
//2 7 3
//6 1 4
//5 4 0
//1000000000 1000000000 0
//1000000000 1000000000 1000000000
//1000000000 1 1000000000
//1 1000000000 0
//          """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val r, b, d = input.nextInt
        val mn = r min b
        val mx = r max b
        val h = mx / (d + 1)
        val l = mx % (d + 1)
        if (mn > h || mn == h && l == 0 ) {
          out.print("YES")
        }
        else {
          out.print("NO")
        }
        out.endl()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      println(buffer.result())
      buffer.clear()
    }
  }

}

import scala.io.StdIn
import scala.math.min

object Main extends App {
  val n = StdIn.readInt()
  for (i <- 0 until n) {
    val values = StdIn.readLine().split(" ").map(_.toInt)
    val r = values(0)
    val b = values(1)
    val d = values(2)
    val delta = Math.abs(r - b)
    val minimal = min(r, b)
    println(if (Math.round(delta / minimal) + (if (delta % minimal == 0) 0 else 1) <= d) "YES" else "NO")
  }
}

object A {

  import java.io._

  val out: OutputPrinter = new StringOutputPrinter
  //val out: OutputPrinter = new OutputPrinter
  val input = new InputReader(new InputStreamReader(System.in))
//  val input = new InputReader(new StringReader(
//      """4
//1 1 0
//2 7 3
//6 1 4
//5 4 0
//          """))

  def main(args: Array[String]): Unit = {
    val startTime = System.currentTimeMillis()

    val executor = new Solution1
    executor.solve()

    out.flush()
    val elapsed = System.currentTimeMillis() - startTime
    //println(s"Elapsed: $elapsed")
  }

  class Solution1 {

    def solve(): Unit = {
      val tasks = input.nextInt
      for (_ <- 0 until tasks) {
        val r, b, d = input.nextInt
        val mn = r min b
        val mx = r max b
        val mx2 = mn * (d + 1)
        if (mx2 >= mx) {
          out.print("YES")
        }
        else {
          out.print("NO")
        }
        out.endl()
      }
    }
  }

  // ===========================================================================
  // ---------  TOOLS  ---------------------------------------------------------
  // ===========================================================================

  class InputReader(reader: Reader) {

    import java.io.BufferedReader
    import java.util.StringTokenizer

    private val buffer = new BufferedReader(reader)
    private var parser: StringTokenizer = _

    private def next = {
      if (parser == null || !parser.hasMoreElements) {
        parser = new StringTokenizer(buffer.readLine)
      }
      parser.nextToken
    }

    def endl(): Unit = {
      parser = null
    }

    def nextByte = next.toByte

    def forBytes(num: Int)(op: (Int, Byte) => Unit): Unit = forr(num, nextByte, op)

    def nextInt = next.toInt

    def forInts(num: Int)(op: (Int, Int) => Unit): Unit = forr(num, nextInt, op)

    def nextLong = next.toLong

    def forLongs(num: Int)(op: (Int, Long) => Unit): Unit = forr(num, nextLong, op)

    def nextDouble = next.toDouble

    def forDoubled(num: Int)(op: (Int, Double) => Unit): Unit = forr(num, nextDouble, op)

    def nextString = next

    def forStrings(num: Int)(op: (Int, String) => Unit): Unit = forr(num, nextString, op)

    private def forr[T](num: Int, readOp: => T, op: (Int, T) => Unit): Unit = {
      for (index <- 0 until num) op(index, readOp)
    }
  }

  class OutputPrinter {
    private val buffer = new StringBuilder() // faster if exists

    def print(c: Char): Unit = {}

    def print(i: Int): Unit = {}

    def print(s: String): Unit = {}

    def endl(): Unit = {}

    def flush(): Unit = {}
  }

  class StringOutputPrinter(capacity: Int = 1024) extends OutputPrinter {
    private val buffer = new StringBuilder(capacity)

    override def print(c: Char): Unit = buffer.append(c)

    override def print(i: Int): Unit = buffer.append(i)

    override def print(s: String): Unit = buffer.append(s)

    override def endl(): Unit = buffer.append("\n")

    override def flush(): Unit = {
      println(buffer.result())
      buffer.clear()
    }
  }

}


There are two types of burgers in your restaurant — hamburgers and chicken burgers! To assemble a hamburger you need two buns and a beef patty. To assemble a chicken burger you need two buns and a chicken cutlet. You have $$$b$$$ buns, $$$p$$$ beef patties and $$$f$$$ chicken cutlets in your restaurant. You can sell one hamburger for $$$h$$$ dollars and one chicken burger for $$$c$$$ dollars. Calculate the maximum profit you can achieve.You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains three integers $$$b$$$, $$$p$$$ and $$$f$$$ ($$$1 \le b, ~p, ~f \le 100$$$) — the number of buns, beef patties and chicken cutlets in your restaurant. The second line of each query contains two integers $$$h$$$ and $$$c$$$ ($$$1 \le h, ~c \le 100$$$) — the hamburger and chicken burger prices in your restaurant.

For each query print one integer — the maximum profit you can achieve.

NoteIn first query you have to sell two hamburgers and three chicken burgers. Your income is $$$2 \cdot 5 + 3 \cdot 10 = 40$$$.In second query you have to ell one hamburgers and two chicken burgers. Your income is $$$1 \cdot 10 + 2 \cdot 12 = 34$$$.In third query you can not create any type of burgers because because you have only one bun. So your income is zero.

object Solution {

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

    import scala.io.StdIn

    val t = StdIn.readLine.trim.toInt
    (0 until t).foreach(_ => {
      var arr = StdIn.readLine.trim.split(" ").map(_.toString.toInt)
      var (b, p, f) = (arr(0), arr(1), arr(2))
      arr = StdIn.readLine.trim.split(" ").map(_.toString.toInt)
      var (h, c) = (arr(0), arr(1))
      if (h < c) {
        var temp = h
        h = c
        c = temp

        temp = p
        p = f
        f = temp
      }

      val sum = if (b <= p * 2) b / 2 * h
      else if (b < p * 2 + f * 2) p * h + (b - p * 2) / 2 * c
      else p * h + f * c
      println(sum)
    })
  }
}


William is a huge fan of planning ahead. That is why he starts his morning routine by creating a nested list of upcoming errands.A valid nested list is any list which can be created from a list with one item "1" by applying some operations. Each operation inserts a new item into the list, on a new line, just after one of existing items $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \,\cdots\, \,.\,a_k$$$ and can be one of two types:   Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, a_k \,.\, 1$$$ (starting a list of a deeper level), or  Add an item $$$a_1 \,.\, a_2 \,.\, a_3 \,.\, \cdots \,.\, (a_k + 1)$$$ (continuing the current level).  Operation can only be applied if the list does not contain two identical items afterwards. And also, if we consider every item as a sequence of numbers, then the sequence of items should always remain increasing in lexicographical order. Examples of valid and invalid lists that are shown in the picture can found in the "Notes" section.When William decided to save a Word document with the list of his errands he accidentally hit a completely different keyboard shortcut from the "Ctrl-S" he wanted to hit. It's not known exactly what shortcut he pressed but after triggering it all items in the list were replaced by a single number: the last number originally written in the item number.William wants you to help him restore a fitting original nested list.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^3$$$), which is the number of lines in the list. Each of the next $$$n$$$ lines contains a single integer $$$a_i$$$ ($$$1 \le a_i \le n$$$), which is what remains of William's nested list. It is guaranteed that in each test case at least one fitting list exists. It is guaranteed that the sum of values $$$n$$$ across all test cases does not exceed $$$10^3$$$.

For each test case output $$$n$$$ lines which represent a valid nested list, which could become the data provided to you by William. If there are multiple answers, print any.

NoteIn the second example test case one example of a fitting list is:11.1 1.1.11.1.21.21.2.122.12.2This list can be produced by using the sequence of operations shown below:    Original list with a single item $$$1$$$.  Insert item $$$2$$$ by using the insertion operation of the second type after item $$$1$$$.  Insert item $$$1.1$$$ by using the insertion operation of the first type after item $$$1$$$.  Insert item $$$1.2$$$ by using the insertion operation of the second type after item $$$1.1$$$.  Insert item $$$1.1.1$$$ by using the insertion operation of the first type after item $$$1.1$$$.  Insert item $$$1.1.2$$$ by using the insertion operation of the second type after item $$$1.1.1$$$.  Insert item $$$1.2.1$$$ by using the insertion operation of the first type after item $$$1.2$$$.  Insert item $$$2.1$$$ by using the insertion operation of the first type after item $$$2$$$.  Insert item $$$2.2$$$ by using the insertion operation of the second type after item $$$2.1$$$.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = Array.fill(n)(readShort())

    def go(level: List[Short], i: Int): Unit =
      if (i == n) ()
      else {
        val ai   = an(i)
        val next =
          if (ai == 1) (1: Short) :: level
          else if (ai == level.head + 1) ai :: level.tail
          else ai :: level.dropWhile(_ + 1 != ai).tail

        println(next.reverse.mkString("."))

        go(next, i + 1)
      }

    go(Nil, 0)
  }
}


Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with $$$n$$$ elements. The $$$i$$$-th element is $$$a_i$$$ ($$$i$$$ = $$$1, 2, \ldots, n$$$). He gradually takes the first two leftmost elements from the deque (let's call them $$$A$$$ and $$$B$$$, respectively), and then does the following: if $$$A > B$$$, he writes $$$A$$$ to the beginning and writes $$$B$$$ to the end of the deque, otherwise, he writes to the beginning $$$B$$$, and $$$A$$$ writes to the end of the deque. We call this sequence of actions an operation.For example, if deque was $$$[2, 3, 4, 5, 1]$$$, on the operation he will write $$$B=3$$$ to the beginning and $$$A=2$$$ to the end, so he will get $$$[3, 4, 5, 1, 2]$$$.The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him $$$q$$$ queries. Each query consists of the singular number $$$m_j$$$ $$$(j = 1, 2, \ldots, q)$$$. It is required for each query to answer which two elements he will pull out on the $$$m_j$$$-th operation.Note that the queries are independent and for each query the numbers $$$A$$$ and $$$B$$$ should be printed in the order in which they will be pulled out of the deque.Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 10^5$$$, $$$0 \leq q \leq 3 \cdot 10^5$$$) — the number of elements in the deque and the number of queries. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$, where $$$a_i$$$ $$$(0 \leq a_i \leq 10^9)$$$ — the deque element in $$$i$$$-th position. The next $$$q$$$ lines contain one number each, meaning $$$m_j$$$ ($$$1 \leq m_j \leq 10^{18}$$$).

For each teacher's query, output two numbers $$$A$$$ and $$$B$$$ — the numbers that Valeriy pulls out of the deque for the $$$m_j$$$-th operation.

//package round569

import scala.io.StdIn._

object TaskC extends App {
  val Array(n, q) = readLine.split(" ").map(_.toInt)

  var maxElement = Integer.MIN_VALUE

  val arr = readLine.split(" ").map(_.toInt)

  val copy = arr.clone()

  val maxVals = arr.map{x => if(x > maxElement) {maxElement = x; x}  else maxElement}

  for (i <- 1 to n-1) {
    if (arr(i-1) > arr(i)) {
      val temp = arr(i-1)
      arr(i-1) = arr(i)
      arr(i) = temp
    }
  }

  for (_ <- 1 to q) {
    val m = readLong
    if (m < n.toLong) {
      println(s"${maxVals(m.toInt-1)} ${copy(m.toInt)}")
    } else {
      val idx = ((m-1) % (n-1)).toInt
      println(s"${arr(n-1)} ${arr(idx)}")
    }
  }
}

//package round569

import scala.io.StdIn._

object TaskC extends App {
  val Array(n, q) = readLine.split(" ").map(_.toInt)

  var maxElement = Integer.MIN_VALUE

  val arr = readLine.split(" ").map(_.toInt)

  val copy = arr.clone()

  val maxVals = arr.map{x => if(x > maxElement) {maxElement = x; x}  else maxElement}

  for (i <- 1 to n-1) {
    if (arr(i-1) > arr(i)) {
      val temp = arr(i-1)
      arr(i-1) = arr(i)
      arr(i) = temp
    }
  }

  for (_ <- 1 to q) {
    val m = readLong
    if (m < n.toLong) {
      println(s"${maxVals(m.toInt-1)} ${copy(m.toInt)}")
    } else {
      val idx = ((m+1) % n).toInt
      println(s"${arr(n-1)} ${arr(idx)}")
    }
  }
}


You are given array $$$a_1, a_2, \dots, a_n$$$. Find the subsegment $$$a_l, a_{l+1}, \dots, a_r$$$ ($$$1 \le l \le r \le n$$$) with maximum arithmetic mean $$$\frac{1}{r - l + 1}\sum\limits_{i=l}^{r}{a_i}$$$ (in floating-point numbers, i.e. without any rounding).If there are many such subsegments find the longest one.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$) — the array $$$a$$$.

Print the single integer — the length of the longest subsegment with maximum possible arithmetic mean.

NoteThe subsegment $$$[3, 4]$$$ is the longest among all subsegments with maximum arithmetic mean.

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)

    val mx = A.max
    var cnt = 0
    var ans = 0
    REP(N) { i =>
      if (A(i) == mx) cnt += 1
      else cnt = 0
      ans = max(ans, cnt)
    }

    out.println(ans)
  }

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


Tokitsukaze has a sequence $$$a$$$ of length $$$n$$$. For each operation, she selects two numbers $$$a_i$$$ and $$$a_j$$$ ($$$i \ne j$$$; $$$1 \leq i,j \leq n$$$).   If $$$a_i = a_j$$$, change one of them to $$$0$$$.  Otherwise change both of them to $$$\min(a_i, a_j)$$$. Tokitsukaze wants to know the minimum number of operations to change all numbers in the sequence to $$$0$$$. It can be proved that the answer always exists.

The first line contains a single positive integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. For each test case, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 100$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 100$$$) — the sequence $$$a$$$.

For each test case, print a single integer — the minimum number of operations to change all numbers in the sequence to $$$0$$$.

NoteIn the first test case, one of the possible ways to change all numbers in the sequence to $$$0$$$:In the $$$1$$$-st operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = a_1 = 1$$$. Now the sequence $$$a$$$ is $$$[1,1,3]$$$.In the $$$2$$$-nd operation, $$$a_1 = a_2 = 1$$$, after the operation, $$$a_1 = 0$$$. Now the sequence $$$a$$$ is $$$[0,1,3]$$$.In the $$$3$$$-rd operation, $$$a_1 < a_2$$$, after the operation, $$$a_2 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,3]$$$.In the $$$4$$$-th operation, $$$a_2 < a_3$$$, after the operation, $$$a_3 = 0$$$. Now the sequence $$$a$$$ is $$$[0,0,0]$$$.So the minimum number of operations is $$$4$$$.

object Task1 extends App {

  import scala.io.StdIn

  def readLine: String = StdIn.readLine()

  def readNum: Int = StdIn.readLine().toInt

  val testCases = readNum

  for (_ <- 0 until testCases) {
    readLine
    val nums = readLine.split(" ").map(_.toInt)

    val numsSet = nums.toSet

    if (numsSet.contains(0)) {
      val zerosCount = nums.count(_ == 0)
      println(nums.length - zerosCount)
    } else {
      if (numsSet.size == nums.length) {
        println(nums.length + 1)
      } else {
        println(nums.length)
      }
    }
  }

}


You are given a string $$$s$$$. You have to reverse it — that is, the first letter should become equal to the last letter before the reversal, the second letter should become equal to the second-to-last letter before the reversal — and so on. For example, if your goal is to reverse the string "abddea", you should get the string "aeddba". To accomplish your goal, you can swap the neighboring elements of the string. Your task is to calculate the minimum number of swaps you have to perform to reverse the given string.

The first line contains one integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the length of $$$s$$$. The second line contains $$$s$$$ — a string consisting of $$$n$$$ lowercase Latin letters.

Print one integer — the minimum number of swaps of neighboring elements you have to perform to reverse the string.

NoteIn the first example, you have to swap the third and the fourth elements, so the string becomes "aazaa". Then you have to swap the second and the third elements, so the string becomes "azaaa". So, it is possible to reverse the string in two swaps.Since the string in the second example is a palindrome, you don't have to do anything to reverse it.

object E {
  import InOut._
  def main(args: Array[String]): Unit = {

    val n = nextInt
    val s = nextLine
    val s2 = s.reverse
    val pos = Array.fill(n)(-1)

    def countInversions(xs: Array[Int]): (Long, Array[Int]) = {

      if (xs.size == 1) (0, xs)
      else {
        val mid = xs.size / 2
        val (lInv, ls) = countInversions(xs.take(mid))
        val (rInv, rs) = countInversions(xs.drop(mid))
        val res = Array.ofDim[Int](xs.size)
        var i, j, k = 0
        var mInv = 0L
        while (k < xs.size) {
          if (j == rs.size || (i < ls.size && ls(i) < rs(j))) {
            res(k) = ls(i)
            i += 1
          } else {
            res(k) = rs(j)
            mInv += (ls.size - i)
            j += 1
          }
          k += 1
        }
        (lInv + rInv + mInv, res)
      }
    }

    for (c <- 'a' to 'z') {
      var i, j = 0
      while (i < n) {
        while (i < n && s(i) != c) {
          i += 1
        }
        if (i < n) {
          while (s2(j) != c) {
            j += 1
          }
          pos(i) = j
          i += 1
          j += 1
        }
      }
    }

    val (res, _) = countInversions(pos)

    out.println(res)
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}


Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1), (n, 1), (1, m), (n, m).Simon thinks that some cells in this table are good. Besides, it's known that no good cell is the corner of the table. Initially, all cells of the table are colorless. Simon wants to color all cells of his table. In one move, he can choose any good cell of table (x1, y1), an arbitrary corner of the table (x2, y2) and color all cells of the table (p, q), which meet both inequations: min(x1, x2) ≤ p ≤ max(x1, x2), min(y1, y2) ≤ q ≤ max(y1, y2).Help Simon! Find the minimum number of operations needed to color all cells of the table. Note that you can color one cell multiple times.

The first line contains exactly two integers n, m (3 ≤ n, m ≤ 50). Next n lines contain the description of the table cells. Specifically, the i-th line contains m space-separated integers ai1, ai2, ..., aim. If aij equals zero, then cell (i, j) isn't good. Otherwise aij equals one. It is guaranteed that at least one cell is good. It is guaranteed that no good cell is a corner.

Print a single number — the minimum number of operations Simon needs to carry out his idea.

NoteIn the first sample, the sequence of operations can be like this:    For the first time you need to choose cell (2, 2) and corner (1, 1).  For the second time you need to choose cell (2, 2) and corner (3, 3).  For the third time you need to choose cell (2, 2) and corner (3, 1).  For the fourth time you need to choose cell (2, 2) and corner (1, 3). In the second sample the sequence of operations can be like this:    For the first time you need to choose cell (3, 1) and corner (4, 3).  For the second time you need to choose cell (2, 3) and corner (1, 1).

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).foldLeft(false) {
    case(true, _) => true
    case(false, 1) => in.next().split(' ').map(_.toInt).contains(1)
    case(false, i) if i == n => in.next().split(' ').map(_.toInt).contains(1)
    case(false, _) =>
      val data = in.next().split(' ').map(_.toInt)
      data.head == 1 || data.last == 1
  }
  if (res)
    println(2)
  else
    println(4)
}

object A359 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = Array.fill(n)(readInts(m))
    val ids = cu.ArrayBuffer.empty[(Int, Int)]
    for(i <- 0 until n; j <- 0 until m) {
      if(a(i)(j) == 1)
        ids.append((i, j))
    }
    if(a(0)(0) == 1 || a(0)(m-1) == 1 || a(n-1)(0) == 1 || a(n-1)(m-1) == 1)
      println("1")
    else if(ids.exists{case (x,y) => x==0 || x==n-1 || y==0 || y==m-1}) {
      println("2")
    } else {
      println("4")
    }
  }

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

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

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

  // n rows
  // m cols

  val N, M = sc.nextInt
  val T = Array.fill(N, M)(sc.nextInt)

  var t = 0
  for (i <- 0 until M) {
    t += T(0)(i)
    t += T(N - 1)(i)
  }
  for (i <- 0 until N) {
    t += T(i)(0)
    t += T(i)(M - 1)
  }

  val answer = if (t > 0) 2
               else 4

  out.println(answer)
  out.close
}

object Main {
  def main(args: Array[String]) {
    val nm = readLine().split(" ").map(_.toInt)
    val n = nm(0)
    val m = nm(1)
    val a = (1 to n).map(_ => readLine())

    val rows = a.head.find(_ == '1').isDefined || a.last.find(_ == '1').isDefined
    val cols = a.find(row => row.head == '1' || row.last == '1').isDefined

    if (rows || cols) println("2")
    else println("4")
  }
}


The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 1310 = 11012, so it has 3 bits set and 13 will be reduced to 3 in one operation.He calls a number special if the minimum number of operations to reduce it to 1 is k.He wants to find out how many special numbers exist which are not greater than n. Please help the Travelling Salesman, as he is about to reach his destination!Since the answer can be large, output it modulo 109 + 7.

The first line contains integer n (1 ≤ n < 21000). The second line contains integer k (0 ≤ k ≤ 1000). Note that n is given in its binary representation without any leading zeros.

Output a single integer — the number of special numbers not greater than n, modulo 109 + 7.

NoteIn the first sample, the three special numbers are 3, 5 and 6. They get reduced to 2 in one operation (since there are two set bits in each of 3, 5 and 6) and then to 1 in one more operation (since there is only one set bit in 2).

object C extends App {

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

  val MOD = 1000000007
  val n = readLine
  val nn = n.length
  val Array(k) = readInts(1)

  val pascal = Array.ofDim[Long](1001, 1001)
  for (i <- pascal.indices) pascal(i)(0) = 1L
  for (i <- 1 until pascal.length) {
    for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD
  }

  val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)

  var counts = Array.fill(nn + 1) { 0L }
  counts(1) = 1L

  for (_ <- 1 until k) {
    val counts2 = Array.fill(nn + 1) { 0L }
    for (i <- 1 to nn) {
      if (counts(i) > 0) {
        for (b <- byBitCount(i)) if (counts(b) == 0) {
          counts2(b) = (counts2(b) + counts(i)) % MOD
        }
      }
    }
    counts = counts2
  }

  var res = counts(n.count(_ == '1'))

  for (ones <- counts.indices) {
    if (counts(ones) > 0) {
      var onesUsed = 0
      for (i <- 0 until nn) {
        if (n(i) == '1') {
          val remainingBits = n.length - i - 1
          val remainingOnes = ones - onesUsed
          if (remainingOnes >= 0) {
            res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD
          }
          onesUsed += 1
        }
      }
    }
  }

  println(if (k == 0) 1 else if (k == 1) nn - 1L else res)
}

object C extends App {

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

  val MOD = 1000000007
  val n = readLine
  val nn = n.length
  val Array(k) = readInts(1)

  val pascal = Array.ofDim[Long](1001, 1001)
  for (i <- pascal.indices) pascal(i)(0) = 1L
  for (i <- 1 until pascal.length) {
    for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD
  }

  val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)

  var counts = Array.fill(nn + 1) { 0L }
  counts(1) = 1L

  for (_ <- 1 until k) {
    val counts2 = Array.fill(nn + 1) { 0L }
    for (i <- 1 to nn) {
      if (counts(i) > 0) {
        for (b <- byBitCount(i)) if (counts(b) == 0) {
          counts2(b) = (counts2(b) + counts(i)) % MOD
        }
      }
    }
    counts = counts2
  }

  var res = if (k == 1) 0L else counts(n.count(_ == '1'))

  for (ones <- counts.indices) {
    if (counts(ones) > 0) {
      var onesUsed = 0
      for (i <- 0 until nn) {
        if (n(i) == '1') {
          val remainingBits = n.length - i - 1
          val remainingOnes = ones - onesUsed
          if (remainingOnes >= 0) {
            res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD
          }
          onesUsed += 1
        }
      }
    }
  }

  println(if (k == 0) 1 else res)
}

object C extends App {

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

  val MOD = 1000000007
  val n = readLine
  val nn = n.length
  val Array(k) = readInts(1)

  val pascal = Array.ofDim[Long](1001, 1001)
  for (i <- pascal.indices) pascal(i)(0) = 1L
  for (i <- 1 until pascal.length) {
    for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD
  }

  val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)

  var counts = Array.fill(nn + 1) { 0L }
  counts(1) = 1L

  for (_ <- 1 until k) {
    val counts2 = Array.fill(nn + 1) { 0L }
    for (i <- 1 to nn) {
      if (counts(i) > 0) {
        for (b <- byBitCount(i)) if (counts(b) == 0) {
          counts2(b) = (counts2(b) + counts(i)) % MOD
        }
      }
    }
    counts = counts2
  }

  var res = counts(n.count(_ == '1'))

  for (ones <- counts.indices) {
    if (counts(ones) > 0) {
      var onesUsed = 0
      for (i <- 0 until nn) {
        if (n(i) == '1') {
          val remainingBits = n.length - i - 1
          val remainingOnes = ones - onesUsed
          if (remainingOnes >= 0) {
            res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD
          }
          onesUsed += 1
        }
      }
    }
  }

  println(if (k == 0) 1 else res)
}

object C extends App {

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

  val MOD = 1000000007
  val n = readLine
  val nn = n.length
  val Array(k) = readInts(1)

  var counts = Array.fill(nn + 1) { 0L }
  counts(1) = 1L

  val pascal = Array.ofDim[Long](1001, 1001)
  for (i <- pascal.indices) pascal(i)(0) = 1L
  for (i <- 1 until pascal.length) {
    for (j <- 1 until pascal(i).length) pascal(i)(j) = (pascal(i - 1)(j - 1) + pascal(i - 1)(j)) % MOD
  }

  val byBitCount = (1 to nn).groupBy(Integer.bitCount).withDefaultValue(Nil)

  for (_ <- 1 until k) {
    val counts2 = Array.fill(nn + 1) { 0L }
    for (i <- 1 to nn) {
      if (counts(i) > 0) {
        for (b <- byBitCount(i)) if (counts(b) == 0) {
          counts2(b) = (counts2(b) + counts(i)) % MOD
        }
      }
    }
    counts = counts2
  }

  var res = counts(n.count(_ == '1'))

  for (ones <- counts.indices) {
    if (counts(ones) > 0) {
      var onesUsed = 0
      for (i <- 0 until nn) {
        if (n(i) == '1') {
          val remainingBits = n.length - i - 1
          val remainingOnes = ones - onesUsed
          if (remainingOnes >= 0) {
            res = (res + pascal(remainingBits)(remainingOnes) * counts(ones)) % MOD
          }
          onesUsed += 1
        }
      }
    }
  }

  println(res)
}


Mikhail the Freelancer dreams of two things: to become a cool programmer and to buy a flat in Moscow. To become a cool programmer, he needs at least p experience points, and a desired flat in Moscow costs q dollars. Mikhail is determined to follow his dreams and registered at a freelance site.He has suggestions to work on n distinct projects. Mikhail has already evaluated that the participation in the i-th project will increase his experience by ai per day and bring bi dollars per day. As freelance work implies flexible working hours, Mikhail is free to stop working on one project at any time and start working on another project. Doing so, he receives the respective share of experience and money. Mikhail is only trying to become a cool programmer, so he is able to work only on one project at any moment of time.Find the real value, equal to the minimum number of days Mikhail needs to make his dream come true.For example, suppose Mikhail is suggested to work on three projects and a1 = 6, b1 = 2, a2 = 1, b2 = 3, a3 = 2, b3 = 6. Also, p = 20 and q = 20. In order to achieve his aims Mikhail has to work for 2.5 days on both first and third projects. Indeed, a1·2.5 + a2·0 + a3·2.5 = 6·2.5 + 1·0 + 2·2.5 = 20 and b1·2.5 + b2·0 + b3·2.5 = 2·2.5 + 3·0 + 6·2.5 = 20.

The first line of the input contains three integers n, p and q (1 ≤ n ≤ 100 000, 1 ≤ p, q ≤ 1 000 000) — the number of projects and the required number of experience and money. Each of the next n lines contains two integers ai and bi (1 ≤ ai, bi ≤ 1 000 000) — the daily increase in experience and daily income for working on the i-th project.

Print a real value — the minimum number of days Mikhail needs to get the required amount of experience and money. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteFirst sample corresponds to the example in the problem statement.

object E{
  //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

      val t0 = System.nanoTime()

    //code starts here
    val (n,p,q)=(nextInt,nextDouble,nextDouble)

    val ab=(for(i<-0 until n) yield (nextLong,nextLong)).distinct.sorted
    var maxBi=0
    var maxB:Double=0
    val idx=Array.ofDim[Int](n)
    for(i<-0 until ab.length){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    var il=0
    idx(il)=maxBi
    il+=1
    if(maxBi<ab.length-1){
      idx(il)=maxBi+1
      il+=1
    }
    for(i<-maxBi+2 until ab.length){
      while(il>1 &&  (ab(i)._2-ab(idx(il-1))._2)*(ab(idx(il-1))._1-ab(idx(il-2))._1)>(ab(idx(il-1))._2-ab(idx(il-2))._2)*(ab(i)._1-ab(idx(il-1))._1)){
        il-=1
      }
      idx(il)=i
      il+=1
    }
    if(ab(idx(0))._2*p<=q*ab(idx(0))._1){
      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(il - 1))._2)*p >= q* (ab(idx(il-1))._1)){

      out.println(p/(ab(idx(il-1))._1))
    }
    else{
      var l=0
      var r=il
      while(l<r-1){
        val mid=(l+r)/2
        if(ab(idx(mid))._2*p>q*ab(idx(mid))._1){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=p*b2-q*a2
      val Dy= -p*b1+q*a1
      out.println((Dx+Dy)/D)
    }

    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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 (n,p,q)=(nextInt,nextDouble,nextDouble)
    val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)
    val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct
    var maxBi=0
    var maxB:Double=0
    val idx=ArrayBuffer[Int]()
    for(i<-0 until ab.length){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    idx+=maxBi
    if(maxBi<ab.length-1){
      idx+=maxBi+1
    }

    for(i<-maxBi+2 until ab.length){

      while(idx.length>1 &&  (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){
        idx-=idx(idx.length-1)

        out.flush
      }
      idx+=i
    }

    if(ab(idx(0))._2/ab(idx(0))._1<=q/p){
      if(n==100000){
        out.println("1")
      }
      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){
      if(n==100000){
        out.println("2")
      }
      out.println(p/(ab(idx(idx.length-1))._1))
    }
    else{
      var l=0
      var r=idx.length
      while(l<r-1){
        val mid=(l+r)/2
        val k=ab(idx(mid))._2/ab(idx(mid))._1
        if(k>q/p){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=q*b2-p*a2
      val Dy= -q*b1+p*a1
      if(n==100000){
        out.println("3 "+l+" "+r)
      }
      //out.println(D+" "+Dx+" "+Dy)
      out.println((Dx+Dy)/D)

    }

    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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 (n,p,q)=(nextInt,nextDouble,nextDouble)
    val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)
    val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct
    var maxBi=0
    var maxB:Double=0
    val idx=ArrayBuffer[Int]()
    for(i<-0 until ab.length){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    idx+=maxBi
    if(maxBi<ab.length-1){
      idx+=maxBi+1
    }

    for(i<-maxBi+2 until ab.length){

      while(idx.length>1 &&  (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){
        idx-=idx(idx.length-1)

        out.flush
      }
      idx+=i
    }

    if(ab(idx(0))._2/ab(idx(0))._1<=q/p){

      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){

      out.println(p/(ab(idx(idx.length-1))._1))
    }
    else{
      var l=0
      var r=idx.length
      while(l<r-1){
        val mid=(l+r)/2
        val k=ab(idx(mid))._2/ab(idx(mid))._1
        if(k>q/p){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=q*b2-p*a2
      val Dy= -q*b1+p*a1
      if(n==100000){
        out.println("3 "+l+" "+r)
        out.println(a1+" "+b1)
        out.println(a2+" "+b2)
        out.println(D+" "+Dx+" "+Dy)
      }

      out.println((Dx+Dy)/D)

    }

    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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 (n,p,q)=(nextInt,nextDouble,nextDouble)
    val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)
    val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct
    var maxBi=0
    var maxB:Double=0
    val idx=ArrayBuffer[Int]()
    for(i<-0 until ab.length){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    idx+=maxBi
    if(maxBi<ab.length-1){
      idx+=maxBi+1
    }

    for(i<-maxBi+2 until ab.length){

      while(idx.length>1 &&  (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){
        idx-=idx(idx.length-1)

        out.flush
      }
      idx+=i
    }
    //out.println(idx)
    //ab.foreach(m=>out.println(m))
    if(ab(idx(0))._2/ab(idx(0))._1<=q/p){
      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){
      out.println(p/(ab(idx(idx.length-1))._1))
    }
    else{
      var l=0
      var r=idx.length
      while(l<r-1){
        val mid=(l+r)/2
        val k=ab(idx(mid))._2/ab(idx(mid))._1
        if(k>q/p){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=q*b2-p*a2
      val Dy= -q*b1+p*a1
      //out.println(D+" "+Dx+" "+Dy)
      out.println((Dx+Dy)/D)

    }

    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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 (n,p,q)=(nextInt,nextDouble,nextDouble)
    val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)
    val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1)
    var maxBi=0
    var maxB:Double=0
    val idx=ArrayBuffer[Int]()
    for(i<-0 until n){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    idx+=maxBi
    if(maxBi<n-1){
      idx+=maxBi+1
    }

    for(i<-maxBi+2 until n){

      while(idx.length>1 &&  (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){
        idx-=idx(idx.length-1)

        out.flush
      }
      idx+=i
    }
    //out.println(idx)
    //ab.foreach(m=>out.println(m))
    if(ab(idx(0))._2/ab(idx(0))._1<q/p){
      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) > q / p){
      out.println(p/(ab(idx(idx.length-1))._1))
    }
    else{
      var l=0
      var r=idx.length
      while(l<r-1){
        val mid=(l+r)/2
        val k=ab(idx(mid))._2/ab(idx(mid))._1
        if(k>q/p){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=q*b2-p*a2
      val Dy= -q*b1+p*a1
      //out.println(D+" "+Dx+" "+Dy)
      out.println((Dx+Dy)/D)

    }

    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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 (n,p,q)=(nextInt,nextDouble,nextDouble)
    val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)
    val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1)
    var maxBi=0
    var maxB:Double=0
    val idx=ArrayBuffer[Int]()
    for(i<-0 until n){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    idx+=maxBi
    if(maxBi<n-1){
      idx+=maxBi+1
    }

    for(i<-maxBi+2 until n){

      while(idx.length>1 &&  (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){
        idx-=idx(idx.length-1)
        out.println(idx)
        out.flush
      }
      idx+=i
    }
    //out.println(idx)
    //ab.foreach(m=>out.println(m))
    if(ab(idx(0))._2/ab(idx(0))._1<q/p){
      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) > q / p){
      out.println(p/(ab(idx(idx.length-1))._1))
    }
    else{
      var l=0
      var r=idx.length
      while(l<r-1){
        val mid=(l+r)/2
        val k=ab(idx(mid))._2/ab(idx(mid))._1
        if(k>q/p){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=q*b2-p*a2
      val Dy= -q*b1+p*a1
      //out.println(D+" "+Dx+" "+Dy)
      out.println((Dx+Dy)/D)

    }

    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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

      val t0 = System.nanoTime()

    //code starts here
    val (n,p,q)=(nextInt,nextDouble,nextDouble)

    val ab=(for(i<-0 until n) yield (nextLong,nextLong)).distinct.sorted
    var maxBi=0
    var maxB:Double=0
    val idx=Array.ofDim[Int](n)
    for(i<-0 until ab.length){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    var il=0
    idx(il)=maxBi
    il+=1
    if(maxBi<ab.length-1){
      idx(il)=maxBi+1
      il+=1
    }
    if(n==100000 && p==487300){
      val t1 = System.nanoTime()
      out.println("Elapsed time: " + (t1 - t0) + "ns")
      out.flush

    }
    for(i<-maxBi+2 until ab.length){
      if(n==100000 && p==487300 && i%(ab.length/10)==0){
        val t1 = System.nanoTime()
        out.println("i="+i)
        out.println("Elapsed time: " + (t1 - t0) + "ns")
        out.flush
      }
      while(il>1 &&  (ab(i)._2-ab(idx(il-1))._2)*(ab(idx(il-1))._1-ab(idx(il-2))._1)>(ab(idx(il-1))._2-ab(idx(il-2))._2)*(ab(i)._1-ab(idx(il-1))._1)){
        il-=1
      }
      idx(il)=i
      il+=1
    }
    if(n==100000 && p==487300){
      val t1 = System.nanoTime()
      out.println("Elapsed time: " + (t1 - t0) + "ns")
      out.flush
    }
    if(ab(idx(0))._2*p<=q*ab(idx(0))._1){
      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(il - 1))._2)*p >= q* (ab(idx(il-1))._1)){

      out.println(p/(ab(idx(il-1))._1))
    }
    else{
      var l=0
      var r=il
      while(l<r-1){
        val mid=(l+r)/2
        if(ab(idx(mid))._2*p>q*ab(idx(mid))._1){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=p*b2-q*a2
      val Dy= -p*b1+q*a1
      if(n==100000 && p==487300 ){
        val t1 = System.nanoTime()
        println("Elapsed time: " + (t1 - t0) + "ns")
        out.flush
      }
      out.println((Dx+Dy)/D)
    }

    //code ends here
    out.flush
    out.close
  }
}

object E{
  //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 (n,p,q)=(nextInt,nextDouble,nextDouble)
    val ab0=for(i<-0 until n) yield (nextDouble,nextDouble)
    val ab=scala.util.Sorting.stableSort(ab0, (e1: Tuple2[Double,Double], e2: Tuple2[Double,Double]) => e1._1 < e2._1).distinct
    var maxBi=0
    var maxB:Double=0
    val idx=ArrayBuffer[Int]()
    for(i<-0 until ab.length){
      if(maxB<ab(i)._2){
        maxB=ab(i)._2
        maxBi=i
      }
    }
    idx+=maxBi
    if(maxBi<ab.length-1){
      idx+=maxBi+1
    }

    for(i<-maxBi+2 until ab.length){

      while(idx.length>1 &&  (ab(i)._2-ab(idx(idx.length-1))._2)/(ab(i)._1-ab(idx(idx.length-1))._1)>(ab(idx(idx.length-1))._2-ab(idx(idx.length-2))._2)/(ab(idx(idx.length-1))._1-ab(idx(idx.length-2))._1)){
        idx-=idx(idx.length-1)

        out.flush
      }
      idx+=i
    }
    if(n==100000){
      out.println(idx)
      ab.foreach(m=>out.println(m))
    }
    if(ab(idx(0))._2/ab(idx(0))._1<=q/p){
      if(n==100000){
        out.println("1")
      }
      out.println(q/ab(idx(0))._2)
    }else if( (ab(idx(idx.length - 1))._2) / (ab(idx(idx.length-1))._1) >= q / p){
      if(n==100000){
        out.println("2")
      }
      out.println(p/(ab(idx(idx.length-1))._1))
    }
    else{
      var l=0
      var r=idx.length
      while(l<r-1){
        val mid=(l+r)/2
        val k=ab(idx(mid))._2/ab(idx(mid))._1
        if(k>q/p){
          l=mid
        }else{
          r=mid
        }
      }
      val (a1,b1)=ab(idx(l))
      val (a2,b2)=ab(idx(r))
      val D=a1*b2-a2*b1
      val Dx=q*b2-p*a2
      val Dy= -q*b1+p*a1
      if(n==100000){
        out.println("3 "+l+" "+r)
      }
      //out.println(D+" "+Dx+" "+Dy)
      out.println((Dx+Dy)/D)

    }

    //code ends here
    out.flush
    out.close
  }
}