All cinema halls in Berland are rectangles with K rows of K seats each, and K is an odd number. Rows and seats are numbered from 1 to K. For safety reasons people, who come to the box office to buy tickets, are not allowed to choose seats themselves. Formerly the choice was made by a cashier, but now this is the responsibility of a special seating program. It was found out that the large majority of Berland's inhabitants go to the cinema in order to watch a movie, that's why they want to sit as close to the hall center as possible. Moreover, a company of M people, who come to watch a movie, want necessarily to occupy M successive seats in one row. Let's formulate the algorithm, according to which the program chooses seats and sells tickets. As the request for M seats comes, the program should determine the row number x and the segment [yl, yr] of the seats numbers in this row, where yr - yl + 1 = M. From all such possible variants as a final result the program should choose the one with the minimum function value of total seats remoteness from the center. Say,  — the row and the seat numbers of the most "central" seat. Then the function value of seats remoteness from the hall center is . If the amount of minimum function values is more than one, the program should choose the one that is closer to the screen (i.e. the row number x is lower). If the variants are still multiple, it should choose the one with the minimum yl. If you did not get yet, your task is to simulate the work of this program.

The first line contains two integers N and K (1 ≤ N ≤ 1000, 1 ≤ K ≤ 99) — the amount of requests and the hall size respectively. The second line contains N space-separated integers Mi from the range [1, K] — requests to the program.

Output N lines. In the i-th line output «-1» (without quotes), if it is impossible to find Mi successive seats in one row, otherwise output three numbers x, yl, yr. Separate the numbers with a space.

//package me.jetblack.cf

import java.util.Scanner

object Cashier extends App {

  val s = new Scanner(System.in)

  val n = s.nextInt()
  val k = s.nextInt()
  val hall = Array.ofDim[Boolean](k + 1, k + 1)
  val trace = Array.fill[String](n)("-1")
  val q = (0 until n).map(_ => s.nextInt()).toArray
  val c = (k / 2) + 1
  var cur = 0

  while (cur < n) {
    var best = Integer.MAX_VALUE
    var bestCoord = (0, 0)
    var x = 1
    while (x < k + 1) {
      var y = 1
      while (y < k - q(cur) + 2) {
        var fits = true
        var cnt = y
        var score = 0
        while (fits && cnt < y + q(cur)) {
          if (hall(x)(cnt)) fits = false
          score += math.abs(x - c) + math.abs(cnt - c)
          cnt += 1
        }
        if (fits && score < best) {
          best = score
          bestCoord = (x, y)
        }
        y += 1
      }
      x += 1
    }
    if (best != Integer.MAX_VALUE) {
      trace(cur) = s"${bestCoord._1} ${bestCoord._2} ${bestCoord._2 + q(cur) - 1} "
      var cnt = bestCoord._2
      while (cnt < bestCoord._2 + q(cur)) {
        hall(bestCoord._1)(cnt) = true
        cnt += 1
      }
    }
    cur += 1
  }

  print(trace.mkString("\n"))

}

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

object B {

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

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

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val n = nextInt
    val k = nextInt
    val cinema = new Array[Array[Int]](k)
    val xc = Math.ceil(k / 2).toInt
    for (i <- 0 until k) {
      cinema(i) = new Array[Int](k)
    }
    for (i <- 0 until k) {
      for (j <- 0 until k) {
        cinema(i)(j) = func(xc, i, j)
      }
    }
    for (t <- 0 until n) {
      val m = nextInt
      var sum = Int.MaxValue
      var start = 0
      var row = 0
      for (i <- 0 until k) {
        var interSum = 0
        for (j <- 0 until m) {
          interSum += cinema(i)(j)
        }
        if (interSum < sum) {
          sum = interSum
          row = i
          start = 0
        }
        for (j <- m until k) {
          interSum += cinema(i)(j)
          interSum -= cinema(i)(j - m)
          if (interSum < sum) {
            sum = interSum
            row = i
            start = j - m + 1
          }
        }
      }
      if (sum < 100000) {
//        out.println(sum)
        out.println((row + 1) + " " + (start + 1) + " " + (start + m))
        for (j <- start until start + m) {
          cinema(row)(j) = 100000
        }
      } else {
        out.println(-1)
      }
//      for (i <- 0 until k) {
//        for (j <- 0 until k) {
//          out.print(cinema(i)(j) + " ")
//        }
//        out.println
//      }
    }
  }

  def func(xc: Int, x: Int, y: Int) = {
    Math.abs(x - xc) + Math.abs(y - xc)
  }

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

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

object B {

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

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

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

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def solve = {
    val n = nextInt
    val k = nextInt
    val cinema = new Array[Array[Int]](k)
    val xc = Math.ceil(k / 2).toInt
    for (i <- 0 until k) {
      cinema(i) = new Array[Int](k)
    }
    for (i <- 0 until k) {
      for (j <- 0 until k) {
        cinema(i)(j) = func(xc, i, j)
      }
    }
    for (t <- 0 until n) {
      val m = nextInt
      var sum = Int.MaxValue
      var start = 0
      var row = 0
      for (i <- 0 until k) {
        var interSum = 0
        for (j <- 0 until m) {
          interSum += cinema(i)(j)
        }
        if (interSum < sum) {
          sum = interSum
          row = i
          start = 0
        }
        for (j <- m until k) {
          if (interSum < sum) {
            sum = interSum
            row = i
            start = j - m
          }
          interSum += cinema(i)(j)
          interSum -= cinema(i)(j - m)
        }
      }
      if (sum < 100000) {
//        out.println(sum)
        out.println((row + 1) + " " + (start + 1) + " " + (start + m))
        for (j <- start until start + m) {
          cinema(row)(j) = 100000
        }
      } else {
        out.println(-1)
      }
//      for (i <- 0 until k) {
//        for (j <- 0 until k) {
//          out.print(cinema(i)(j) + " ")
//        }
//        out.println
//      }
    }
  }

