We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name $$$s$$$ can transform to another superhero with name $$$t$$$ if $$$s$$$ can be made equal to $$$t$$$ by changing any vowel in $$$s$$$ to any other vowel and any consonant in $$$s$$$ to any other consonant. Multiple changes can be made.In this problem, we consider the letters 'a', 'e', 'i', 'o' and 'u' to be vowels and all the other letters to be consonants.Given the names of two superheroes, determine if the superhero with name $$$s$$$ can be transformed to the Superhero with name $$$t$$$.

The first line contains the string $$$s$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. The second line contains the string $$$t$$$ having length between $$$1$$$ and $$$1000$$$, inclusive. Both strings $$$s$$$ and $$$t$$$ are guaranteed to be different and consist of lowercase English letters only.

Output "Yes" (without quotes) if the superhero with name $$$s$$$ can be transformed to the superhero with name $$$t$$$ and "No" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first sample, since both 'a' and 'u' are vowels, it is possible to convert string $$$s$$$ to $$$t$$$.In the third sample, 'k' is a consonant, whereas 'a' is a vowel, so it is not possible to convert string $$$s$$$ to $$$t$$$.

object Problem_1111A {

  def main(args: Array[String]) {
    val scan = scala.io.StdIn
    val s1: String = scan.readLine()
    val s2: String = scan.readLine()

    if(s1.length != s2.length){
      print("No")
      return
    }

    var areSame= true;
    for (i <- 0 until s1.length) {
      if(isVowel(s1(i)) != isVowel(s2(i))){
        areSame =false
      }
    }

    if(areSame){
      print("Yes")
    }
    else{
      print("No")
    }

  }

  def isVowel(x : Char) ={
    val vowels: Array[Char] = Array('a','e','i','o','u')
    vowels.contains(x)
  }

}

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 S, T = ns()

    def tpe(c: Char) = c match {
      case 'a' | 'i' | 'u' | 'e' | 'o' => 1
      case _ => 2
    }

    if (S.length != T.length) {
      out.println("No")
    } else {
      var ok = true
      REP(S.length) { i =>
        ok &&= tpe(S(i)) == tpe(T(i))
      }
      if (ok) out.println("Yes")
      else out.println("No")
    }
  }

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

object A extends App {

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

  val Array(s) = readStrings(1)
  val Array(t) = readStrings(1)

  val cos = Seq('a', 'e', 'i', 'o', 'u')

  val matchCase = for {
    (cs, ct) <- s.zip(t)
    matches = cos.contains(cs) == cos.contains(ct)
  } yield matches

  if (matchCase.forall(_ == true) && s.length == t.length)
    println("yes")
  else
    print("no")

  Console.flush
}

object Main {

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val line1 = std.readLine()
    val line2 = std.readLine()

    val vowels = "aeiou"
    if (line1.length == line2.length) {
      if (line1.zip(line2).exists(x => vowels.contains(x._1) != vowels.contains(x._2))) {
        println("No")
      }
      else {
        println("Yes")
      }
    }
    else {
      println("No")
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val s, t = io.read[String]
    val vowels = "aeiou"
    val ans = s.length == t.length && s.zip(t).forall({case (a, b) => vowels.contains(a) == vowels.contains(b)})
    io.write(if (ans) "Yes" else "No" +
      "")
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

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

object A extends App {

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

  val Array(s) = readStrings(1)
  val Array(t) = readStrings(1)

  val cos = Seq('a', 'e', 'i', 'o', 'u')

  val matchCase = !s.zip(t).forall {
    case (c1, c2) => cos.contains(c1) ^ cos.contains(c2)
  }

  if (matchCase && s.length == t.length)
    println("yes")
  else
    print("no")

  Console.flush
}


There is a bus stop near the university. The lessons are over, and n students come to the stop. The i-th student will appear at the bus stop at time ti (all ti's are distinct).We shall assume that the stop is located on the coordinate axis Ox, at point x = 0, and the bus goes along the ray Ox, that is, towards the positive direction of the coordinate axis, and back. The i-th student needs to get to the point with coordinate xi (xi > 0).The bus moves by the following algorithm. Initially it is at point 0. The students consistently come to the stop and get on it. The bus has a seating capacity which is equal to m passengers. At the moment when m students get on the bus, it starts moving in the positive direction of the coordinate axis. Also it starts moving when the last (n-th) student gets on the bus. The bus is moving at a speed of 1 unit of distance per 1 unit of time, i.e. it covers distance y in time y.Every time the bus passes the point at which at least one student needs to get off, it stops and these students get off the bus. The students need 1 + [k / 2] units of time to get off the bus, where k is the number of students who leave at this point. Expression [k / 2] denotes rounded down k / 2. As soon as the last student leaves the bus, the bus turns around and goes back to the point x = 0. It doesn't make any stops until it reaches the point. At the given point the bus fills with students once more, and everything is repeated.If students come to the stop when there's no bus, they form a line (queue) and get on the bus in the order in which they came. Any number of students get on the bus in negligible time, you should assume that it doesn't take any time. Any other actions also take no time. The bus has no other passengers apart from the students.Write a program that will determine for each student the time when he got off the bus. The moment a student got off the bus is the moment the bus stopped at the student's destination stop (despite the fact that the group of students need some time to get off).

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of students and the number of passengers the bus can transport, correspondingly. Next n lines contain descriptions of the students, one per line. Each line contains a pair of integers ti, xi (1 ≤ ti ≤ 105, 1 ≤ xi ≤ 104). The lines are given in the order of strict increasing of ti. Values of xi can coincide.

Print n numbers w1, w2, ..., wn, wi — the moment of time when the i-th student got off the bus. Print the numbers on one line and separate them with single spaces.

NoteIn the first sample the bus waits for the first student for 3 units of time and drives him to his destination in additional 5 units of time. So the student leaves the bus at the moment of time 3 + 5 = 8.In the second sample the capacity of the bus equals 1, that's why it will drive the first student alone. This student is the same as the student from the first sample. So the bus arrives to his destination at the moment of time 8, spends 1 + [1 / 2] = 1 units of time on getting him off, and returns back to 0 in additional 5 units of time. That is, the bus returns to the bus stop at the moment of time 14. By this moment the second student has already came to the bus stop. So he immediately gets in the bus, and is driven to his destination in additional 5 units of time. He gets there at the moment 14 + 5 = 19. In the third sample the bus waits for the fourth student for 6 units of time, then drives for 5 units of time, then gets the passengers off for 1 + [4 / 2] = 3 units of time, then returns for 5 units of time, and then drives the fifth student for 1 unit of time.

import java.io._

object Solution {
  def main(args: Array[String]) {
    val in = new BufferedReader(new InputStreamReader(System.in))
    def readInts = in.readLine.split(" ").map(_.toInt).toList
    val n :: m :: _ = readInts
    val students = for(i <- 0 until n) yield {
      val t :: x :: _ = readInts
      (t, x, i)
    }
    var time = 0
    val ans = new Array[Int](n)
    for(chunk <- students grouped m) {
      time = (time /: chunk)(_ max _._1)
      val grouped = chunk.groupBy(_._2).toList
      val sorted = grouped.sortWith(_._1 < _._1)
      var biggestTime = 0
      for(l <- sorted) {
        for(s <- l._2) ans(s._3) = time + s._2
        time += 1 + l._2.length / 2
        biggestTime = l._1
      }
      time += biggestTime * 2
    }
    println(ans.mkString(" "))
  }
}


This is an interactive problem. Refer to the Interaction section below for better understanding.Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.This game will go on for m rounds. In each round, Ithea will give Chtholly an integer between 1 and c, and Chtholly needs to choose one of the sheets to write down this number (if there is already a number before, she will erase the original one and replace it with the new one).Chtholly wins if, at any time, all the sheets are filled with a number and the n numbers are in non-decreasing order looking from left to right from sheet 1 to sheet n, and if after m rounds she still doesn't win, she loses the game.Chtholly really wants to win the game as she wants to cook something for Willem. But she doesn't know how to win the game. So Chtholly finds you, and your task is to write a program to receive numbers that Ithea gives Chtholly and help her make the decision on which sheet of paper write this number.

The first line contains 3 integers n, m and c (,  means  rounded up) — the number of sheets, the number of rounds and the largest possible number Ithea can give to Chtholly respectively. The remaining parts of input are given throughout the interaction process.

NoteIn the example, Chtholly initially knew there were 2 sheets, 4 rounds and each number was between 1 and 4. She then received a 2 and decided to write it in the 1st sheet. Then she received a 1 and wrote it in the 2nd sheet. At last, she received a 3 and replaced 1 with 3 in the 2nd sheet. At this time all the sheets were filled with a number and they were non-decreasing, so she won the game. Note that it is required that your program terminate immediately after Chtholly wins and do not read numbers from the input for the remaining rounds. If not, undefined behaviour may arise and it won't be sure whether your program will be accepted or rejected. Also because of this, please be careful when hacking others' codes. In the sample, Chtholly won the game after the 3rd round, so it is required that your program doesn't read the number of the remaining 4th round.The input format for hacking:   The first line contains 3 integers n, m and c;  The following m lines each contains an integer between 1 and c, indicating the number given to Chtholly in each round.

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(-1)

  var solved = false
  while (!solved) {

    val p = readLine.toInt

    val pos = if (p > c / 2) {
      var j = n - 1
      while (xs(j) > 0 && p <= xs(j)) j -= 1
      j
    } else {
      var j = 0
      while (xs(j) > 0 && p >= xs(j)) j += 1
      j
    }

    xs(pos) = p

    println(pos + 1)
    Console.flush

    var i = 1
    solved = xs(0) > 0
    while (i < n && solved) {
      if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(-1)

  var solved = false
  while (!solved) {

    val p = readLine.toInt
    val cand = if (p == c) n - 1 else (p - 1) * n / c

    val pos = if (xs(cand) < 0) {
      cand
    } else if (p == xs(cand)) {
      var l = cand
      while (l > 0 && xs(l) == p) l -= 1
      var r = cand
      while (r < n - 1 && xs(r) == p) r += 1
      if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r
    } else if (p < xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1
      j
    } else if (p > xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1
      j
    } else -100

    xs(pos) = p
    //println(cand, xs.mkString(" "))

    println(pos + 1)
    Console.flush

    var i = 1
    solved = xs(0) > 0
    while (i < n && solved) {
      if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(-1)

  var solved = false
  while (!solved) {

    val p = readLine.toInt
    val cand = (p - 1) * n / c

    val pos = if (xs(cand) < 0) {
      cand
    } else if (xs(cand) == p) {
      var l = cand
      while (l > 0 && xs(l) == p) l -= 1
      var r = 0
      while (r < n - 1 && xs(r) == p) r += 1
      if (cand - l < r - cand && xs(l) != p) l else r
    } else if (p < xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1
      j
    } else if (p > xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1
      j
    } else -100

    xs(pos) = p
    //println(cand, xs.mkString(" "))

    println(pos + 1)
    Console.flush

    var i = 1
    solved = xs(0) > 0
    while (i < n && solved) {
      if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(-1)

  var solved = false
  while (!solved) {

    val p = readLine.toInt
    val cand = p * n / c - 1

    val pos = if (xs(cand) < 0) {
      cand
    } else if (p == xs(cand)) {
      var l = cand
      while (l > 0 && xs(l) == p) l -= 1
      var r = cand
      while (r < n - 1 && xs(r) == p) r += 1
      if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r
    } else if (p < xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1
      j
    } else if (p > xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1
      j
    } else -100

    xs(pos) = p
    //println(cand, xs.mkString(" "))

    println(pos + 1)
    Console.flush

    var i = 1
    solved = xs(0) > 0
    while (i < n && solved) {
      if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(-1)

  var solved = false
  while (!solved) {

    val p = readLine.toInt
    val cand = (p * n / c - 1) max 0

    val pos = if (xs(cand) < 0) {
      cand
    } else if (p == xs(cand)) {
      var l = cand
      while (l > 0 && xs(l) == p) l -= 1
      var r = cand
      while (r < n - 1 && xs(r) == p) r += 1
      if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r
    } else if (p < xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1
      j
    } else if (p > xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1
      j
    } else -100

    xs(pos) = p
    //println(cand, xs.mkString(" "))

    println(pos + 1)
    Console.flush

    var i = 1
    solved = xs(0) > 0
    while (i < n && solved) {
      if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(c + 100)

  var solved = false
  while (!solved) {

    val p = readLine.toInt
    val cand = (p - 1) * n / c

    val pos = if (xs(cand) > c) {
      cand
    } else if (xs(cand) == p) {
      var l = cand
      while (l > 0 && xs(l) == p) l -= 1
      var r = 0
      while (r < n - 1 && xs(r) == p) r += 1
      if (cand - l < r - cand && xs(l) != p) l else r
    } else if (p < xs(cand)) {
      var j = cand
      while (xs(j) <= c && j > 0 && p < xs(j)) j -= 1
      j
    } else if (p > xs(cand)) {
      var j = cand
      while (xs(j) <= c && j < n - 1 && p > xs(j)) j += 1
      j
    } else -100

    xs(pos) = p
    //println(cand, xs.mkString(" "))

    println(pos + 1)
    Console.flush

    var i = 1
    solved = true
    while (i < n && solved) {
      if (xs(i) > c || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(-1)

  var solved = false
  while (!solved) {

    val p = readLine.toInt

    val pos = if (p > c / 2) {
      var j = n - 1
      while (xs(j) > 0 && p < xs(j)) j -= 1
      j
    } else {
      var j = 0
      while (xs(j) > 0 && p > xs(j)) j += 1
      j
    }

    xs(pos) = p

    println(pos + 1)
    Console.flush

    var i = 1
    solved = xs(0) > 0
    while (i < n && solved) {
      if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}

object D extends App {

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

  val Array(n, m, c) = readInts(3)
  val xs = Array.fill(n)(-1)

  var solved = false
  while (!solved) {

    val p = readLine.toInt
    val cand = (p - 1) * n / c

    val pos = if (xs(cand) < 0) {
      cand
    } else if (p == xs(cand)) {
      var l = cand
      while (l > 0 && xs(l) == p) l -= 1
      var r = cand
      while (r < n - 1 && xs(r) == p) r += 1
      if (xs(r) == p || (cand - l < r - cand && xs(l) != p)) l else r
    } else if (p < xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j > 0 && p < xs(j)) j -= 1
      j
    } else if (p > xs(cand)) {
      var j = cand
      while (xs(j) > 0 && j < n - 1 && p > xs(j)) j += 1
      j
    } else -100

    xs(pos) = p
    //println(cand, xs.mkString(" "))

    println(pos + 1)
    Console.flush

    var i = 1
    solved = xs(0) > 0
    while (i < n && solved) {
      if (xs(i) < 0 || xs(i) < xs(i - 1)) solved = false
      i += 1
    }
  }
}


You are given two strings $$$s$$$ and $$$t$$$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $$$1$$$. You can't choose a string if it is empty.For example:  by applying a move to the string "where", the result is the string "here",  by applying a move to the string "a", the result is an empty string "". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.Write a program that finds the minimum number of moves to make two given strings $$$s$$$ and $$$t$$$ equal.

The first line of the input contains $$$s$$$. In the second line of the input contains $$$t$$$. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and $$$2\cdot10^5$$$, inclusive.

Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.

NoteIn the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".In the second example, the move should be applied to the string "codeforces" $$$8$$$ times. As a result, the string becomes "codeforces" $$$\to$$$ "es". The move should be applied to the string "yes" once. The result is the same string "yes" $$$\to$$$ "es".In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.In the fourth example, the first character of the second string should be deleted.

object StrCut {
  def main(args: Array[String]): Unit = {
    val s1: String = scala.io.StdIn.readLine()
    val s2: String = scala.io.StdIn.readLine()
    var u = 0
    while ( {
      u < Math.min(s1.length, s2.length) && s1.charAt(s1.length - u - 1) == s2.charAt(s2.length - u - 1)
    }) {
      u += 1; u
    }
    println(s1.length - u + s2.length - u)
  }
}

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 S, T = ns()

    val N = min(S.length, T.length)
    var i = 0
    var continue = true
    while(i < N && continue) {
      if (S(S.length - 1 - i) == T(T.length - 1 - i))
        i += 1
      else
        continue = false
    }
    out.println(S.length + T.length - 2 * i)
  }

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

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

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

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

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

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

object CF496B extends App {

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

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

  def solve = {
    val w1 = in.next
    val w2 = in.next

    val sameCount = w1.reverse.zipWithIndex
      .takeWhile(x => w2.length - 1 - x._2 >= 0 && w2.charAt(w2.length - 1 - x._2) == x._1)
      .length

    out.println(w1.length + w2.length - sameCount*2)
  }

  solve
  out.flush
  out.close
}

import scala.collection.mutable._

object Solution {
  def main(args: Array[String]) {
    val s = scala.io.StdIn.readLine.trim
    val t = scala.io.StdIn.readLine.trim
    println(solve(s, t))
  }

  def solve(s: String, t: String): Int = {
    var i = s.length
    var j = t.length
    var flag = true
    while (i > 0 && j > 0 && flag) {
      if (s(i-1) != t(j-1)) flag = false
      else {
        i -= 1
        j -= 1
      }
    }
    (i + j)
  }

}

import scala.io.StdIn

object Codeforces1005B {

  def getFewestMove(s: String, t: String): Int = {
    var totalMatched = 0
    var misMatched = false
    while (!misMatched) {
      if (totalMatched >= s.length || totalMatched >= t.length) {
        misMatched = true
      } else if (s(s.length - 1 - totalMatched) == t(t.length - 1 - totalMatched)) {
        totalMatched += 1
      } else {
        misMatched = true
      }
    }

    s.length + t.length - 2 * totalMatched
  }

  def main(args: Array[String]): Unit = {
    val s = StdIn.readLine()
    val t = StdIn.readLine()
    val fewestMove = getFewestMove(s, t)
    println(fewestMove)
  }
}

import scala.collection.mutable._

object Solution {
  def main(args: Array[String]) {
    val s = scala.io.StdIn.readLine.trim
    val t = scala.io.StdIn.readLine.trim
    println(solve(s, t))
  }

  def solve(s: String, t: String) {
    var i = s.length
    var j = t.length
    var flag = true
    while (i > 0 && j > 0 && flag) {
      if (s(i-1) != t(j-1)) flag = false
      else {
        i -= 1
        j -= 1
      }
    }
    (i + j)
  }

}

import scala.collection.mutable._

object Solution {
  def main(args: Array[String]) {
    val s = scala.io.StdIn.readLine.trim
    val t = scala.io.StdIn.readLine.trim
    println(solve(s, t))
  }

  def solve(s: String, t: String): Int = {
    var i = s.length - 1
    var j = t.length - 1
    var flag = true
    while (i > 0 && j > 0 && flag) {
      if (s(i) != t(j)) flag = false
      else {
        i -= 1
        j -= 1
      }
    }
    (i + j + 2)
  }

}


There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.

First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).

Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.

NoteIllustration for the first example: Illustration for the second 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)

  def solve(): Unit = {
    val N = ni()
    val A = Array.ofDim[Int](N)
    rep(N) { i =>
      A(i) = ni() + ni()
    }
    val ans = A.max
    out.println(ans)
  }

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

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

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

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

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

import scala.io.StdIn

object CoverPoints {
  def main(args: Array[String]): Unit ={
    val n = StdIn.readInt()
    var ans = 0
    for( i <- 1 to n){
      val xy = StdIn.readLine().split(" ").map(_.toInt)
      val x = xy(0)
      val y = xy(1)
      ans  = math.max(ans,x + y)
    }
    print(ans)
  }

}

object b1047 {
  def main(args: Array[String]): Unit = {
    println(scala.io.Source.stdin getLines() drop 1  map(_.split(" ").map(_.toInt).sum)  reduce scala.math.max)
  }
}

object CF511B extends App {

  import scala.io.StdIn

  val n = StdIn.readInt
  val points = new Array[Int](n).map(_ => StdIn.readLine.split(' ').map(_.toInt))
  println(points.map(point => point(0)+point(1)).max)
  // y-y1=-(x-x1)
  // y=-(x-x1)+y1 | evaluated at x=0
  // y=x1+y1
}

import scala.io.StdIn

object Codeforces1047B {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val result = (1 to n).map(_ => StdIn.readLine.trim.split(" ").map(_.toInt)).map(a => a.sum).max

    print(result)
  }
}

import scala.io.StdIn

object Codeforces1047B {

  def getCoverPoint(n: Int, points: Seq[Point]): Int =
    points.map(a => a.x + a.y).max

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

    val points = (1 to n).map(_ => StdIn.readLine.trim.split(" ").map(_.toInt)).map(a => Point(a(0), a(1)))

    val result = getCoverPoint(n, points)

    print(result)
  }

  case class Point(x: Int, y: Int)

}

object b1047 {
  def main(args: Array[String]): Unit = {
    //val n = scala.io.StdIn.readInt()
    val r : Array[Array[Int]] = scala.io.Source.stdin getLines() drop 1  map(_.split(" ").map(_.toInt)) toArray
    val s = r.sortBy {i => (-i(0),-i(1))}
    println(s.head(0)+s.head(1))
  }
}


There is a forest that we model as a plane and live $$$n$$$ rare animals. Animal number $$$i$$$ has its lair in the point $$$(x_{i}, y_{i})$$$. In order to protect them, a decision to build a nature reserve has been made.The reserve must have a form of a circle containing all lairs. There is also a straight river flowing through the forest. All animals drink from this river, therefore it must have at least one common point with the reserve. On the other hand, ships constantly sail along the river, so the reserve must not have more than one common point with the river.For convenience, scientists have made a transformation of coordinates so that the river is defined by $$$y = 0$$$. Check whether it is possible to build a reserve, and if possible, find the minimum possible radius of such a reserve.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of animals.  Each of the next $$$n$$$ lines contains two integers $$$x_{i}$$$, $$$y_{i}$$$ ($$$-10^7 \le x_{i}, y_{i} \le 10^7$$$) — the coordinates of the $$$i$$$-th animal's lair. It is guaranteed that $$$y_{i} \neq 0$$$. No two lairs coincide.

If the reserve cannot be built, print $$$-1$$$. Otherwise print the minimum radius. Your answer will be accepted if absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteIn the first sample it is optimal to build the reserve with the radius equal to $$$0.5$$$ and the center in $$$(0,\ 0.5)$$$.In the second sample it is impossible to build a reserve.In the third sample it is optimal to build the reserve with the radius equal to $$$\frac{5}{8}$$$ and the center in $$$(\frac{1}{2},\ \frac{5}{8})$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val X, Y = Array.ofDim[Int](N)
    rep(N) { i =>
      X(i) = ni()
      Y(i) = ni()
    }

    val EPS = 1e-9
    def lt(x: Double, y: Double) = x < y - EPS
    def le(x: Double, y: Double) = x < y + EPS
    def gt(x: Double, y: Double) = x > y - EPS
    def ge(x: Double, y: Double) = x > y + EPS
    def eq(x: Double, y: Double) = abs(x - y) < EPS

    def binSearch(l: Double, h: Double)(f: Double => Boolean): Double = {
      // ltをここでつかうとEPSがらみでおかしいことになって終了しない
      if (h - l < EPS * max(1, min(abs(l), abs(h)))) h
      else {
        val mid = (h + l) / 2.0
        if (f(mid)) binSearch(l, mid)(f)
        else binSearch(mid, h)(f)
      }
    }

    if (Y.exists(_ > 0) && Y.exists(_ < 0)) {
      out.println(-1)
    } else {
      rep(N) { i =>
        Y(i) = abs(Y(i))
      }

      val ans = binSearch(0.0, 1e16) { y =>
        var ms = -1e16
        var mx = 1e16
        0 until N forall { i =>
          if (lt(2 * y, Y(i))) false
          else {
            val h = abs(Y(i) - y)
            val w = Math.sqrt(y + h) * Math.sqrt(y - h)
            ms = max(ms, X(i) - w)
            mx = min(mx, X(i) + w)
            lt(ms, mx)
          }
        }
      }
      out.println(f"$ans%.6f")
    }
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val X, Y = Array.ofDim[Int](N)
    rep(N) { i =>
      X(i) = ni()
      Y(i) = ni()
    }

    if (Y.exists(_ > 0) && Y.exists(_ < 0)) {
      out.println(-1)
    } else {
      rep(N) { i =>
        Y(i) = abs(Y(i))
      }

      val E = 0.0000000001

      def test(y: Double): Boolean = {
        var ms = -1e7
        var mx = 1e7
        0 until N forall { i =>
          val h = abs(Y(i) - y)
          if (abs(h) < E) true
          else if (h > y - E) false
          else {
            val t = Math.asin(h / y)
            val w = Math.cos(t) * y
            ms = max(ms, X(i) - w)
            mx = min(mx, X(i) + w)
            ms < mx + E
          }
        }
      }

      var l = 0.0
      var h = 2e7

      rep(100) { _ =>
        val mid = (h + l) / 2
        if (test(mid)) h = mid
        else l = mid
      }

      out.println(f"$l%.6f")
    }
  }

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

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

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

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

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


There are $$$n$$$ segments drawn on a plane; the $$$i$$$-th segment connects two points ($$$x_{i, 1}$$$, $$$y_{i, 1}$$$) and ($$$x_{i, 2}$$$, $$$y_{i, 2}$$$). Each segment is non-degenerate, and is either horizontal or vertical — formally, for every $$$i \in [1, n]$$$ either $$$x_{i, 1} = x_{i, 2}$$$ or $$$y_{i, 1} = y_{i, 2}$$$ (but only one of these conditions holds). Only segments of different types may intersect: no pair of horizontal segments shares any common points, and no pair of vertical segments shares any common points.We say that four segments having indices $$$h_1$$$, $$$h_2$$$, $$$v_1$$$ and $$$v_2$$$ such that $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ form a rectangle if the following conditions hold:  segments $$$h_1$$$ and $$$h_2$$$ are horizontal;  segments $$$v_1$$$ and $$$v_2$$$ are vertical;  segment $$$h_1$$$ intersects with segment $$$v_1$$$;  segment $$$h_2$$$ intersects with segment $$$v_1$$$;  segment $$$h_1$$$ intersects with segment $$$v_2$$$;  segment $$$h_2$$$ intersects with segment $$$v_2$$$. Please calculate the number of ways to choose four segments so they form a rectangle. Note that the conditions $$$h_1 < h_2$$$ and $$$v_1 < v_2$$$ should hold.

The first line contains one integer $$$n$$$ ($$$1 \le n \le 5000$$$) — the number of segments. Then $$$n$$$ lines follow. The $$$i$$$-th line contains four integers $$$x_{i, 1}$$$, $$$y_{i, 1}$$$, $$$x_{i, 2}$$$ and $$$y_{i, 2}$$$ denoting the endpoints of the $$$i$$$-th segment. All coordinates of the endpoints are in the range $$$[-5000, 5000]$$$. It is guaranteed that each segment is non-degenerate and is either horizontal or vertical. Furthermore, if two segments share a common point, one of these segments is horizontal, and another one is vertical.

Print one integer — the number of ways to choose four segments so they form a rectangle.

NoteThe following pictures represent sample cases:

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
  case class Seg(v: Int, from: Int, to: Int)
  case class Event(y: Int, tpe: Int, seg: Seg)

class BIT(n: Int, zero: Int)(f: (Int, Int) => Int) {
  def this(n: Int) = this(n, 0)(_ + _)

  private val N = {
    val a = Integer.highestOneBit(n)
    if (a == n) a else a << 1
  }
  private val bit = if (zero != 0) Array.fill[Int](N + 1)(zero) else Array.ofDim[Int](N + 1)

  /**
    * 1 index
    * addとindex違うよ
    * cumsumなんかといっしょ
    */
  def sum(i: Int): Int = {
    assert(i <= n)
    var x = i
    var s: Int = zero
    while(x > 0) {
      s = f(s, bit(x))
      x -= x & -x
    }
    s
  }

  /**
    * 0 index
    */
  def add(i: Int, a: Int): Unit = {
    assert(i < n)
    var x = i + 1
    while(x <= N) {
      bit(x) = f(bit(x), a)
      x += x & -x
    }
  }

  def sumAll: Int = sum(n)

  // A がLongとかじゃない場合はこれらを実装しないと下の奴らが使えない
  private def sub(a: Int, b: Int) = a - b
  private def lt(a: Int, b: Int) = a < b

  /**
    * [l, r)
    */
  def query(l: Int, r: Int): Int = {
    assert(r > l)
    sub(sum(r), sum(l))
  }

  def lowerBound(W: Int): Int = {
    var k = N
    var x = 0
    var w = W
    while(k > 0) {
      if (x + k <= N && lt(bit(x + k), w)) {
        w = sub(w, bit(x + k))
        x += k
      }
      k /= 2
    }
    math.min(n, x)
  }
}
}

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

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

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

  def solve(): Unit = {
    val n = ni()
    val E_buf = ArrayBuffer[Event]()
    var zipX_buf = ArrayBuffer[Int]()
    REP(n) { _ =>
      val x1, y1, x2, y2 = ni()
      if (x1 == x2) {
        val v = Seg(x1, min(y1, y2), max(y1, y2))
        E_buf += Event(min(y1, y2), 1, v)
        E_buf += Event(max(y1, y2), 3, v)
      } else {
        val h = Seg(y1, min(x1, x2), max(x1, x2))
        E_buf += Event(y1, 2, h)
      }
      zipX_buf += x1
      zipX_buf += x2
    }

    // nが少ないからこれでok
    val E = E_buf.sortBy(e => (e.y, e.tpe)).toArray

    val MAX = isDebug(20, 10000)
    val OFF = isDebug(10, 5000)

    val zipX = zipX_buf.distinct.sorted.toArray
    val zipX_rev = Array.fill[Int](MAX + 1)(-1)
    REP(zipX.length) { i =>
      zipX_rev(zipX(i) + OFF) = i
    }

    debug(zipX)
    debug(zipX_rev)

    val vlines, flg = Array.ofDim[Boolean](zipX.length)
    var ans = 0L
    REP(E.length) { i =>
      if (E(i).tpe == 2) {
        val s = E(i).y
        val bit = new BIT(vlines.length)
        var id = 0
        while(id < vlines.length) {
          if (vlines(id) && E(i).seg.from <= zipX(id) && zipX(id) <= E(i).seg.to) {
            flg(id) = true
          } else {
            flg(id) = false
          }
          id += 1
        }
        REP(vlines.length) { id =>
          if (flg(id)) bit.add(id, 1)
        }
        var j = i + 1
        while(j < E.length) {
          if (E(j).tpe == 3) {
            val x = E(j).seg.v
            val xid = zipX_rev(x+OFF)
            if (flg(xid)) {
              bit.add(xid, -1)
              flg(xid) = false
            }
          } else if(E(j).tpe == 2) {
            val x1 = E(j).seg.from
            val x2 = E(j).seg.to
            val cnt = bit.query(zipX_rev(x1+OFF), zipX_rev(x2+OFF) + 1)
            debug(s"$s ${E(j).y} $x1 $x2 $cnt")
            ans += max(0, cnt * (cnt - 1) / 2)
          }
          j += 1
        }

      } else if (E(i).tpe == 1) {
        val x = E(i).seg.v
        vlines(zipX_rev(x+OFF)) = true
      } else {
        val x = E(i).seg.v
        vlines(zipX_rev(x+OFF)) = false
      }
    }

    out.println(ans)
  }
}


You are given a set of all integers from $$$l$$$ to $$$r$$$ inclusive, $$$l < r$$$, $$$(r - l + 1) \le 3 \cdot 10^5$$$ and $$$(r - l)$$$ is always odd.You want to split these numbers into exactly $$$\frac{r - l + 1}{2}$$$ pairs in such a way that for each pair $$$(i, j)$$$ the greatest common divisor of $$$i$$$ and $$$j$$$ is equal to $$$1$$$. Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.

If any solution exists, print "YES" in the first line. Each of the next $$$\frac{r - l + 1}{2}$$$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $$$1$$$. All $$$(r - l + 1)$$$ numbers should be pairwise distinct and should have values from $$$l$$$ to $$$r$$$ inclusive. If there are multiple solutions, print any of them. If there exists no solution, print "NO".

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 L, R = nl()
    val N = (R - L + 1).toInt
    out.println("YES")
    rep(N / 2) { k =>
      val i = L + 2 * k
      val j = i + 1
      out.println(s"$i $j")
    }
  }

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

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

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

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

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


Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets:   A ticket for one ride on some bus or trolley. It costs c1 burles;  A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles;  A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles;  A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.

The first line contains four integers c1, c2, c3, c4 (1 ≤ c1, c2, c3, c4 ≤ 1000) — the costs of the tickets. The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of buses and trolleys Vasya is going to use. The third line contains n integers ai (0 ≤ ai ≤ 1000) — the number of times Vasya is going to use the bus number i. The fourth line contains m integers bi (0 ≤ bi ≤ 1000) — the number of times Vasya is going to use the trolley number i.

Print a single number — the minimum sum of burles Vasya will have to spend on the tickets.

NoteIn the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2·1) + 3 + 7 = 12 burles.In the second sample the profitable strategy is to buy one ticket of the fourth type.In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(c1, c2, c3, c4) = in.next().split(' ').map(_.toInt)
  in.next()
  val a = in.next().split(' ').map(_.toInt).sorted.reverse
  val b = in.next().split(' ').map(_.toInt).sorted.reverse
  println(Math.min(
    c4,
    Math.min(a.map(i => Math.min(i * c1, c2)).sum, c3) + Math.min(b.map(i => Math.min(i * c1, c2)).sum, c3)
  ))
}

object Main {
  def main(args: Array[String]) {
    val Array(c1, c2, c3, c4) = readLine().split(" ").map(_.toInt)
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val ns = readLine().split(" ").map(_.toInt)
    val ms = readLine().split(" ").map(_.toInt)

    val nsum = ns.map(count => c2.min(count * c1)).sum
    val nmin = nsum.min(c3)

    val msum = ms.map(count => c2.min(count * c1)).sum
    val mmin = msum.min(c3)

    println(c4.min(nmin + mmin))
  }
}


Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).

The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.

Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).

NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.

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 S = ns()
    val N = S.length
    val C = Array.ofDim[Int](26)
    REP(N) { i =>
      C(S(i) - 'a') += 1
    }

    /**
      * s文字目から始めて足りない分はスライドしてN文字列作った場合、回文になっているか
      */
    def testPali(s: Int): Boolean = {
      var ok = true
      REP(N / 2) { i =>
        ok &&= S((s + i) % N) == S((s + N - 1 - i) % N)
      }
      ok
    }

    def testNotSame(s: Int): Boolean = {
      var ok = false
      REP(N) { i =>
        ok ||= S((s + i) % N) != S(i)
      }
      ok
    }

    val mxUsed = C.max
    if (mxUsed == N || mxUsed == N - 1) {
      out.println("Impossible")
    } else {
      var ans = 2
      REP(N - 1, 1) { i =>
        if (testPali(i) && testNotSame(i)) {
//          debug(s"find cut1 $i")
          ans = min(ans, 1)
        }
      }
      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
  }
}

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 S = ns()
    val N = S.length

    val memo = Array.fill[Int](N + 1)(-1)
    /**
      * 回文チェック
      * @param i 1-indexed
      */
    def test(i: Int): Boolean = {
//      debug(s"test($i)")
      if (memo(i) == -1) {
        var ok = true
        REP(i / 2) { j =>
          val oppo = i - 1 - j
          ok &&= S(oppo) == S(j)
        }
        memo(i) = if (ok) 1 else 0
      }
      memo(i) == 1
    }

    /**
      * 偶の回文をを半分に分割していって、最後に回文じゃないものになるかどうか
      * 12211221 => 1221 => 12 => ok
      * 1232112321 => 12321 => no
      * @param i 1-indexed
      */
    def check(i: Int): Boolean = {
      i % 2 == 0 && {
        !test(i / 2) || check(i / 2)
      }
    }

    val INF = 100
    var ans = INF

    // 左から真ん中までで回文がなければ逆側と入れ替えて別の名前にできる
    REP(N / 2, 1) { i =>
      if (!test(i)) {
        // ちょうど真ん中の場合は分割は１回でいい
        if (N % 2 == 0 && i == N / 2) {
//          debug(s"HOGE $i")
          ans = min(1, ans)
        }
        else ans = min(2, ans)
      }
      else {
        // 回文だった場合は、偶の場合なら左半分を一番右にもっていくことで回文をつくれる
        // ただしこれも回文だった場合、もとの文字といっしょになるので、さらに同じ操作を繰り返して回文でないものがないか探す
        if (check(i)) {
//          debug(s"FUGA $i")
          ans = min(1, ans)
        }
      }
    }

//    debug(memo)

    if (ans == INF) out.println("Impossible")
    else 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
  }
}

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 S = ns()
    val N = S.length
    val C = Array.ofDim[Int](26)
    REP(N) { i =>
      C(S(i) - 'a') += 1
    }

    /**
      * s文字目から始めて足りない分はスライドしてN文字列作った場合、回文になっているか
      */
    def testPali(s: Int): Boolean = {
      var ok = true
      REP(N / 2) { i =>
        ok &&= S((s + i) % N) == S((s + N - 1 - i) % N)
      }
      ok
    }

    val mxUsed = C.max
    if (mxUsed == N || mxUsed == N - 1) {
      out.println("Impossible")
    } else {
      var ans = 2
      REP(N - 1, 1) { i =>
        if (testPali(i)) ans = min(ans, 1)
      }
      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
  }
}