  def func(xc: Int, x: Int, y: Int) = {
    Math.abs(x - xc) + Math.abs(y - xc)
  }

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


A sequence of non-negative integers $$$a_1, a_2, \dots, a_n$$$ is called growing if for all $$$i$$$ from $$$1$$$ to $$$n - 1$$$ all ones (of binary representation) in $$$a_i$$$ are in the places of ones (of binary representation) in $$$a_{i + 1}$$$ (in other words, $$$a_i \:\&\: a_{i + 1} = a_i$$$, where $$$\&$$$ denotes bitwise AND). If $$$n = 1$$$ then the sequence is considered growing as well.For example, the following four sequences are growing:   $$$[2, 3, 15, 175]$$$ — in binary it's $$$[10_2, 11_2, 1111_2, 10101111_2]$$$;  $$$[5]$$$ — in binary it's $$$[101_2]$$$;  $$$[1, 3, 7, 15]$$$ — in binary it's $$$[1_2, 11_2, 111_2, 1111_2]$$$;  $$$[0, 0, 0]$$$ — in binary it's $$$[0_2, 0_2, 0_2]$$$. The following three sequences are non-growing:   $$$[3, 4, 5]$$$ — in binary it's $$$[11_2, 100_2, 101_2]$$$;  $$$[5, 4, 3]$$$ — in binary it's $$$[101_2, 100_2, 011_2]$$$;  $$$[1, 2, 4, 8]$$$ — in binary it's $$$[0001_2, 0010_2, 0100_2, 1000_2]$$$. Consider two sequences of non-negative integers $$$x_1, x_2, \dots, x_n$$$ and $$$y_1, y_2, \dots, y_n$$$. Let's call this pair of sequences co-growing if the sequence $$$x_1 \oplus y_1, x_2 \oplus y_2, \dots, x_n \oplus y_n$$$ is growing where $$$\oplus$$$ denotes bitwise XOR.You are given a sequence of integers $$$x_1, x_2, \dots, x_n$$$. Find the lexicographically minimal sequence $$$y_1, y_2, \dots, y_n$$$ such that sequences $$$x_i$$$ and $$$y_i$$$ are co-growing.The sequence $$$a_1, a_2, \dots, a_n$$$ is lexicographically smaller than the sequence $$$b_1, b_2, \dots, b_n$$$ if there exists $$$1 \le k \le n$$$ such that $$$a_i = b_i$$$ for any $$$1 \le i < k$$$ but $$$a_k < b_k$$$.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — length of the sequence $$$x_i$$$. The second line contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i < 2^{30}$$$) — elements of the sequence $$$x_i$$$. It is guaranteed that the sum of $$$n$$$ overall all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$ ($$$0 \le y_i < 2^{30}$$$) — lexicographically minimal sequence such that such that it's co-growing with given sequence $$$x_i$$$.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val xn = readLine().split(" ").map(_.toInt)
    val yn = (1 until n).scanLeft(0) { case (yj, i) =>
      val xj = yj ^ xn(i - 1)
      xj - (xj & xn(i))
    }

    println(yn.mkString(" "))
  }
}


In Aramic language words can only represent objects.Words in Aramic have special properties:   A word is a root if it does not contain the same letter more than once.  A root and all its permutations represent the same object.  The root $$$x$$$ of a word $$$y$$$ is the word that contains all letters that appear in $$$y$$$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab".  Any word in Aramic represents the same object as its root. You have an ancient script in Aramic. What is the number of different objects mentioned in the script?

The first line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$) — the number of words in the script. The second line contains $$$n$$$ words $$$s_1, s_2, \ldots, s_n$$$ — the script itself. The length of each string does not exceed $$$10^3$$$. It is guaranteed that all characters of the strings are small latin letters.

Output one integer — the number of different objects mentioned in the given ancient Aramic script.

NoteIn the first test, there are two objects mentioned. The roots that represent them are "a","ab".In the second test, there is only one object, its root is "amer", the other strings are just permutations of "amer".

object CF975A extends App {
  import scala.io.Source
  //val src = Source.fromFile("data.txt")
  val src = Source.stdin
  val lines = src.getLines

  def readString(): String =  {
    val line = if (lines.hasNext) lines.next else null
    if (line == null) throw new RuntimeException("Premature end of source encountered")
    line
  }

  def readStrings(): Array[String] = readString().split(" ")

  readString()
  val nObj = readStrings().map(x => x.toSet).toSet.size
  println(nObj)
}

import scala.annotation.tailrec

object Prg1 extends App {

  @tailrec
  def wordsAramic(s: List[String], presentStr:List[String]=List[String](), count:Int = 0):Int = {
    if (s.length == 0) count
    else {
      val uniqueString = s.head.sorted.distinct
      if (presentStr.contains(uniqueString))
        wordsAramic(s.tail, presentStr, count)
      else wordsAramic(s.tail, presentStr :+ uniqueString, count + 1)
    }
  }

  val t = scala.io.StdIn.readLine.toInt
  val listOfStr = scala.io.StdIn.readLine.split(" ").toList
  println(wordsAramic(listOfStr))
}

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

  override def apply(io: IO): io.type = {
    val words = io.read[Set[String]]
    val ans = words.map(_.distinct.sorted).size
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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
      }
    }
  }
}


Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy and with a maximum possible speed. Compute the minimum time when Vasiliy will get in any of Beru-taxi cars.

The first line of the input contains two integers a and b ( - 100 ≤ a, b ≤ 100) — coordinates of Vasiliy's home. The second line contains a single integer n (1 ≤ n ≤ 1000) — the number of available Beru-taxi cars nearby.  The i-th of the following n lines contains three integers xi, yi and vi ( - 100 ≤ xi, yi ≤ 100, 1 ≤ vi ≤ 100) — the coordinates of the i-th car and its speed. It's allowed that several cars are located at the same point. Also, cars may be located at exactly the same point where Vasiliy lives.

Print a single real value — the minimum time Vasiliy needs to get in any of the Beru-taxi cars. You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, first taxi will get to Vasiliy in time 2, and second will do this in time 1, therefore 1 is the answer.In the second sample, cars 2 and 3 will arrive simultaneously.

import io.StdIn._
object Euclid extends App {

  val l1 = readLine().split(" ").map(_.toInt)
  val (a:Int, b:Int) = (l1(0), l1(1))

  val cars = readLine().toInt
  var i = 0
  var result:Option[Double] = None
  while(i<cars){
    val t = readLine().split(' ').map(_.toInt)
    val (x:Int,y:Int,v:Int) = (t(0),t(1),t(2))
    val s:Double = math.sqrt( math.pow(a-x, 2) + math.pow(b-y,2) )
//    println("s: is " + s)
    result = if (result.isEmpty || (s/v < result.get)) Some(s/v) else result
//    println("result: " + result)
    i +=1
  }
  println(result.get)
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val Array(a, b) = lines.next().split(' ').map(_.toInt)
  val n = lines.next().toInt
  val result = lines.take(n).map(_.split(' ').map(_.toInt)).map{case Array(a1, b1, v) => Math.sqrt((a1 - a) * (a1 - a) + (b1 - b) * (b1 - b)) / v}.min
  println(result)
}

import scala.io.StdIn._

object Main {
    def main(args: Array[String]): Unit = {
        var line = readLine().split(" ")
        val x = line(0).toDouble
        val y = line(1).toDouble

        val n = readInt()

        var minTime: Double = -1
        (1 to n).foreach(i => {
            line = readLine().split(" ")
            val ix = line(0).toDouble
            val iy = line(1).toDouble
            val iz = line(2).toDouble

            val time = Math.hypot(ix-x, iy-y) / iz
            if(minTime == -1){
                minTime = time
            }
            minTime = minTime.min(time)
        })

        println(f"$minTime%1.10f")
    }
}

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

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(a, b) = readInts(2)
    val Array(n) = readInts(1)
    println(Array.fill(n)(readInts(3)).map{ arr =>
      math.sqrt(math.pow(a-arr(0), 2) + math.pow(b-arr(1), 2)) / arr(2).toDouble
    }.min)
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _706A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write}
    val a, b = read[Int]
    var ans = Double.MaxValue
    repeat(read[Int]) {
      val x, y, v = read[Double]
      val dist = Math.hypot(a - x, b - y)
      ans = ans min (dist/v)
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeOnNextLine(obj: Any, more: Any*): this.type = {
    printer.println()
    write(obj, more: _*)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

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

object Main extends App {
  import scala.io._
  val input = Source.stdin
  val inputit:Iterator[String] = input.getLines()
  var lineit:Iterator[String] = List.empty.iterator
  def rs() : String = {
    if (lineit.hasNext) lineit.next
    else {
      lineit = inputit.next.split(" ").iterator
      rs()
    }
  }
  def ri(): Int = rs().toInt
  val a = ri ()
  val b = ri ()
  val n = ri ()
  println(
    (for (i <- 1 to n)
      yield {
       val x = ri ();
       val y = ri ();
       val v = ri ();
       math.sqrt ((x - a) * (x - a) + (y - b) * (y - b)) / v} )
  .toList.min)
}

import scala.io.StdIn._

object A extends App {
  val Array(a, b) = readLine().split(" ").map(_.toInt)
  val n = readInt()

  var time = Double.MaxValue
  1 to n foreach { _ =>
    val Array(x, y, v) = readLine().split(" ").map(_.toInt)
    val dist = Math.sqrt((x.toDouble - a) * (x - a) + (y.toDouble - b) * (y - b))
    val newTime = dist / v
    if (time > newTime) {
      time = newTime
    }
  }

  println(time)
}

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

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(a, b) = readInts(2)
    val Array(n) = readInts(1)
    println(Array.fill(n)(readInts(3)).map(arr => (math.abs(a- arr(0)) + math.abs(b-arr(1))).toDouble / arr(2).toDouble).min)
  }
}


You are given a set of $$$n$$$ segments on the axis $$$Ox$$$, each segment has integer endpoints between $$$1$$$ and $$$m$$$ inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — coordinates of the left and of the right endpoints. Consider all integer points between $$$1$$$ and $$$m$$$ inclusive. Your task is to print all such points that don't belong to any segment. The point $$$x$$$ belongs to the segment $$$[l; r]$$$ if and only if $$$l \le x \le r$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the number of segments and the upper bound for coordinates. The next $$$n$$$ lines contain two integers each $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le m$$$) — the endpoints of the $$$i$$$-th segment. Segments may intersect, overlap or even coincide with each other. Note, it is possible that $$$l_i=r_i$$$, i.e. a segment can degenerate to a point.

In the first line print one integer $$$k$$$ — the number of points that don't belong to any segment. In the second line print exactly $$$k$$$ integers in any order — the points that don't belong to any segment. All points you print should be distinct. If there are no such points at all, print a single integer $$$0$$$ in the first line and either leave the second line empty or do not print it at all.

NoteIn the first example the point $$$1$$$ belongs to the second segment, the point $$$2$$$ belongs to the first and the second segments and the point $$$5$$$ belongs to the third segment. The points $$$3$$$ and $$$4$$$ do not belong to any segment.In the second example all the points from $$$1$$$ to $$$7$$$ belong to the first segment.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, M = sc.nextInt()
    val used = Array.ofDim[Boolean](M)
    rep(N) { _ =>
      val l, r = sc.nextInt() - 1
      l to r foreach (j => used(j) = true)
    }

    val cnt = M - used.count(identity)
    out.println(cnt)
    out.println((used.zipWithIndex filterNot (_._1) map (_._2 + 1)).mkString(" "))
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

object CF501A 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 n = in.nextInt
    val m = in.nextInt

    var points = (1 to m).toList
    var segments = (0 until n).map(_ => (in.nextInt, in.nextInt)).toList

    for (segment <- segments) {
      points = points.filter(x => x < segment._1 || x > segment._2)
    }

    out.println(points.length)
    out.println(points.mkString(" "))
  }

  solve
  out.flush
  out.close
}

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

  override def apply(io: IO): io.type = {
    val n, m = io.read[Int]
    val intervals: Seq[(Int, Int)] = io.read(n)
    val ans = intervals.foldLeft(mutable.Set(1 to m : _*))({case (s, (i, j)) => s --= i to j})
    io.writeLine(ans.size).writeAll(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def 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
      }
    }
  }
}

import scala.collection.mutable
import scala.io.StdIn

object A {
  def main(args: Array[String]): Unit = {
    val List(n, m) = StdIn.readLine().split(" ").map(_.toInt).toList

    var s = new mutable.HashSet[Int]()
    for (i <- 1 to n) {
      val List(b, e) = StdIn.readLine().split(" ").map(_.toInt).toList
      for (j <- b to e) {
        s += j
      }
    }

    var res = new mutable.TreeSet[Int]()
    for (i <- 1 to m) {
      if (!(s contains i)) {
        res += i
      }
    }

    println(res.size)
    if (res.nonEmpty) {
      println(res.mkString(" "))
    }
  }
}