You are given a tree consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is equal to $$$a_i$$$.Let's denote the function $$$g(x, y)$$$ as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex $$$x$$$ to vertex $$$y$$$ (including these two vertices). Also let's denote $$$dist(x, y)$$$ as the number of vertices on the simple path between vertices $$$x$$$ and $$$y$$$, including the endpoints. $$$dist(x, x) = 1$$$ for every vertex $$$x$$$.Your task is calculate the maximum value of $$$dist(x, y)$$$ among such pairs of vertices that $$$g(x, y) > 1$$$.

The first line contains one integer $$$n$$$ — the number of vertices $$$(1 \le n \le 2 \cdot 10^5)$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ $$$(1 \le a_i \le 2 \cdot 10^5)$$$ — the numbers written on vertices. Then $$$n - 1$$$ lines follow, each containing two integers $$$x$$$ and $$$y$$$ $$$(1 \le x, y \le n, x \ne y)$$$ denoting an edge connecting vertex $$$x$$$ with vertex $$$y$$$. It is guaranteed that these edges form a tree.

If there is no pair of vertices $$$x, y$$$ such that $$$g(x, y) > 1$$$, print $$$0$$$. Otherwise print the maximum value of $$$dist(x, y)$$$ among such pairs.

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)

  val P = Array(
    2,  3,  5,  7, 11, 13, 17, 19, 23, 29,
    31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
    73, 79, 83, 89, 97,101,103,107,109,113,
    127,131,137,139,149,151,157,163,167,173,
    179,181,191,193,197,199,211,223,227,229,
    233,239,241,251,257,263,269,271,277,281,
    283,293,307,311,313,317,331,337,347,349,
    353,359,367,373,379,383,389,397,401,409,
    419,421,431,433,439,443,449
  )

  val NN = 2e5.toInt
  val prime = Array.ofDim[Int](2e4.toInt)
  val factor = Array.ofDim[Int](NN + 1)
  var pp = 0

  2 to NN foreach { i =>
    if (factor(i) == 0) {
      factor(i) = i
      prime(pp) = i
      pp += 1
    }

    def fill(p: Int): Unit = {
      if (p < pp && prime(p) * i <= NN) {
        factor(prime(p) * i) = prime(p)
        if (prime(p) != i)
          fill(p + 1)
      }
    }

    fill(0)
  }

  def factorize(x: Int)(fn: Int => Unit): Unit = {
    if (x > 1) {
      val f = factor(x)
      fn(f)
      factorize(x / f)(fn)
    }
  }

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val (from, to) = na2(N - 1, -1)
    val g = packUGraph(N, from, to)
    val (_, parent, queue) = traceBfs(g)

    val flg = Array.ofDim[Boolean](N)
    val dp = Array.ofDim[Int](N)

    var ans = 0

    // √Nまで
    REP(P.length) { i =>
      val p = P(i)
      REP(N) { j =>
        flg(j) = A(j) % p == 0
      }

      REP_r(N) { j =>
        val v = queue(j)
        if (!flg(v)) {
          dp(v) = 0
        } else {
          var c1, c2 = 0
          REP(g(v).length) { k =>
            val u = g(v)(k)
            if (u != parent(v)) {
              c2 = max(c2, dp(u))
              if (c2 > c1) {
                val tmp = c1
                c1 = c2
                c2 = tmp
              }
            }
          }
          dp(v) = c1 + 1
          ans = max(ans, c1 + c2 + 1)
        }
      }
    }

    def findBigPrime(x: Int): Int = {
      factorize(x) { p =>
        if (p.toLong * p > NN) return p
      }
      0
    }

    // √N以降はノードを各々１回だけ割り当てると考えることができる

    // √N以降の素数が因数ならその値が入っている
    val B = Array.ofDim[Int](N)
    REP(N) { i =>
      B(i) = findBigPrime(A(i))
    }

    REP_r(N) { i =>
      val v = queue(i)
      if (B(v) == 0) {
        dp(v) = 0
      } else {
        var c1, c2 = 0
        REP(g(v).length) { k =>
          val u = g(v)(k)
          if (u != parent(v) && B(u) == B(v)) { // 素数が一緒のものだけ
            c2 = max(c2, dp(u))
            if (c2 > c1) {
              val tmp = c1
              c1 = c2
              c2 = tmp
            }
          }
        }
        dp(v) = c1 + 1
        ans = max(ans, c1 + c2 + 1)
      }
    }

    out.println(ans)
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

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

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

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

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

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

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

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

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

  val P = Array(
  2,  3,  5,  7, 11, 13, 17, 19, 23, 29,
  31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
  73, 79, 83, 89, 97,101,103,107,109,113,
  127,131,137,139,149,151,157,163,167,173,
  179,181,191,193,197,199,211,223,227,229,
  233,239,241,251,257,263,269,271,277,281,
  283,293,307,311,313,317,331,337,347,349,
  353,359,367,373,379,383,389,397,401,409,
  419,421,431,433,439,443,449
  )

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val (from, to) = na2(N - 1, -1)
    val g = packUGraph(N, from, to)
    val (_, parent, queue) = traceBfs(g)

    val flg = Array.ofDim[Boolean](N)
    val dp = Array.ofDim[Int](N)

    var ans = 0
    REP(P.length) { i =>
      val p = P(i)
      REP(N) { j =>
        flg(j) = A(j) % p == 0
      }

      REP_r(N) { j =>
        val v = queue(j)
        if (!flg(v)) {
          dp(v) = 0
        } else {
          var mxChild = 0
          REP(g(v).length) { k =>
            val u = g(v)(k)
            if (u != parent(v)) mxChild = max(mxChild, dp(u))
          }
          dp(v) = mxChild + 1
        }
        ans = max(ans, dp(v))
      }
    }

    out.println(ans)
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

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

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


Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of mannequins. Next n lines contain two space-separated integers each: xi, yi (|xi|, |yi| ≤ 1000) — the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.