Lord Omkar would like to have a tree with $$$n$$$ nodes ($$$3 \le n \le 10^5$$$) and has asked his disciples to construct the tree. However, Lord Omkar has created $$$m$$$ ($$$\mathbf{1 \le m < n}$$$) restrictions to ensure that the tree will be as heavenly as possible. A tree with $$$n$$$ nodes is an connected undirected graph with $$$n$$$ nodes and $$$n-1$$$ edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.Here is an example of a tree:   A restriction consists of $$$3$$$ pairwise distinct integers, $$$a$$$, $$$b$$$, and $$$c$$$ ($$$1 \le a,b,c \le n$$$). It signifies that node $$$b$$$ cannot lie on the simple path between node $$$a$$$ and node $$$c$$$. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers, $$$n$$$ and $$$m$$$ ($$$3 \leq n \leq 10^5$$$, $$$\mathbf{1 \leq m < n}$$$), representing the size of the tree and the number of restrictions. The $$$i$$$-th of the next $$$m$$$ lines contains three integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$ ($$$1 \le a_i, b_i, c_i \le n$$$, $$$a$$$, $$$b$$$, $$$c$$$ are distinct), signifying that node $$$b_i$$$ cannot lie on the simple path between nodes $$$a_i$$$ and $$$c_i$$$.  It is guaranteed that the sum of $$$n$$$ across all test cases will not exceed $$$10^5$$$.

For each test case, output $$$n-1$$$ lines representing the $$$n-1$$$ edges in the tree. On each line, output two integers $$$u$$$ and $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \neq v$$$) signifying that there is an edge between nodes $$$u$$$ and $$$v$$$. Given edges have to form a tree that satisfies Omkar's restrictions.

NoteThe output of the first sample case corresponds to the following tree:    For the first restriction, the simple path between $$$1$$$ and $$$3$$$ is $$$1, 3$$$, which doesn't contain $$$2$$$. The simple path between $$$3$$$ and $$$5$$$ is $$$3, 5$$$, which doesn't contain $$$4$$$. The simple path between $$$5$$$ and $$$7$$$ is $$$5, 3, 1, 2, 7$$$, which doesn't contain $$$6$$$. The simple path between $$$6$$$ and $$$4$$$ is $$$6, 7, 2, 1, 3, 4$$$, which doesn't contain $$$5$$$. Thus, this tree meets all of the restrictions.The output of the second sample case corresponds to the following tree:

import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLine

object OmkarAndHeavenlyTree extends App {
  val t = readLine.trim.toInt
  for(_ <- 0 until t) {
    val n::m::_ = readLine.split(' ').toList.map(_.toInt)
    val seen : ListBuffer[Int] = ListBuffer()
    for(_ <- 1 to m) {
      val _::b::_::_ = readLine.split(' ').toList.map(_.toInt)
      seen += b
    }
    val all = (1 to n).toSet
    val possible = all.diff(seen.toSet).head
    val nodes = (all - possible).toList
    for (n <- nodes) {
      println(n + " " + possible)
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object sample extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        val mark = new Array[Boolean](n+1)
        for (i <- 1 to m){
            readInt()
            mark(readInt()) = true
            readInt()
        }
        var root = 0
        for (i <- 1 to n){
            if (!mark(i))
                root = i
        }
        for (i <- 1 to n){
            if (root != i) {
                writer.print(root)
                writer.print(" ")
                writer.println(i)
            }
        }
    }
    writer.flush()
}


The Fair Nut is going to travel to the Tree Country, in which there are $$$n$$$ cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city $$$u$$$ and go by a simple path to city $$$v$$$. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex.A filling station is located in every city. Because of strange law, Nut can buy only $$$w_i$$$ liters of gasoline in the $$$i$$$-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last.He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 3 \cdot 10^5$$$) — the number of cities. The second line contains $$$n$$$ integers $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \leq w_{i} \leq 10^9$$$) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next $$$n - 1$$$ lines describes road and contains three integers $$$u$$$, $$$v$$$, $$$c$$$ ($$$1 \leq u, v \leq n$$$, $$$1 \leq c \leq 10^9$$$, $$$u \ne v$$$), where $$$u$$$ and $$$v$$$ — cities that are connected by this road and $$$c$$$ — its length. It is guaranteed that graph of road connectivity is a tree.

Print one number — the maximum amount of gasoline that he can have at the end of the path.