Print a single real number — the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10 - 6.

NoteSolution for the first sample test is shown below:   Solution for the second sample test is shown below:   Solution for the third sample test is shown below:   Solution for the fourth sample test is shown below:

import scala.util.Sorting._
import math._

object Contest extends App {
  val n = readInt()
  val arcs = new Array[Double](n+1);
  arcs(n) = 3 * Pi
  for (i <- 0 until n){
    val Array(x, y) = readLine().split(" ").map(_.toDouble)
    arcs(i) = atan2(y, x)
  }
  stableSort(arcs, (a: Double, b: Double) => {a < b})
  arcs(n) = arcs(0) + 2 * Pi
  var maxArc = 0.0
  for (i <- 0 until n){
    maxArc = max(maxArc, arcs(i+1) - arcs(i))
  }
  println(360 - maxArc * 180 / Pi)
}

object C{
  def main(args:Array[String]){

    val a:Array[Double]={
      val n=readLine.toInt
      val alist=
        (1 to n).toList.foldLeft(List[Double]()){(list,i)=>
          val (x, y)={
            val sp=readLine.split(" ").map(_.toInt)
            (sp(0),sp(1))
          }
          if(x==0 && y==0){
            list
          }else{
            val next=Math.toDegrees(Math.atan2(y,x))
            next::list
          }
        }

      alist.toArray.sorted
    }

    val n=a.length

    val max= (0 until n).toList.foldLeft(0.0){(max,i)=>
      var m= a((i+1)%n) -a(i)
      if(i==n-1) m+=360
      Math.max(m,max)
    }

    println(360-max)
  }
}