NoteThe optimal way in the first example is $$$2 \to 1 \to 3$$$.   The optimal way in the second example is $$$2 \to 4$$$.

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 W = na(N)
    val From, To, Cost = Array.ofDim[Int](N - 1)
    REP(N - 1) { i =>
      From(i) = ni() - 1
      To(i) = ni() - 1
      Cost(i) = ni()
    }
    val g = packWUGraph(N, From, To, Cost)
    val (_, parent, queue) = traceBfs(g)

    val dp = Array.ofDim[Long](N)

    var ans = 0L
    REP_r(N) { i =>
      val v = queue(i)
      val single = W(v)

      var withChild = Long.MinValue
      val childCnt = g(v).length - (if (v != 0) 1 else 0)

      if (childCnt > 0) {
        val es = g(v)
        REP(es.length) { j =>
          val e = es(j)
          if (parent(v) != e.to) withChild = max(withChild, dp(e.to) - e.weight + W(v))
        }
      }
      dp(v) = max(single, withChild)
      ans = max(ans, dp(v))

      // merge
      if (childCnt > 1) {
        // 最上位２つが欲しい
        var mx1, mx2 = Long.MinValue

        val es = g(v)
        REP(es.length) { j =>
          val e = es(j)
          if (parent(v) != e.to) {
            mx2 = max(mx2, dp(e.to) - e.weight)
            // swap
            if (mx2 > mx1) {
              val tmp = mx1
              mx1 = mx2
              mx2 = tmp
            }
          }
        }

        val merged = mx1 + mx2 + W(v)
        ans = max(ans, merged)
      }
    }

    out.println(ans)
  }

  case class Edge(to: Int, weight: Int)
  type WUGraph = Array[Array[Edge]]
  /**
    * uwiのぱくり
    */
  def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Int]): WUGraph = {
    val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      g(from(i))(p(from(i))) = Edge(to(i), w(i))
      p(to(i)) -= 1
      g(to(i))(p(to(i))) = Edge(from(i), w(i))
    }
    g
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: WUGraph, 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 e = g(v)(i)
        val u = e.to
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

  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[Int](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 N = ni()
    val W = na(N)
    val From, To, Cost = Array.ofDim[Int](N - 1)
    REP(N - 1) { i =>
      From(i) = ni() - 1
      To(i) = ni() - 1
      Cost(i) = ni()
    }
    val g = packWUGraph(N, From, To, Cost)
    val (_, parent, queue) = traceBfs(g)

    val dp = Array.ofDim[Long](N)

    var ans = 0L
    REP_r(N) { i =>
      val v = queue(i)
      val single = W(v)

      var withChild = Long.MinValue
      if (g(v).length > 0) {
        val es = g(v)
        REP(es.length) { j =>
          val e = es(j)
          if (parent(v) != e.to) withChild = max(withChild, dp(e.to) - e.weight + W(v))
        }
      }
      dp(v) = max(single, withChild)
      ans = max(ans, dp(v))

      // merge
      if (g(v).length > 1) {
        // 最上位２つが欲しい
        var mx1, mx2 = Long.MinValue

        val es = g(v)
        REP(es.length) { j =>
          val e = es(j)
          if (parent(v) != e.to) {
            mx2 = max(mx2, dp(e.to) - e.weight)
            // swap
            if (mx2 > mx1) {
              val tmp = mx1
              mx1 = mx2
              mx2 = tmp
            }
          }
        }

        val merged = mx1 + mx2 + W(v)
        ans = max(ans, merged)
      }
    }

    out.println(ans)
  }

  case class Edge(to: Int, weight: Int)
  type WUGraph = Array[Array[Edge]]
  /**
    * uwiのぱくり
    */
  def packWUGraph(n: Int, from: Array[Int], to: Array[Int], w: Array[Int]): WUGraph = {
    val g = new Array[Array[Edge]](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 => g(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      g(from(i))(p(from(i))) = Edge(to(i), w(i))
      p(to(i)) -= 1
      g(to(i))(p(to(i))) = Edge(from(i), w(i))
    }
    g
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: WUGraph, 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 e = g(v)(i)
        val u = e.to
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

  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[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


Recenlty Luba got a credit card and started to use it. Let's consider n consecutive days Luba uses the card.She starts with 0 money on her account.In the evening of i-th day a transaction ai occurs. If ai > 0, then ai bourles are deposited to Luba's account. If ai < 0, then ai bourles are withdrawn. And if ai = 0, then the amount of money on Luba's account is checked.In the morning of any of n days Luba can go to the bank and deposit any positive integer amount of burles to her account. But there is a limitation: the amount of money on the account can never exceed d.It can happen that the amount of money goes greater than d by some transaction in the evening. In this case answer will be «-1».Luba must not exceed this limit, and also she wants that every day her account is checked (the days when ai = 0) the amount of money on her account is non-negative. It takes a lot of time to go to the bank, so Luba wants to know the minimum number of days she needs to deposit some money to her account (if it is possible to meet all the requirements). Help her!

The first line contains two integers n, d (1 ≤ n ≤ 105, 1 ≤ d ≤ 109) —the number of days and the money limitation. The second line contains n integer numbers a1, a2, ... an ( - 104 ≤ ai ≤ 104), where ai represents the transaction in i-th day.

Print -1 if Luba cannot deposit the money to her account in such a way that the requirements are met. Otherwise print the minimum number of days Luba has to deposit money.

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

import collection.Searching._
import scala.collection.mutable

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

  def doCase() : Unit = {
    val Array(n, d) = readLongLine()
    val transactions = readLongLine()

    val nint = n.toInt
    val sums : Array[Long] = Array.ofDim(nint)
    var i = 1
    sums(0) = transactions(0)
    while (i < sums.length) {
      sums(i) = transactions(i) + sums(i - 1)
      i += 1
    }
    val greatestToCome : Array[Long] = Array.ofDim(nint)
    greatestToCome(nint - 1) = sums(nint - 1)
    i = nint - 2
    while (i >= 0) {
      greatestToCome(i) = Math.max(greatestToCome(i + 1), sums(i))
      i -= 1
    }

    var days = 0
    var totalDeposited = 0L
    var balance = 0L
    i = 0
    while (i < transactions.length) {
      val t = transactions(i)
      if (t == 0 && balance < 0) {
        val toDeposit = d - (greatestToCome(i) + totalDeposited)
        balance += toDeposit
        if (balance < 0) {
          println(-1)
          return
        }
        totalDeposited += toDeposit
        days += 1
      }
      balance += t
      if (balance > d) {
        println(-1)
        return
      }
      i += 1
    }
    println(days)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

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

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

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

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

import collection.Searching._
import scala.collection.mutable

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

  def doCase() : Unit = {
    val Array(n, d) = readLongLine()
    val transactions = readLongLine()

    val nint = n.toInt
    var greatestToCome : Array[Long] = Array.ofDim(nint)
    greatestToCome(nint - 1) = transactions(nint - 1)
    var i = nint - 2
    while (i >= 0) {
      greatestToCome(i) = Math.max(greatestToCome(i + 1), transactions(i))
      i -= 1
    }

    var days = 0
    var totalDeposited = 0L
    var balance = 0L
    i = 0
    while (i < transactions.length) {
      val t = transactions(i)
      if (t == 0 && balance < 0) {
        val toDeposit = d - (greatestToCome(i) + totalDeposited) - balance
        balance += toDeposit
        if (balance < 0) {
          println(-1)
          return
        }
        totalDeposited += toDeposit
        days += 1
      }
      balance += t
      if (balance > d) {
        println(-1)
        return
      }
      i += 1
    }
    println(days)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

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

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

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

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

import collection.Searching._
import scala.collection.mutable

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

  def doCase() : Unit = {
    val Array(n, d) = readLongLine()
    val transactions = readLongLine()

    val nint = n.toInt
    var greatestToCome : Array[Long] = Array.ofDim(nint)
    greatestToCome(nint - 1) = transactions(nint - 1)
    var i = nint - 2
    while (i >= 0) {
      greatestToCome(i) = Math.max(greatestToCome(i + 1), transactions(i))
      i -= 1
    }

    var days = 0
    var totalDeposited = 0L
    var balance = 0L
    i = 0
    while (i < transactions.length) {
      val t = transactions(i)
      if (t == 0 && balance < 0) {
        val toDeposit = d - (greatestToCome(i) + totalDeposited) - balance
        balance += toDeposit
        if (balance < 0) {
          println(-1)
          return
        }
        totalDeposited += toDeposit
        days += 1
      }
      balance += t
      i += 1
    }
    println(days)
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
      caseNo += 1
    }
  }

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

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

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


Victor has a 24-hour clock that shows the time in the format "HH:MM" (00 $$$\le$$$ HH $$$\le$$$ 23, 00 $$$\le$$$ MM $$$\le$$$ 59). He looks at the clock every $$$x$$$ minutes, and the clock is currently showing time $$$s$$$. How many different palindromes will Victor see in total after looking at the clock every $$$x$$$ minutes, the first time being at time $$$s$$$?For example, if the clock starts out as 03:12 and Victor looks at the clock every $$$360$$$ minutes (i.e. every $$$6$$$ hours), then he will see the times 03:12, 09:12, 15:12, 21:12, 03:12, and the times will continue to repeat. Here the time 21:12 is the only palindrome he will ever see, so the answer is $$$1$$$.A palindrome is a string that reads the same backward as forward. For example, the times 12:21, 05:50, 11:11 are palindromes but 13:13, 22:10, 02:22 are not.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of each test case follows. The only line of each test case contains a string $$$s$$$ of length $$$5$$$ with the format "HH:MM" where "HH" is from "00" to "23" and "MM" is from "00" to "59" (both "HH" and "MM" have exactly two digits) and an integer $$$x$$$ ($$$1 \leq x \leq 1440$$$) — the number of minutes Victor takes to look again at the clock.

For each test case, output a single integer — the number of different palindromes Victor will see if he looks at the clock every $$$x$$$ minutes starting from time $$$s$$$.

NoteThe first test case is explained in the statement.

import scala.collection.mutable
import scala.io.StdIn
import scala.math.BigDecimal.double2bigDecimal

object Main {

  def isPalindrome(currentTime: (Int, Int)): Boolean = {
    val hour = currentTime._1.toString.reverse.padTo(2, '0').reverse
    val minute = currentTime._2.toString.reverse.padTo(2, '0').reverse

    (hour + minute).reverse == (hour + minute)
  }

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

    for (_ <- 0 until t) {
      val Array(timeS, minutesS) = StdIn.readLine().split(" ")
      val Array(hourS, minuteS) = timeS.split(":")

      val hour = hourS.toInt
      val minute = minuteS.toInt
      val minutes = minutesS.toInt

      val seen = mutable.Set[(Int, Int)]()

      var currentTime = (hour, minute)
      var palindromes = 0

      while(!seen.contains(currentTime)) {
        seen.add(currentTime)
        if(isPalindrome(currentTime)) {
          palindromes += 1
        }
        val newMinutes = (currentTime._2 + minutes) % 60
        val newHours = (currentTime._1 + (currentTime._2 + minutes)/60) % 24

        currentTime = (newHours, newMinutes)
      }

      println(palindromes)
    }
  }

}


A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri].You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want to test your assumption. Find in the given set the segment which covers all other segments, and print its number. If such a segment doesn't exist, print -1.Formally we will assume that segment [a, b] covers segment [c, d], if they meet this condition a ≤ c ≤ d ≤ b.

The first line contains integer n (1 ≤ n ≤ 105) — the number of segments. Next n lines contain the descriptions of the segments. The i-th line contains two space-separated integers li, ri (1 ≤ li ≤ ri ≤ 109) — the borders of the i-th segment. It is guaranteed that no two segments coincide.

Print a single integer — the number of the segment that covers all other segments in the set. If there's no solution, print -1. The segments are numbered starting from 1 in the order in which they appear in the input.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(' ').map(_.toInt))
  val minFirst = data.minBy(_.head).head
  val maxSecond = data.maxBy(_.last).last
  println(data.indices.find(a => data(a).head == minFirst && data(a).last == maxSecond).map(i => i + 1).getOrElse(-1))
}

import java.util.Scanner
import scala.collection.mutable._

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

  val n = sc.nextInt
  val seg = (1<<30, 0) :: List.tabulate(n)(_ => (sc.nextInt, sc.nextInt))
  val s = seg.reduce((a, b) => (math.min(a._1, b._1), math.max(a._2, b._2)))

  println(seg.indexOf(s))
}

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

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

  def solve(): Int = {
    val N = sc.nextInt
    val Segments = List.fill(N, 2)(sc.nextLong)
    val List(s, t) = Segments.transpose
    val S = s.min
    val T = t.max

    @tailrec
    def loop(i: Int, segments: List[List[Long]]): Int = segments match {
        case Nil => -1
        case List(`S`, `T`) :: xs => i
        case _ => loop(i + 1, segments.tail)
      }

    loop(1, Segments)
 }

  out.println(solve)
  out.close
}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 23 Jun 2016
 */
object B242 extends App {

  def checkExists(pairs: IndexedSeq[(Int, Int)], min: Int, max: Int): Int = {
    for (i <- 0 until pairs.size) {
      if (pairs(i)._1 == min && pairs(i)._2 == max) {
        return i+1
      }
    }

    -1
  }

  def solve() = {
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    val n = reader.readLine().toInt
    val pairs: IndexedSeq[(Int, Int)] = (0 until n).map((i) => {
      val split = reader.readLine().split(" ")
      (split(0).toInt, split(1).toInt)
    })
    val min: Int = pairs.minBy(_._1)._1
    val max: Int = pairs.maxBy(_._2)._2
    println(checkExists(pairs, min, max))
  }

  solve()

}

// CodeForces 242B

object BigLine extends App {
  val n = Console.readInt
  val seqpr: Seq[(Int, Int)] = for {
    i <- Range(0, n)
    val ln = (Console.readLine()).split(" ") map (_.toInt)
  } yield (ln(0), ln(1))
  val lpr = seqpr toList

  def maxPr(lpr: List[(Int, Int)], idx:Int, maxP:(Int, Int, Int)):(Int, Int, Int) = lpr match {
    case Nil => maxP
    case (a,b) :: tl => {
      val (ma, mb, ii) = maxP
      if (a<=ma && mb<=b) maxPr(tl, idx+1, (a,b, idx))
      else if (ma<=a && b<=mb) maxPr(tl, idx+1, (ma, mb, ii))
      else maxPr(tl, idx+1, (Math.min(a,ma), Math.max(b, mb), -1))
    }
  }