object C{
  def main(args:Array[String]){

    val a:Array[Double]={
      val n=readLine.toInt
      val alist=
        (1 to n).toList.foldLeft(List[Double]()){(list,i)=>
          val (x, y)={
            val sp=readLine.split(" ").map(_.toInt)
            (sp(0),sp(1))
          }
          if(x==0 && y==0){
            list
          }else{
            val next=Math.toDegrees(Math.atan2(y,x))
            next::list
          }
        }

      alist.toArray.sorted
    }

    val n=a.length

    val max= (0 until n).toList.foldLeft(0.0){(max,i)=>
      var m= a((i+1)%n) -a(i)
      if(m<0) m+=360
      Math.max(m,max)
    }

    if(n==1){
      println(0)
    }else{
      println(360-max)
    }
  }
}

object C{
  def main(args:Array[String]){

    val a:Array[Double]={
      val n=readLine.toInt
      val alist=
        (1 to n).toList.foldLeft(List[Double]()){(list,i)=>
          val (x, y)={
            val sp=readLine.split(" ").map(_.toInt)
            (sp(0),sp(1))
          }
          if(x==0 && y==0){
            list
          }else{
            val next=Math.toDegrees(Math.atan2(y,x))
            next::list
          }
        }

      alist.toArray.sorted
    }

    val n=a.length

    val max= (0 until n).toList.foldLeft(0.0){(max,i)=>
      var m= a((i+1)%n) -a(i)
      if(m<0) m+=360
      Math.max(m,max)
    }

    println(360-max)

  }
}