  val (a,b,idx) = maxPr(lpr.tail, 2, (lpr.head._1, lpr.head._2, 1))
  println(idx)
}

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

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

  val segs = for(_ <- 1 to readInt) yield readInts
  val foo = Array((x: Int, y: Int) => x min y, (x: Int, y: Int) => x max y)
  val seg = segs.transpose.zip(foo).map(x => x._1.reduceLeft(x._2))
  def ans = segs.indexWhere(_.sameElements(seg)) match {
    case -1 => -1
    case x => x + 1
  }

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

import java.util.Scanner

object Main extends App
{
	val cin=new Scanner(System.in)
	val n=cin.nextInt()
	val seg=(1<<30,0) :: List.tabulate(n)(_=>(cin.nextInt,cin.nextInt))
	val s=seg.reduce((a,b) => (math.min(a._1,b._1),math.max(a._2,b._2)))
	println(seg.indexOf(s))
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val tr = a.transpose
    val min = tr(0).min
    val max = tr(1).max
    val t = a.zipWithIndex.find(t => t._1(0) == min && t._1(1) == max)
    t match {
      case None => println("-1")
      case Some(t0) => println(t0._2 + 1)
    }
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val res = (1 to n).foldLeft((true, 0, 0, 0)) {
    case(acc, 1) =>
      val Array(l, r) = in.next().split(' ').map(_.toInt)
      (true, l, r, 1)
    case(acc@(false, _, _, _), _) => acc
    case(acc@(true, la, ra, ri), i) =>
      val Array(l, r) = in.next().split(' ').map(_.toInt)
      if (l <= la && r >= ra)
        (true, l, r, i)
      else if (l >= la && r <= ra)
        acc
      else
        (false, l, r, i)
  }
  if (res._1)
    println(res._4)
  else
    println(-1)
}

object BigLine extends App {
  val n = Console.readInt
  val seqpr: Seq[(Int, Int)] = for {
    i <- Range(0, n)
    val ln = (Console.readLine()).split(" ") map (_.toInt)
  } yield (ln(0), ln(1))
  val lpr = seqpr toList

  def maxPr(lpr: List[(Int, Int)], idx:Int, maxP:(Int, Int, Int)):(Int, Int, Int) = lpr match {
    case Nil => maxP
    case (a,b) :: tl => {
      val (ma, mb, ii) = maxP
      if (a<=ma && mb<=b) maxPr(tl, idx, (a,b, idx))
      else if (ma<=a && b<=mb) maxPr(tl, idx+1, (ma, mb, ii))
      else maxPr(tl, idx+1, (Math.min(a,ma), Math.max(b, mb), -1))
    }
  }

  val (a,b,idx) = maxPr(lpr.tail, 2, (lpr.head._1, lpr.head._2, 1))
  println(idx)
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = (1 to n).map(_ => readLine().split(" ").map(_.toInt))
    val tr = a.transpose
    val min = a(0).min
    val max = a(1).max
    val t = a.zipWithIndex.find(t => t._1(0) == min && t._1(1) == max)
    t match {
      case None => println("-1")
      case Some(t0) => println(t0._2)
    }
  }
}


One unknown hacker wants to get the admin's password of AtForces testing system, to get problems from the next contest. To achieve that, he sneaked into the administrator's office and stole a piece of paper with a list of $$$n$$$ passwords — strings, consists of small Latin letters.Hacker went home and started preparing to hack AtForces. He found that the system contains only passwords from the stolen list and that the system determines the equivalence of the passwords $$$a$$$ and $$$b$$$ as follows:  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a letter, that exists in both $$$a$$$ and $$$b$$$;  two passwords $$$a$$$ and $$$b$$$ are equivalent if there is a password $$$c$$$ from the list, which is equivalent to both $$$a$$$ and $$$b$$$. If a password is set in the system and an equivalent one is applied to access the system, then the user is accessed into the system.For example, if the list contain passwords "a", "b", "ab", "d", then passwords "a", "b", "ab" are equivalent to each other, but the password "d" is not equivalent to any other password from list. In other words, if:  admin's password is "b", then you can access to system by using any of this passwords: "a", "b", "ab";  admin's password is "d", then you can access to system by using only "d". Only one password from the list is the admin's password from the testing system. Help hacker to calculate the minimal number of passwords, required to guaranteed access to the system. Keep in mind that the hacker does not know which password is set in the system.

The first line contain integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of passwords in the list. Next $$$n$$$ lines contains passwords from the list – non-empty strings $$$s_i$$$, with length at most $$$50$$$ letters. Some of the passwords may be equal. It is guaranteed that the total length of all passwords does not exceed $$$10^6$$$ letters. All of them consist only of lowercase Latin letters.

In a single line print the minimal number of passwords, the use of which will allow guaranteed to access the system.

NoteIn the second example hacker need to use any of the passwords to access the system.

import scala.collection.immutable.BitSet
import scala.collection.mutable
import scala.collection.parallel.immutable

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

  def long(xs: Iterator[Int]): Long = {
    var y = 0L
    for (x <- xs) y |= (1L << x)
    y
  }

  val n = nextInt
  val ps = Array.fill(n)(long(nextLine.iterator.map(_ - 'a')))

  val xs = mutable.Set.empty[Long]

  for (p <- ps) {
    var pp = p
    for (x <- xs) {
      if ((x & pp) != 0) {
        pp |= x
        xs.remove(x)
      }
    }
    xs += pp
  }

  out.println(xs.size)
  out.flush()

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


Fox Ciel has a board with n rows and n columns. So, the board consists of n × n cells. Each cell contains either a symbol '.', or a symbol '#'.A cross on the board is a connected set of exactly five cells of the board that looks like a cross. The picture below shows how it looks.Ciel wants to draw several (may be zero) crosses on the board. Each cross must cover exactly five cells with symbols '#', and any cell with symbol '#' must belong to some cross. No two crosses can share a cell.Please, tell Ciel if she can draw the crosses in the described way.

The first line contains an integer n (3 ≤ n ≤ 100) — the size of the board. Each of the next n lines describes one row of the board. The i-th line describes the i-th row of the board and consists of n characters. Each character is either a symbol '.', or a symbol '#'.

Output a single line with "YES" if Ciel can draw the crosses in the described way. Otherwise output a single line with "NO".