As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.

The first line contains two space-separated positive integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000) — the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 104) — the towers' initial heights.

In the first line print two space-separated non-negative integers s and m (m ≤ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i ≠ j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them.

NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6.

import scala.collection.mutable.ListBuffer

object P479B {
	def iterate(k: Int, values: Vector[Int]) : (ListBuffer[(Int, Int)], Vector[Int]) = {
		val results = ListBuffer[(Int, Int)]()
		val max = values.zipWithIndex.maxBy(_._1)
		val min = values.zipWithIndex.minBy(_._1)
		if (max._1 > min._1 + 1 && k > 0) {
			val updated = values.updated(max._2, max._1 - 1).updated(min._2, min._1 + 1)
			val (rresults, rupdated) = iterate(k - 1, updated)
			(results ++= ((max._2 + 1, min._2 + 1) +=: rresults), rupdated)
		} else {
			(results, values)
		}
	}

	def main(args: Array[String]) {
		val read = () => scala.io.StdIn.readLine.split(" ").map(_.toInt)
		val Array(n, k) = read()
		val (results, values) = iterate(k, read().to[Vector])
		printf("%d %d\n", values.max - values.min, results.length)
		results.foreach(x => printf("%d %d\n", x._1, x._2))
	}
}

import scala.collection.mutable.ListBuffer

object P479B {
	def transfer(values: Vector[Int], src: (Int, Int), dst: (Int, Int)) : Vector[Int] = {
		values.updated(src._2, src._1 - 1).updated(dst._2, dst._1 + 1)
	}

	def iterate(k: Int, values: Vector[Int]) : (ListBuffer[(Int, Int)], Vector[Int]) = {
		val max = values.zipWithIndex.maxBy(_._1)
		val min = values.zipWithIndex.minBy(_._1)

		val accumulator = ListBuffer[(Int, Int)]()
		if (max._1 - min._1 > 1 && k > 0) {
			val (results, updated) = iterate(k - 1, transfer(values, max, min))
			(accumulator ++= ((max._2 + 1, min._2 + 1) +=: results), updated)
		} else {
			(accumulator, values)
		}
	}

	def main(args: Array[String]) {
		val read = () => scala.io.StdIn.readLine.split(" ").map(_.toInt)
		val (Array(n, k), a) = (read(), read().to[Vector])
		val (results, values) = iterate(k, a)

		printf("%d %d\n", values.max - values.min, results.length)
		results.foreach(x => printf("%d %d\n", x._1, x._2))
	}
}

import Console._
import scala.io.Source

object Main extends App {

  val in = Source.fromInputStream(System.in)
  val n = nextInt(in).get
  val k = nextInt(in).get
  val arr = Array.ofDim[Int](n)

  for (i <- 1 to n) {
    arr(i - 1) = nextInt(in).get
  }
  val sumAll = arr.foldLeft(0)(_ + _)
  val minInstability = (sumAll / n.toDouble).ceil.toInt - sumAll / n
  val arrIndexed = arr.zipWithIndex
  val initialInstability = arrIndexed(findMaxIdx(arrIndexed))._1 - arrIndexed(findMinIdx(arrIndexed))._1

  val (instability, opCount, allOps) =
    findMinInstability(initialInstability, 0, Array[(Int, Int)](), arrIndexed)

  print(s"$instability $opCount")

  for (i <- 1 to opCount) {
    val op = allOps(i - 1)
    print(s"\n${op._1} ${op._2}")
  }

  def findMinInstability(instability: Int, nOps: Int, ops: Array[(Int, Int)], arrIndexed: Array[(Int, Int)]):
        (Int, Int, Array[(Int, Int)]) = {

    if (instability == minInstability || nOps == k) {
      (instability, nOps, ops)
    } else {
      val maxIdx = findMaxIdx(arrIndexed)
      val minIdx = findMinIdx(arrIndexed)
      arrIndexed(maxIdx) = (arrIndexed(maxIdx)._1 - 1, arrIndexed(maxIdx)._2)
      arrIndexed(minIdx) = (arrIndexed(minIdx)._1 + 1, arrIndexed(minIdx)._2)
      val newInstability = arrIndexed(findMaxIdx(arrIndexed))._1 - arrIndexed(findMinIdx(arrIndexed))._1

      findMinInstability(newInstability, nOps + 1, ops :+ (maxIdx + 1, minIdx + 1), arrIndexed)
    }
  }

  def findMaxIdx(arrIndexed: Array[(Int, Int)]) = {
    arrIndexed.max._2
  }

  def findMinIdx(arrIndexed: Array[(Int, Int)]) = {
    arrIndexed.min._2
  }

  def nextInt(src: Iterator[Char]): Option[Int] = {
    val (ignored, tail) = src.span(!_.isDigit)
    val (nbr, _) = tail.span(_.isDigit)
    if (!nbr.isEmpty) {
        Some(nbr.mkString.toInt)
    } else {
      None
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val arr = Array.fill(10001){List.empty[Int]}
  data.indices.foreach { i => arr(data(i)) ::= i + 1 }
  var nk = k
  var left = arr.indices.find(i => arr(i).nonEmpty).get
  var right = arr.indices.reverse.find(i => arr(i).nonEmpty).get
  var res = List.empty[(Int, Int)]
  while (nk > 0 && left + 1 < right) {
    val lIndex = arr(left).head
    val rIndex = arr(right).head
    res ::= (rIndex, lIndex)
    nk -= 1
    arr(left) = arr(left).tail
    arr(left + 1) ::= lIndex
    arr(right) = arr(right).tail
    arr(right - 1) ::= rIndex
    if (arr(left).isEmpty)
      left += 1
    if (arr(right).isEmpty)
      right -= 1
  }
  println(s"${right - left} ${k - nk}")
  println(res.map{case(a, b) => s"$a $b"}.mkString("\n"))
}