NoteIn example 1, you can draw two crosses. The picture below shows what they look like.In example 2, the board contains 16 cells with '#', but each cross contains 5. Since 16 is not a multiple of 5, so it's impossible to cover all.

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

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

  def solve(): String = {
    val N = sc.nextInt
    sc.nextLine

    val B = Array.fill(N) {
        val line = Array.ofDim[Char](N + 2)
        Array.copy(sc.nextLine.toArray, 0, line, 1, N)
        line
      }

    def eraseCross(i: Int, j: Int): Boolean = {
      val cells = List((i, j),
                       (i + 1, j - 1),
                       (i + 1, j),
                       (i + 1, j + 1),
                       (i + 2, j))
      val isCross = cells.forall { c => B(c._1)(c._2) == '#' }
      val erase = cells.foreach { c => B(c._1)(c._2) = '.' }
      isCross
    }

    var res = true
    breakable {
      for (i <- 0 until N - 2; j <- 1 to N) {
        if (B(i)(j) == '#' && !eraseCross(i, j)) {
          res = false
          break
        }
      }
    }
    res = res && B.flatten.forall(_ != '#')
    if (res) "YES"
    else "NO"
  }

  out.println(solve)
  out.close
}

import java.util

object Main {
  var st = new util.StringTokenizer("")

  def readToken() = {
    while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)
    st.nextToken
  }

  val n = readToken.toInt
  val g = Array.ofDim[Int](n, n)

  def check(): Boolean = {
    for (i <- 0 until n) {
      if (g(i)(0) == 1 || g(i)(n - 1) == 1) return false
      for (j <- 1 until n - 1) {
        if (g(i)(j) == 1) {
          if (i + 2 >= n) return false
          if (g(i + 1)(j) == 0) return false
          if (g(i + 2)(j) == 0) return false
          if (g(i + 1)(j + 1) == 0) return false
          if (g(i + 1)(j - 1) == 0) return false

          g(i + 1)(j) = 0
          g(i + 2)(j) = 0
          g(i + 1)(j + 1) = 0
          g(i + 1)(j - 1) = 0
        }
      }
    }
    true
  }

  def main(args: Array[String]) {
    (0 until n).foreach(i => {
      val s = readLine
      (0 until s.size).foreach(j => {
        g(i)(j) = if (s(j) == '#') 1 else 0
      })
    })

    printf(if (check) "YES" else "NO")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().toCharArray).toArray
  val changes = List((0, 0), (1, 0), (2, 0), (1, -1), (1, 1))

  def mark(arr: Array[Array[Char]], i: Int, j: Int): Boolean = {
    val delta = changes.map{case (di, dj) => (di + i, dj + j)}
//    println(delta)
    val res = delta.forall{case(ni, nj) => ni >= 0 && nj >= 0 && ni < n && nj < n && arr(ni)(nj) == '#'}
//    println(res)
    if (res)
      delta.foreach{case(ni, nj) => arr(ni)(nj) = '.'}
    res
  }

  val res = (0 until n).foldLeft(true) {
    case (false, _) => false
    case (true, i) => data(i).indices.foldLeft(true) {
      case (false, _) => false
      case (true, j) if data(i)(j) == '#' => mark(data, i, j)
      case (true, j) => true
    }
  }
//  println(data.map(_.mkString).mkString("\n"))
  if (res)
    println("YES")
  else
    println("NO")
}


Consider the array $$$a$$$ composed of all the integers in the range $$$[l, r]$$$. For example, if $$$l = 3$$$ and $$$r = 7$$$, then $$$a = [3, 4, 5, 6, 7]$$$.Given $$$l$$$, $$$r$$$, and $$$k$$$, is it possible for $$$\gcd(a)$$$ to be greater than $$$1$$$ after doing the following operation at most $$$k$$$ times?   Choose $$$2$$$ numbers from $$$a$$$.  Permanently remove one occurrence of each of them from the array.  Insert their product back into $$$a$$$. $$$\gcd(b)$$$ denotes the greatest common divisor (GCD) of the integers in $$$b$$$.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. The description of test cases follows. The input for each test case consists of a single line containing $$$3$$$ non-negative integers $$$l$$$, $$$r$$$, and $$$k$$$ ($$$1 \leq l \leq r \leq 10^9, \enspace 0 \leq k \leq r - l$$$).

For each test case, print "YES" if it is possible to have the GCD of the corresponding array greater than $$$1$$$ by performing at most $$$k$$$ operations, and "NO" otherwise (case insensitive).

NoteFor the first test case, $$$a = [1]$$$, so the answer is "NO", since the only element in the array is $$$1$$$.For the second test case the array is $$$a = [3, 4, 5]$$$ and we have $$$1$$$ operation. After the first operation the array can change to: $$$[3, 20]$$$, $$$[4, 15]$$$ or $$$[5, 12]$$$ all of which having their greatest common divisor equal to $$$1$$$ so the answer is "NO".For the third test case, $$$a = [13]$$$, so the answer is "YES", since the only element in the array is $$$13$$$.For the fourth test case, $$$a = [4]$$$, so the answer is "YES", since the only element in the array is $$$4$$$.

import sun.management.counter.Counter

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

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(l, r, k) = readLongs()
    val oddNumber = if (l % 2 == 1) (r - l + 2) / 2 else (r - l + 1) / 2
    if (((r - l + 1 == 1) || (oddNumber <= k)) && !(r == 1 && l == 1))  println("YES") else println("NO")
  }

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

  def gcd(a: Long, b: Long): Long = if (a == 0) b else gcd(b % a, b)

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }

    def contains(value: T) = multiSet.contains(value)

    def max: T = multiSet.last._1

    def min: T = multiSet.head._1

    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }

    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val l = readInt()
        val r = readInt()
        val k = readInt()
        var cnt = r - l + 1
        if (cnt % 2 == 0) {
            cnt /= 2
        } else {
            cnt /= 2
            if (r % 2 == 1) {
                cnt += 1
            }
        }
        if (r == l && r != 1) {
            writer.println("YES")
        }else if (cnt > k || r == 1) {
            writer.println("NO")
        } else {
            writer.println("YES")
        }

        def check(kk: Long, fi: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long, fi:Long): Long = {
            if (en - st <= 1L) {
                if (check(st, fi))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid, fi))
                return bs(st, mid, fi)
            else
                return bs(mid, en, fi)
        }
    }
    writer.flush()
}