A sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a length of not more than d meters. Running and jumping is permitted only in the direction from left to right. He can start andfinish a jump only at the points with integer coordinates in which there are no obstacles. To overcome some obstacle, it is necessary to land at a point which is strictly to the right of this obstacle.On the way of an athlete are n obstacles at coordinates x1, x2, ..., xn. He cannot go over the obstacles, he can only jump over them. Your task is to determine whether the athlete will be able to get to the finish point.

The first line of the input containsd four integers n, m, s and d (1 ≤ n ≤ 200 000, 2 ≤ m ≤ 109, 1 ≤ s, d ≤ 109) — the number of obstacles on the runner's way, the coordinate of the finishing point, the length of running before the jump and the maximum length of the jump, correspondingly. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ m - 1) — the coordinates of the obstacles. It is guaranteed that the starting and finishing point have no obstacles, also no point can have more than one obstacle, The coordinates of the obstacles are given in an arbitrary order.

If the runner cannot reach the finishing point, print in the first line of the output "IMPOSSIBLE" (without the quotes). If the athlete can get from start to finish, print any way to do this in the following format:   print a line of form "RUN X>" (where "X" should be a positive integer), if the athlete should run for "X" more meters;  print a line of form "JUMP Y" (where "Y" should be a positive integer), if the sportsman starts a jump and should remain in air for "Y" more meters.  All commands "RUN" and "JUMP" should strictly alternate, starting with "RUN", besides, they should be printed chronologically. It is not allowed to jump over the finishing point but it is allowed to land there after a jump. The athlete should stop as soon as he reaches finish.

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.collection.mutable
import scala.io.Codec

/**
  * @author itegulov
  */
object D extends App {

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

  val n = in.nextInt()
  val m = in.nextInt()
  val s = in.nextInt()
  val d = in.nextInt()
  var a: Array[Int] = Array.ofDim(n + 2)
  a(0) = 0
  a(n + 1) = m + 1

  for (i <- 1 to n) {
    a(i) = in.nextInt()
  }

  a = a.sorted

  if (a(1) - a(0) - 1 < s) {
    println("IMPOSSIBLE")
  } else {
    var lastJumpIndex = 0

    val jumpFrom: Array[Int] = Array.fill(n + 1)(-1)

    for (i <- 1 to n)
      if ((a(i) + 1) - (a(lastJumpIndex + 1) - 1) <= d) {
        jumpFrom(i) = lastJumpIndex
        if ((a(i + 1) - 1) - (a(i) + 1) >= s) lastJumpIndex = i
      }

    if (jumpFrom(n) == -1) {
      println("IMPOSSIBLE")
    } else {
      val answer: mutable.ArrayBuffer[String] = mutable.ArrayBuffer()

      var last = n
      while (last > 0) {
        if (a(last + 1) - 1 - (a(last) + 1) > 0) answer += ("RUN " + (a(last + 1) - 1 - (a(last) + 1)))
        answer += ("JUMP " + (a(last) + 1 - (a(jumpFrom(last) + 1) - 1)))
        last = jumpFrom(last)
      }
      answer += ("RUN " + (a(1) - 1 - a(0)))

      answer.reverse.foreach(out.println)
    }
  }

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine())
      .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.collection.mutable
import scala.io.Codec

/**
  * @author itegulov
  */
object D extends App {

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

  val n = in.nextInt()
  val m = in.nextInt()
  val s = in.nextInt()
  val d = in.nextInt()
  var a: Array[Int] = Array.ofDim(n + 2)
  a(0) = 0
  a(n + 1) = m + 1

  for (i <- 1 to n) {
    a(i) = in.nextInt()
  }

  a = a.sorted

  if (a(1) - a(0) - 1 < s) {
    println("IMPOSSIBLE")
  } else {
    var lastJumpIndex = 0

    val jumpFrom: Array[Int] = Array.fill(n + 1)(-1)

    for (i <- 1 to n)
      if ((a(i) + 1) - (a(lastJumpIndex + 1) - 1) <= d) {
        jumpFrom(i) = lastJumpIndex
        if (a(i + 1) - a(i) - 1 >= s) lastJumpIndex = i
      }

    if (jumpFrom(n) == -1) {
      println("IMPOSSIBLE")
    } else {
      val answer: mutable.ArrayBuffer[String] = mutable.ArrayBuffer()

      var last = n
      while (last > 0) {
        if (a(last + 1) - 1 - (a(last) + 1) > 0) answer += ("RUN " + (a(last + 1) - 1 - (a(last) + 1)))
        answer += ("JUMP " + (a(last) + 1 - (a(jumpFrom(last) + 1) - 1)))
        last = jumpFrom(last)
      }
      answer += ("RUN " + (a(1) - 1 - a(0)))

      answer.reverse.foreach(out.println)
    }
  }

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine())
      .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.collection.mutable
import scala.io.Codec

/**
  * @author itegulov
  */
object D extends App {

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

  val n = in.nextInt()
  val m = in.nextInt()
  val s = in.nextInt()
  val d = in.nextInt()
  var a: Array[Int] = Array.ofDim(n + 2)
  a(0) = 0
  a(n + 1) = m + 1

  for (i <- 1 to n) {
    a(i) = in.nextInt()
  }

  a = a.sorted

  if (a(1) - a(0) - 1 < s) {
    println("IMPOSSIBLE")
  } else {
    var lastJumpIndex = 0

    val jumpFrom: Array[Int] = Array.fill(n + 1)(-1)

    for (i <- 1 to n)
      if ((a(i) + 1) - (a(lastJumpIndex + 1) - 1) <= d) {
        jumpFrom(i) = lastJumpIndex
        if (a(i + 1) - a(i) - 1 >= s) lastJumpIndex = i
      }

    if (jumpFrom(n) == -1) {
      println("IMPOSSIBLE")
    } else {
      val answer: mutable.ArrayBuffer[String] = mutable.ArrayBuffer()

      var last = n
      while (last > 0) {
        answer += ("RUN " + (a(last + 1) - 1 - (a(last) + 1)))
        answer += ("JUMP " + (a(last) + 1 - (a(jumpFrom(last) + 1) - 1)))
        last = jumpFrom(last)
      }
      answer += ("RUN " + (a(1) - 1 - a(0)))

      answer.reverse.foreach(out.println)
    }
  }

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine())
      .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}


YouKn0wWho has two even integers $$$x$$$ and $$$y$$$. Help him to find an integer $$$n$$$ such that $$$1 \le n \le 2 \cdot 10^{18}$$$ and $$$n \bmod x = y \bmod n$$$. Here, $$$a \bmod b$$$ denotes the remainder of $$$a$$$ after division by $$$b$$$. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$)  — the number of test cases. The first and only line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$2 \le x, y \le 10^9$$$, both are even).

For each test case, print a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^{18}$$$) that satisfies the condition mentioned in the statement. If there are multiple such integers, output any. It can be shown that such an integer always exists under the given constraints.

NoteIn the first test case, $$$4 \bmod 4 = 8 \bmod 4 = 0$$$.In the second test case, $$$10 \bmod 4 = 2 \bmod 10 = 2$$$.In the third test case, $$$420 \bmod 420 = 420 \bmod 420 = 0$$$.

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 pair(var minl: Int, var maxl:  Int, var minr: Int, var maxr:  Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return minl.compareTo(that.minl)
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readLong()
        val m = readLong()
        var k = 0L
        if (n > m) {
            k = 1000000000L*n+m
        } else {
            k = (m/n).toLong
            k *= n
            k = (m + k)/2L
        }
        writer.println(k)
    }
    writer.flush()
}


You have a Petri dish with bacteria and you are preparing to dive into the harsh micro-world. But, unfortunately, you don't have any microscope nearby, so you can't watch them.You know that you have $$$n$$$ bacteria in the Petri dish and size of the $$$i$$$-th bacteria is $$$a_i$$$. Also you know intergalactic positive integer constant $$$K$$$.The $$$i$$$-th bacteria can swallow the $$$j$$$-th bacteria if and only if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The $$$j$$$-th bacteria disappear, but the $$$i$$$-th bacteria doesn't change its size. The bacteria can perform multiple swallows. On each swallow operation any bacteria $$$i$$$ can swallow any bacteria $$$j$$$ if $$$a_i > a_j$$$ and $$$a_i \le a_j + K$$$. The swallow operations go one after another.For example, the sequence of bacteria sizes $$$a=[101, 53, 42, 102, 101, 55, 54]$$$ and $$$K=1$$$. The one of possible sequences of swallows is: $$$[101, 53, 42, 102, \underline{101}, 55, 54]$$$ $$$\to$$$ $$$[101, \underline{53}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[\underline{101}, 42, 102, 55, 54]$$$ $$$\to$$$ $$$[42, 102, 55, \underline{54}]$$$ $$$\to$$$ $$$[42, 102, 55]$$$. In total there are $$$3$$$ bacteria remained in the Petri dish.Since you don't have a microscope, you can only guess, what the minimal possible number of bacteria can remain in your Petri dish when you finally will find any microscope.

The first line contains two space separated positive integers $$$n$$$ and $$$K$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le K \le 10^6$$$) — number of bacteria and intergalactic constant $$$K$$$. The second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — sizes of bacteria you have.

Print the only integer — minimal possible number of bacteria can remain.

NoteThe first example is clarified in the problem statement.In the second example an optimal possible sequence of swallows is: $$$[20, 15, 10, 15, \underline{20}, 25]$$$ $$$\to$$$ $$$[20, 15, 10, \underline{15}, 25]$$$ $$$\to$$$ $$$[20, 15, \underline{10}, 25]$$$ $$$\to$$$ $$$[20, \underline{15}, 25]$$$ $$$\to$$$ $$$[\underline{20}, 25]$$$ $$$\to$$$ $$$[25]$$$.In the third example no bacteria can swallow any other bacteria.

object B extends App {
  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

  var c = 0
  var r = 1
  var j = a.head
  for (i <- a.tail) {
    if (i == j) r += 1
    else {
      if (i - j > k) c += r
      r = 1
    }

    j = i
  }

  println(c + r)
}

object B extends App {
  val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted

  var c = 0
  var r = 1
  var j = a.head
  for (i <- a.tail) {
    if (i == j) r += 1
    else {
      if (i - j > k) c += 1
      r = 1
    }

    j = i
  }

  println(c + r)
}


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ of length $$$n$$$ containing each number exactly once. For example, $$$[1]$$$, $$$[4, 3, 5, 1, 2]$$$, $$$[3, 2, 1]$$$ are permutations, and $$$[1, 1]$$$, $$$[0, 1]$$$, $$$[2, 2, 1, 4]$$$ are not.There was a permutation $$$p[1 \dots n]$$$. It was merged with itself. In other words, let's take two instances of $$$p$$$ and insert elements of the second $$$p$$$ into the first maintaining relative order of elements. The result is a sequence of the length $$$2n$$$.For example, if $$$p=[3, 1, 2]$$$ some possible results are: $$$[3, 1, 2, 3, 1, 2]$$$, $$$[3, 3, 1, 1, 2, 2]$$$, $$$[3, 1, 3, 1, 2, 2]$$$. The following sequences are not possible results of a merging: $$$[1, 3, 2, 1, 2, 3$$$], [$$$3, 1, 2, 3, 2, 1]$$$, $$$[3, 3, 1, 2, 2, 1]$$$.For example, if $$$p=[2, 1]$$$ the possible results are: $$$[2, 2, 1, 1]$$$, $$$[2, 1, 2, 1]$$$. The following sequences are not possible results of a merging: $$$[1, 1, 2, 2$$$], [$$$2, 1, 1, 2]$$$, $$$[1, 2, 2, 1]$$$.Your task is to restore the permutation $$$p$$$ by the given resulting sequence $$$a$$$. It is guaranteed that the answer exists and is unique.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 400$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the length of permutation. The second line of the test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the array $$$a$$$ represents the result of merging of some permutation $$$p$$$ with the same permutation $$$p$$$.

For each test case, print the answer: $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$), representing the initial permutation. It is guaranteed that the answer exists and is unique.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n   = readInt()
    val a2n = readLine().split(" ").map(_.toInt)

    var flags = Array.fill(n + 1)(0)
    val an    = a2n.foldLeft(List.empty[Int])((as, a) => if (flags(a) == 1) as else { flags(a) = 1; a :: as }).reverse

    println(an.mkString(" "))
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n   = readInt()
    val a2n = readLine().split(" ").map(_.toInt)
    val an  = a2n.distinct

    println(an.mkString(" "))
  }
}

import scala.io.StdIn._

object contest356B extends App {

  def getRear(input: Array[Int]): String= {
    val res = new Array[Int](input.length / 2)
    var found = 0
    for (i <- 0 until input.length) {
      if (!res.contains(input(i))) {
        res(found) = input(i)
        found += 1
      }
    }
    var fin = ""
    res.foreach(x => fin += s"$x ")
    fin.dropRight(1)
  }

  val t = readInt
  var lst: List[String] = List()
  for(a <- 1 to t){
    readLine
    val input :Array[Int] = readLine.split(" ").map(_.toInt)
    lst = getRear(input) :: lst
  }

  for(y <- lst.length-1 to 0 by -1){
    println(lst(y))
  }

}


Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.

The first line contains two space-separated integers, n and m (3 ≤ n ≤ 4000, 0 ≤ m ≤ 4000) — respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.

If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).

NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.In the second sample there is no triple of warriors knowing each other.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(" ").map(_.toInt)
  val known = Array.fill[Set[Int]](n){Set.empty[Int]}
  Range(0, m).foreach { _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    known(a) += b
    known(b) += a
  }
  val r = known.indices.flatMap{ i =>
    known(i).flatMap{j =>
      known(j).intersect(known(i)).map(t => known(i).size + known(j).size + known(t).size)
    }
  }
  if (r.isEmpty)
    println(-1)
  else
    println(r.min - 6)
}

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

object BearMusketeers {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def findMin(g : Map[Int,IndexedSeq[Int]], n: Int) : Int = {
     var curBest = scala.Int.MaxValue
     for (i <- 1 to n) {
       if (g(i).size < curBest) {
         for (j <- g(i).filter { _ > i }) {
           if (g(i).size + g(j).size < curBest) {
             for (k <- g(i).filter{x => x > j && (g(j) contains x) }) {
               if (g(i).size + g(j).size + g(k).size < curBest)
                 curBest = g(i).size + g(j).size + g(k).size
             }
           }
         }
       }
     }
     if (curBest < scala.Int.MaxValue) curBest - 6 else -1
   }

   def main(args: Array[String]) {
     val (n,m) = readTuple
     val abs = for {
       i <- 1 to m
       t = readTuple
     } yield t
     val absSym = abs.flatMap(t => List(t,(t._2,t._1))).groupBy(_._1)
       .mapValues(is => is.map(_._2))
       .filterNot{ _._2.length < 2}

     /* val mins = for {
       i <- absSym.keys
       j <- absSym(i).filter(_ > i)
       k <- absSym(i).filter(k => k  > j )
       if (absSym.getOrElse(j, IndexedSeq[Int]()) contains k)
       //_ =   println(s"$i, $j en $k kennen elkaar size ${(absSym(i).size + absSym(j).size + absSym(k).size)}")

     } yield (absSym(i).size + absSym(j).size + absSym(k).size)
     if (mins.isEmpty) {
       println("-1")
     } else {
       println(mins.min - 6)
     }*/
     println(findMin(absSym.withDefaultValue(IndexedSeq[Int]()), n))
   }

}

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

object BearMusketeers {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def main(args: Array[String]) {
     val (n,m) = readTuple
     val abs = for {
       i <- 1 to m
       t = readTuple
     } yield t
     val absSym = abs.flatMap(t => List(t,(t._2,t._1))).groupBy(_._1)
       .mapValues(is => is.map(_._2))
       .filterNot{ _._2.length < 3}
     val mins = for {
       i <- absSym.keys
       j <- absSym(i).filter(_ > i)
       k <- absSym(i).filter(k => k  > j )
       if (absSym.getOrElse(j, IndexedSeq[Int]()) contains k)
     } yield (absSym(i).toSet + absSym(j) + absSym(k)).size
     if (mins.isEmpty) {
       println("-1")
     } else {
       println(mins.min - 3)
     }
   }

}


You are given a permutation $$$p$$$ of $$$n$$$ integers $$$1$$$, $$$2$$$, ..., $$$n$$$ (a permutation is an array where each element from $$$1$$$ to $$$n$$$ occurs exactly once).Let's call some subsegment $$$p[l, r]$$$ of this permutation special if $$$p_l + p_r = \max \limits_{i = l}^{r} p_i$$$. Please calculate the number of special subsegments.

The first line contains one integer $$$n$$$ ($$$3 \le n \le 2 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, ..., $$$p_n$$$ ($$$1 \le p_i \le n$$$). All these integers are pairwise distinct.

Print the number of special subsegments of the given permutation.

NoteSpecial subsegments in the first example are $$$[1, 5]$$$ and $$$[1, 3]$$$.The only special subsegment in the second example is $$$[1, 3]$$$.

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    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 = 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) { i =>
      f(i)
    }
  }
  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
  }
}

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  override def run(): Unit = {
    val N = ni()
    val A = na(N)
    val R = Array.ofDim[Int](N + 1)
    REP(N) { i =>
      R(A(i)) = i
    }
    val t = new SegmentTree(N, 0)(max)
    REP(N) { i =>
      t.update(i, A(i))
    }

    // [l, r)
    def f(l: Int, r: Int): Long = {
      if (r <= l) 0L
      else {
        debug(s"f($l, $r)")
        val mx = t.query(l, r)
        val i = R(mx)
        val llen = i - l
        val rlen = r - i - 1
        val (from, to, opl, opr) = if (llen <= rlen) {
          (l, i - 1, i + 1, r)
        } else {
          (i + 1, r - 1, l, i)
        }

        var res = 0
        TO(from, to) { j =>
          val d = A(i) - A(j)
          debug(s"i:$i j:$j d:$d")
          if (R(d) >= opl && R(d) < opr) res += 1
        }
        res + f(l, i) + f(i + 1, r)
      }
    }
    val ans = f(0, N)
    out.println(ans)
  }

  def solve(): Unit = {
    val t = new Thread(null, this, "solve", 1 << 26)
    t.start()
    t.join()
  }

  /**
    * @param n 個数 最大値じゃないぞ。
    * iの範囲は[0, n - 1]
    *
    * AがIntやLongのときは埋め込んでしまおう
    * type A = Int
    */
  class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      assert(i < n)
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }
}

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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  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()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    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 = 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) { i =>
      f(i)
    }
  }
  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
  }
}

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  override def run(): Unit = {
    val N = ni()
    val A = na(N)
    val R = Array.ofDim[Int](N + 1)
    REP(N) { i =>
      R(A(i)) = i
    }
    val t = new SegmentTree(N, 0)(max)
    REP(N) { i =>
      t.update(i, A(i))
    }

    // [l, r)
    def f(l: Int, r: Int): Long = {
      if (r <= l) 0L
      else {
        debug(s"f($l, $r)")
        val mx = t.query(l, r)
        val i = R(mx)
        val llen = i - l
        val rlen = r - i - 1
        val (from, to) = if (llen <= rlen) {
          (l, i - 1)
        } else {
          (i + 1, r - 1)
        }

        var res = 0
        TO(from, to) { j =>
          val d = A(i) - A(j)
          debug(s"i:$i j:$j d:$d")
          if (R(d) >= l && R(d) < r) res += 1
        }
        res + f(l, i) + f(i + 1, r)
      }
    }
    val ans = f(0, N)
    out.println(ans)
  }

  def solve(): Unit = {
    val t = new Thread(null, this, "solve", 1 << 26)
    t.start()
    t.join()
  }

  /**
    * @param n 個数 最大値じゃないぞ。
    * iの範囲は[0, n - 1]
    *
    * AがIntやLongのときは埋め込んでしまおう
    * type A = Int
    */
  class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      assert(i < n)
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }
}


You are given an integer $$$n$$$ and an array $$$a_1, a_2, \ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i)$$$ is maximized.$$$\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\textbf{MEX}(\{1, 2, 3\}) = 0$$$, $$$\textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3$$$.

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

For each test case print an array $$$b_1, b_2, \ldots, b_n$$$  — the optimal reordering of $$$a_1, a_2, \ldots, a_n$$$, so the sum of $$$\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.

import scala.reflect.ClassTag
import scala.collection.immutable.StringOps
import scala.collection.immutable
object cf1497a {

	def readInt(s: String) = s.toInt
	def readLong(s: String) = s.toLong

  def read[T](conv: (String) => T): T = {
		conv(Console.in.readLine())
	}

	def readArray[T:ClassTag](conv: (String) => T): Array[T] = {
		val line = Console.in.readLine()
		line.split(' ').map(conv(_))
	}

	def solve(arr: Array[Long]): Unit = {
		val s = arr.sorted
		val min = s.foldLeft(0L)( (min, v) => {
			if (v == min) v+1
			else min
		})

		val lessThanUnique = immutable.SortedSet(s.takeWhile(_ < min):_*).toArray
		val reminder = arr.diff(lessThanUnique.toSeq)
		println((lessThanUnique ++ reminder).mkString(" "))
	}

	def main(args: Array[String]): Unit = {
		val cases = read(readInt)
		var nCase = 0
		for (nCase <- 1 to cases) {
			read(readInt)
			val arr = readArray[Long](readLong)
			solve(arr)
    }
  }
}

object P1497A extends App {
  import java.io._
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  val t = readInt
  for (_ <- 0 until t) {
    val n = readInt
    val sortedArray = readInts.sorted
    var isVisited = Map[Int, Boolean]()
    var ascending = List[Int]()
    var rest = List[Int]()
    sortedArray.foreach {
      case i@_ if isVisited getOrElse(i, false) => rest = i +: rest
      case i@_ => {
        ascending = i +: ascending
        isVisited += (i -> true)
      }
    }
    ascending = ascending.reverse
    println((ascending ++ rest).mkString(" "))
  }
}


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

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

    val n=readLine.toInt

    val a=readLine.split(" ").toList.map(_.toInt)

    if(a.count(_==0)==0){
      //NG
      println(-1)
      return
    }

    val sum=a.sum

    val pl=
      if(sum%3==0){
        //OK
        a
      }else{
        val l0=a.filter(_%3==0)
        val l1=a.filter(_%3==sum%3)
        val l2=a.filter(_%3+sum%3==3)

        if(l1.length>=1){
          //OK
          l1.sorted.tail:::l0:::l2
        }else if(l2.length>=2){
          //OK
          l2.sorted.tail.tail:::l0:::l1
        }else{
          l0
        }
      }

    //print
    if(pl.count(_!=0)==0){
      println(0)
    }else{
      println(pl.sorted.reverse.mkString)
    }
  }
}

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

    val n=readLine.toInt

    val a=readLine.split(" ").toList.map(_.toInt)

    if(a.count(_==0)==0){
      //NG
      println(-1)
      return
    }

    val sum=a.sum

    val pl=
      if(sum%3==0){
        //OK
        a
      }else{
        val l0=a.filter(_%3==0)
        val l1=a.filter(_%3==sum%3)
        val l2=a.filter(_%3+sum%3==3)

        if(l1.length>=1){
          //OK
          l1.sorted.tail:::l0:::l2
        }else if(l2.length>=2){
          //OK
          l2.sorted.tail.tail:::l0:::l1
        }else{
          l0
        }
      }

    //print
    if(pl.head==0){
      println(0)
    }else{
      println(pl.sorted.reverse.mkString)
    }
  }
}

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

    val n=readLine.toInt

    val a=readLine.split(" ").toList.map(_.toInt)

    if(a.count(_==0)==0){
      //NG
      println(-1)
      return
    }

    val sum=a.sum

    val pl=
      if(sum%3==0){
        //OK
        a
      }else{
        val l0=a.filter(_%3==0)
        val l1=a.filter(_%3==sum%3)
        val l2=a.filter(_%3+sum%3==3)

        if(l1.length>=1){
          //OK
          l1.sorted.tail:::l0:::l2
        }else if(l2.length>=2){
          //OK
          l2.sorted.tail.tail:::l0:::l1
        }else{
          //0,3,6,9
          if(l0.count(_!=0)==0){
            List(0)
          }else{
            l0
          }
        }
      }

    //print
    println(pl.sorted.reverse.mkString)
  }
}

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

    val n=readLine.toInt

    val a=readLine.split(" ").toList.map(_.toInt)

    if(a.count(_==0)==0){
      //NG
      println(-1)
      return
    }

    val sum=a.sum

    val pl=
      if(a.count(_!=0)==0){
        List(0)
      }else if(sum%3==0){
        //OK
        a
      }else{
        val l0=a.filter(_%3==0)
        val l1=a.filter(_%3==sum%3)
        val l2=a.filter(_%3+sum%3==3)

        if(l1.length>=1){
          //OK
          l1.sorted.tail:::l0:::l2
        }else if(l2.length>=2){
          //OK
          l2.sorted.tail.tail:::l0:::l1
        }else{
          l0
        }
      }

    //print
    println(pl.sorted.reverse.mkString)
  }
}


Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions:  a1 ≤ a2 ≤ ... ≤ an;  a1 ≥ a2 ≥ ... ≥ an. Help Petya find the two required positions to swap or else say that they do not exist.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n non-negative space-separated integers a1, a2, ..., an — the elements of the array that Petya's mother presented him. All integers in the input do not exceed 109.

If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.

NoteIn the first two samples the required pairs obviously don't exist.In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted.

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    val swap=(a:Array[Int], i:Int, j:Int)=>{
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        swap(a,i,j)
        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
        swap(a,i,j)
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    if(a.max==a.min){
        println(-1)
        exit(0)
    }

    val swap=(a:Array[Int], i:Int, j:Int)=>{
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        swap(a,i,j)
        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
        swap(a,i,j)
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase && arr(i)<arr(i-1)) return false
            if(!increase && arr(i)>arr(i-1)) return false
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    /*
    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }
    *
    */
    if(a.max==a.min){
        println(-1)
        exit(0)
    }

    val swap=(a:Array[Int], i:Int, j:Int)=>{
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        swap(a,i,j)
        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
        swap(a,i,j)
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    for(i<-1 until n-1){
        if(i>max && a(i)<a(max) && a(i+1)<=a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i>min && a(i)>a(min) && a(i+1)>=a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    for(i<-1 until n-1){
        if(i!=max && a(i)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i!=min && a(i)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    for(i<-1 until n-1){
        if(i>max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i>min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    if(isSorted(a)){
        println((max+1) +" " +(min+1)); exit(0)
    }
    else{
        for(i<-1 until n-1){
            if(i>max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
            if(i>min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
        }
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

import collection.mutable.Map
import collection.mutable.ArrayBuffer
import java.util.Scanner

object test6 extends App {
    def maxsub(s:String):Int={
        val n=s.length
        val dp=new Array[Int](n)

        for(i<-1 until n){
            var j=i
            while(j>0 && s(i)!=s(dp(j-1))) j=dp(j-1)
            dp(i)=if(j>0) dp(j-1)+1 else 0
        }

        var j=dp(n-1)
        while(n%(n-j)!=0) j=dp(j-1)
        n/(n-j)
    }

    println(maxsub("a"))
    println(maxsub("a"*5))
    println(maxsub("ab"*1000))
    println(maxsub("byebye"))
    println(maxsub("codility"))
    println(maxsub("aabaaaba"))
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    for(i<-1 until n-1){
        if(i!=max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
        if(i!=min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
    }

    println(-1)
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    if(isSorted(a) || max-min==1){
        println((max+1) +" " +(min+1)); exit(0)
    }
    else{
        for(i<-1 until n-1){
            if(i>max && a(i-1)<a(max) && a(i+1)<a(max)) {println((max+1) +" " +(i+1)); exit(0)}
            if(i>min && a(i-1)>a(min) && a(i+1)>a(min)) {println((min+1) + " "+(i+1)); exit(0)}
        }
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}

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

object test4 extends App {
    val n=readInt
    val a=readLine.split(" ").map(_.toInt)

    val max=a.indexOf(a.max)
    val min=a.indexOf(a.min)

    if(n<=2 || max-min==0) {
        println(-1)
        exit(0)
    }

    for(i<-0 until n; j<-i+1 until n if a(i)!=a(j)){
        val tmp=a(i)
        a(i)=a(j)
        a(j)=tmp

        if(!isSorted(a)) {println((i+1)+" "+(j+1));exit(0)}
    }

    println(-1)

    def isSorted(arr:Array[Int]):Boolean={
        val increase=arr.last >= arr.head
        for(i<- 1 until arr.length){
            if(increase){
                if(arr(i)<arr(i-1)) return false
            }
            else{
                if(arr(i)>arr(i-1)) return false
            }
        }
        true
    }
}


Local authorities have heard a lot about combinatorial abilities of Ostap Bender so they decided to ask his help in the question of urbanization. There are n people who plan to move to the cities. The wealth of the i of them is equal to ai. Authorities plan to build two cities, first for n1 people and second for n2 people. Of course, each of n candidates can settle in only one of the cities. Thus, first some subset of candidates of size n1 settle in the first city and then some subset of size n2 is chosen among the remaining candidates and the move to the second city. All other candidates receive an official refuse and go back home.To make the statistic of local region look better in the eyes of their bosses, local authorities decided to pick subsets of candidates in such a way that the sum of arithmetic mean of wealth of people in each of the cities is as large as possible. Arithmetic mean of wealth in one city is the sum of wealth ai among all its residents divided by the number of them (n1 or n2 depending on the city). The division should be done in real numbers without any rounding.Please, help authorities find the optimal way to pick residents for two cities.

The first line of the input contains three integers n, n1 and n2 (1 ≤ n, n1, n2 ≤ 100 000, n1 + n2 ≤ n) — the number of candidates who want to move to the cities, the planned number of residents of the first city and the planned number of residents of the second city. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100 000), the i-th of them is equal to the wealth of the i-th candidate.

Print one real value — the maximum possible sum of arithmetic means of wealth of cities' residents. 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, one of the optimal solutions is to move candidate 1 to the first city and candidate 2 to the second.In the second sample, the optimal solution is to pick candidates 3 and 4 for the first city, and candidate 2 for the second one. Thus we obtain (a3 + a4) / 2 + a2 = (3 + 2) / 2 + 4 = 6.5

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, n1, n2) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).sorted.reverse.take(n1 + n2)
  val min = Math.min(n1, n2)
  val max = Math.max(n1, n2)
  println(a.take(min).foldLeft(0l)(_+_).toDouble / min + a.drop(min).foldLeft(0l)(_+_).toDouble / max)
}

import java.io._
import scala.io.Source

import scala.annotation.tailrec

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val parms = line.split(" ").map(_.toInt)
    val n = parms(0)
    val n1 = parms(1)
    val n2 = parms(2)
    val as = lines.next().split(" ").map(_.toLong)
    val soln = solve(n, n1, n2, as)
    bw.write(soln.toString)
    bw.newLine()
  }

  def solve(n: Int, n1: Int, n2: Int, as: Array[Long]): Double = {
    val nMin = math.min(n1, n2)
    val nMax = math.max(n1, n2)
    val asorted = as.map(- _).sorted
    val (aMin, aRest) = asorted.splitAt(nMin)
    val aMax = aRest.take(nMax)
    val mean1 = - aMin.sum / nMin.toDouble
    val mean2 = - aMax.sum / nMax.toDouble
    val sumOfMeans = mean1 + mean2
    sumOfMeans
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, n1, n2) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).sorted.reverse.take(n1 + n2)
  val min = Math.min(n1, n2)
  val max = Math.max(n1, n2)
  println(a.take(min).sum.toDouble / min + a.drop(min).sum.toDouble / max)

}


While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from $$$a_1, a_2, \ldots, a_n$$$ to $$$-a_1, -a_2, \ldots, -a_n$$$. For some unknown reason, the number of service variables is always an even number.William understands that with his every action he attracts more and more attention from the exchange's security team, so the number of his actions must not exceed $$$5\,000$$$ and after every operation no variable can have an absolute value greater than $$$10^{18}$$$. William can perform actions of two types for two chosen variables with indices $$$i$$$ and $$$j$$$, where $$$i < j$$$:  Perform assignment $$$a_i = a_i + a_j$$$  Perform assignment $$$a_j = a_j - a_i$$$  William wants you to develop a strategy that will get all the internal variables to the desired values.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 20$$$). Description of the test cases follows. The first line of each test case contains a single even integer $$$n$$$ ($$$2 \le n \le 10^3$$$), which is the number of internal variables. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$, which are initial values of internal variables.

For each test case print the answer in the following format: The first line of output must contain the total number of actions $$$k$$$, which the strategy will perform. Note that you do not have to minimize $$$k$$$. The inequality $$$k \le 5\,000$$$ must be satisfied.  Each of the next $$$k$$$ lines must contain actions formatted as "type i j", where "type" is equal to "1" if the strategy needs to perform an assignment of the first type and "2" if the strategy needs to perform an assignment of the second type. Note that $$$i < j$$$ should hold. We can show that an answer always exists.

NoteFor the first sample test case one possible sequence of operations is as follows:  "2 1 2". Values of variables after performing the operation: [1, 0, 1, 1]  "2 1 2". Values of variables after performing the operation: [1, -1, 1, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, 0, 1]  "2 1 3". Values of variables after performing the operation: [1, -1, -1, 1]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, 0]  "2 1 4". Values of variables after performing the operation: [1, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [0, -1, -1, -1]  "1 1 2". Values of variables after performing the operation: [-1, -1, -1, -1] For the second sample test case one possible sequence of operations is as follows:  "2 1 4". Values of variables after performing the operation: [4, 3, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, 1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -1, 1, -2]  "1 2 4". Values of variables after performing the operation: [4, -3, 1, -2]  "1 3 4". Values of variables after performing the operation: [4, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [1, -3, -1, -2]  "1 1 2". Values of variables after performing the operation: [-2, -3, -1, -2]  "1 1 4". Values of variables after performing the operation: [-4, -3, -1, -2]

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine()

    println(n / 2 * 6)

    (1 until (n, 2)).foreach { i =>
      val j = i + 1

      println(s"1 ${i} ${j}")
      println(s"2 ${i} ${j}")
      println(s"1 ${i} ${j}")
      println(s"1 ${i} ${j}")
      println(s"2 ${i} ${j}")
      println(s"1 ${i} ${j}")
    }
  }
}


Recently, Norge found a string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string $$$s$$$. Yes, all $$$\frac{n (n + 1)}{2}$$$ of them!A substring of $$$s$$$ is a non-empty string $$$x = s[a \ldots b] = s_{a} s_{a + 1} \ldots s_{b}$$$ ($$$1 \leq a \leq b \leq n$$$). For example, "auto" and "ton" are substrings of "automaton".Shortly after the start of the exercise, Norge realized that his keyboard was broken, namely, he could use only $$$k$$$ Latin letters $$$c_1, c_2, \ldots, c_k$$$ out of $$$26$$$.After that, Norge became interested in how many substrings of the string $$$s$$$ he could still type using his broken keyboard. Help him to find this number.

The first line contains two space-separated integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$1 \leq k \leq 26$$$) — the length of the string $$$s$$$ and the number of Latin letters still available on the keyboard. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters. The third line contains $$$k$$$ space-separated distinct lowercase Latin letters $$$c_1, c_2, \ldots, c_k$$$ — the letters still available on the keyboard.

Print a single number — the number of substrings of $$$s$$$ that can be typed using only available letters $$$c_1, c_2, \ldots, c_k$$$.

object CF605C extends App {

  import scala.io.StdIn

  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val string = StdIn.readLine
  val available = StdIn.readLine.split(' ').map(_.toCharArray.head)
  if (k == 26) {
    println((n.toLong*(n.toLong+1))/2)
  } else {
    val notAvailable = "abcdefghijklmnopqrstuvwxyz".toCharArray.filter(!available.contains(_))
    val split = string.split(notAvailable)
    println(split.map(s => (s.length.toLong*(s.length.toLong+1))/2).sum)
  }
}

object CF605C extends App {

  import scala.io.StdIn

  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val string = StdIn.readLine
  val available = StdIn.readLine.split(' ').map(_.toCharArray.head)
  val notAvailable = "abcdefghijklmnopqrstuvwxyz".toCharArray.filter(!available.contains(_))
  val split = if (notAvailable.isEmpty) List(string).toArray else string.split(notAvailable)
  println(split.map(s => (s.length*(s.length+1))/2).sum)
}

object CF605C extends App {

  import scala.io.StdIn

  val Array(n, k) = StdIn.readLine.split(' ').map(_.toInt)
  val string = StdIn.readLine
  val available = StdIn.readLine.split(' ').map(_.toCharArray.head)
  if (k == 26) {
    println((n*(n+1))/2)
  } else {
    val notAvailable = "abcdefghijklmnopqrstuvwxyz".toCharArray.filter(!available.contains(_))
    val split = string.split(notAvailable)
    println(split.map(s => (s.length*(s.length+1))/2).sum)
  }
}


Toad Pimple has an array of integers $$$a_1, a_2, \ldots, a_n$$$.We say that $$$y$$$ is reachable from $$$x$$$ if $$$x<y$$$ and there exists an integer array $$$p$$$ such that $$$x = p_1 < p_2 < \ldots < p_k=y$$$, and $$$a_{p_i}\, \&\, a_{p_{i+1}} > 0$$$ for all integers $$$i$$$ such that $$$1 \leq i < k$$$.Here $$$\&$$$ denotes the bitwise AND operation.You are given $$$q$$$ pairs of indices, check reachability for each of them.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$2 \leq n \leq 300\,000$$$, $$$1 \leq q \leq 300\,000$$$) — the number of integers in the array and the number of queries you need to answer. The second line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i \leq 300\,000$$$) — the given array. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th of them contains two space-separated integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i < y_i \leq n$$$). You need to check if $$$y_i$$$ is reachable from $$$x_i$$$.

Output $$$q$$$ lines. In the $$$i$$$-th of them print "Shi" if $$$y_i$$$ is reachable from $$$x_i$$$, otherwise, print "Fou".

NoteIn the first example, $$$a_3 = 0$$$. You can't reach it, because AND with it is always zero. $$$a_2\, \&\, a_4 > 0$$$, so $$$4$$$ is reachable from $$$2$$$, and to go from $$$1$$$ to $$$4$$$ you can use $$$p = [1, 2, 4]$$$.

object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  @inline def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    var b = 0
    while (b < BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          var b2 = 0
          while (b2 < BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)
            b2 += 1
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      }
      b += 1
    }

  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    var b = 0
    while (b < BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true
      b += 1
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}

object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    for (b <- 0 until BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          for (b2 <- 0 until BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2) : @inline
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      } : @inline
    }
    for (b2 <- 0 until BITS) {
      if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2) : @inline
    }
  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    for (b <- 0 until BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true : @inline
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}

object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    for (b <- 0 until BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          for (b2 <- 0 until BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      }
    }
    for (b2 <- 0 until BITS) {
      if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2)
    }
  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    for (b <- 0 until BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}

object C extends App {

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

  val Array(n, q) = readInts(2)
  val as = readInts(n)

  val BITS = 20
  @inline def bit(i: Int) = 1 << i

  val minReachableWith = Array.fill(BITS){ n + 1 }
  for (b <- 0 until BITS) {
    if ((as.last & bit(b)) > 0) minReachableWith(b) = n - 1
  }

  val minReachable = Array.fill(n, BITS){ n + 1 }

  for (i <- n - 2 to 0 by -1) {
    val a = as(i)
    var b = 0
    while (b < BITS) {
      if ((a & bit(b)) > 0) {
        if (minReachableWith(b) < n) {
          val j = minReachableWith(b)
          var b2 = 0
          while (b2 < BITS) {
            if (minReachable(j)(b2) < minReachable(i)(b2)) minReachable(i)(b2) = minReachable(j)(b2)
            b2 += 1
          }
        }
        minReachableWith(b) = i
        minReachable(i)(b) = i
      }
      b += 1
    }
    var b2 = 0
    while (b2 < BITS) {
      if (minReachable(i)(b2) < minReachableWith(b2)) minReachableWith(b2) = minReachable(i)(b2)
      b2 += 1
    }
  }

  val reachable = Array.fill(q)(false)
  for (i <- 0 until q) {
    val Array(l0, r0) = readInts(2)
    val l = l0 - 1
    val r = r0 - 1
    var b = 0
    while (b < BITS) {
      if ((as(r) & bit(b)) > 0 && minReachable(l)(b) <= r) reachable(i) = true
      b += 1
    }
  }

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

  println(reachable.map(if (_) "Shi" else "Fou").mkString("\n"))

  Console.flush
}


Vasya has started watching football games. He has learned that for some fouls the players receive yellow cards, and for some fouls they receive red cards. A player who receives the second yellow card automatically receives a red card.Vasya is watching a recorded football match now and makes notes of all the fouls that he would give a card for. Help Vasya determine all the moments in time when players would be given red cards if Vasya were the judge. For each player, Vasya wants to know only the first moment of time when he would receive a red card from Vasya.

The first line contains the name of the team playing at home. The second line contains the name of the team playing away. Both lines are not empty. The lengths of both lines do not exceed 20. Each line contains only of large English letters. The names of the teams are distinct. Next follows number n (1 ≤ n ≤ 90) — the number of fouls.  Each of the following n lines contains information about a foul in the following form:    first goes number t (1 ≤ t ≤ 90) — the minute when the foul occurs;  then goes letter "h" or letter "a" — if the letter is "h", then the card was given to a home team player, otherwise the card was given to an away team player;  then goes the player's number m (1 ≤ m ≤ 99);  then goes letter "y" or letter "r" — if the letter is "y", that means that the yellow card was given, otherwise the red card was given.  The players from different teams can have the same number. The players within one team have distinct numbers. The fouls go chronologically, no two fouls happened at the same minute.

For each event when a player received his first red card in a chronological order print a string containing the following information:   The name of the team to which the player belongs;  the player's number in his team;  the minute when he received the card.  If no player received a card, then you do not need to print anything. It is possible case that the program will not print anything to the output (if there were no red cards).

import java.util.StringTokenizer
import scala.collection.mutable.Map

object _493A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val home = next
  val away = next
  val homeYellow = Map[Int, Int]()
  val awayYellow = Map[Int, Int]()
  val homeRed = Map[Int, Int]()
  val awayRed = Map[Int, Int]()

  val a = (1 to next.toInt).map(i => (1 to 4).map(j => next)).toArray.sortBy(arr => arr(0).toInt)
  for (event <- a) {
    val t = event(0).toInt
    val yellow = if (event(1) == "h") homeYellow else awayYellow
    val red = if(event(1) == "h") homeRed else awayRed
    val player = event(2).toInt
    if (event(3) == "y") {
      if (yellow.contains(player)) {
        if (red.contains(player)) red(player) = red(player) min t else red += ((player, t))
      }
      else yellow += ((player, t))
    } else {
      if (red.contains(player)) red(player) = red(player) min t
      else red += ((player, t))
    }
  }

  val cb = homeRed.toArray.map(i => (home, i._1, i._2))
  val wb = awayRed.toArray.map(i => (away, i._1, i._2))
  (cb ++ wb).sortBy(i => i._3).foreach(i => println("%s %d %d".format(i._1, i._2, i._3)))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val team1 = in.next()
  val team2 = in.next()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next().split(" "))
  var t1_1 = Set.empty[Int]
  var t1_2 = Map.empty[Int, Int]
  var t2_1 = Set.empty[Int]
  var t2_2 = Map.empty[Int, Int]
  data.foreach {
    case Array(time, "h", number, color) if t1_2.contains(number.toInt) =>
    case Array(time, "h", number, "r") => t1_2 += (number.toInt -> time.toInt)
    case Array(time, "h", number, "y") if t1_1.contains(number.toInt) => t1_2 += (number.toInt -> time.toInt)
    case Array(time, "h", number, "y") => t1_1 += number.toInt
    case Array(time, "a", number, color) if t2_2.contains(number.toInt) =>
    case Array(time, "a", number, "r") => t2_2 += (number.toInt -> time.toInt)
    case Array(time, "a", number, "y") if t2_1.contains(number.toInt) => t2_2 += (number.toInt -> time.toInt)
    case Array(time, "a", number, "y") => t2_1 += number.toInt
  }
  println((t1_2.map {
    case(number, time) => (time, team1, number)
  }.toList ::: t2_2.map {
    case(number, time) => (time, team2, number)
  }.toList).sorted.map(t => s"${t._2} ${t._3} ${t._1}").mkString("\n"))

}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](100)(0)
        val home: Array[Int] = Array.fill[Int](100)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(curteam(r(2).toInt) < 2) {
                if(r(3) == "y") curteam(r(2).toInt) += 1
                else curteam(r(2).toInt) += 2
                if(curteam(r(2).toInt) >= 2) {
                    println(curname + " " + r(2).toInt + " " + r(0).toInt)
                }
            }
        }
    }
}

import scala.collection.immutable.IndexedSeq

object ProblemARunner extends App {
  ProblemA.run()
}
object ProblemA {
  import scala.io.StdIn._

  private def relevantFouls(fouls: IndexedSeq[Foul]) = {
    val byPlayer = fouls.groupBy(foul => (foul.team, foul.player))
    byPlayer.values.toSeq.collect { case foulsByPlayer if foulsByPlayer.map(_.cards).sum >= 2 =>
        if(foulsByPlayer(0).cards == 2)
          foulsByPlayer(0)
        else
          foulsByPlayer(1)
    }.sortBy(_.time)
  }

  def run(): Unit = {
    val oneTeam = readTeamName()
    val otherTeam = readTeamName()
    val fouls = 1 to readFouls() map { _ =>
      Foul.read(oneTeam, otherTeam)
    }
    val relevant = relevantFouls(fouls)
    printFouls(relevant)
  }

  private def printFouls(fouls: Seq[Foul]) = {
    fouls.foreach(_.toOutput())
  }
  private def readTeamName(): String = {
    readLine()
  }
  private def readFouls(): Int = {
    readInt()
  }
  private case class Foul(time: Int, team: String, player: Int, cards: Int) {
    def toOutput() = {
      println(s"$team $player $time")
    }
  }
  private object Foul {
    def read(oneName: String, otherName: String): Foul = {
      val line = readLine().split(' ')
      val time = line(0).toInt
      val team = line(1) match {
        case "h" => oneName
        case "a" => otherName
      }
      val player = line(2).toInt
      val cards = line(3) match {
        case "y" => 1
        case "r" => 2
      }
      Foul(time, team, player, cards)
    }
  }

}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

import scala.annotation.tailrec

object A_VasyaAndFootbal {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val homeTeam = scanner.next()
    val awayTeam = scanner.next()

    val n = scanner.nextInt()

    val input = for (i <- 1 to n) yield {
      val time = scanner.nextInt()
      val teamId = scanner.next()
      val playerId = scanner.nextInt()
      val cardType = scanner.next()

      val teamName = teamId match {
        case "a" => awayTeam
        case "h" => homeTeam
      }

      (time, teamName, playerId, cardType)
    }

    //result (team, playerId, time, cardsCount)
    @tailrec def process (l : List[(Int, String, Int, String)], acc : Map[String, (String, Int, Int, Int)] = Map.empty) : Map[String, (String, Int, Int, Int)] = {
      l match {
        case x :: tail => {
          val playerId = x._2 + "_" + x._3
          val cardPoints = x._4 match {
            case "y" => 1
            case "r" => 2
            case _ => 0
          }

          val cardsCount = if (acc.contains(playerId)) acc(playerId)._4 else 0

          if (cardsCount >= 2) {
            process(tail, acc)
          } else {
            process(tail, acc + (playerId -> (x._2, x._3, x._1, cardsCount + cardPoints)))
          }
        }
        case Nil => acc
      }
    }

    val result = process(input.toList).filter(x => x._2._4 >= 2).toList.map(_._2).sortBy(x => x._3)

    for (x <- result) {
      out.println(s"${x._1} ${x._2} ${x._3}")
    }
  }
}

object Main extends App {

  val teamH = readLine
  val teamA = readLine

  def rename(team: String) = if(team == "h") teamH else teamA

  val games = readLine.toInt
  (1 to games).foldLeft(Map[(String, String), String]()) {
    case (acc, _) =>
      val Array(time, team, num, card) = readLine.split(" ")
      acc.get((team, num)) match {
        case None =>
          if(card == "r") println("%s %s %s".format(rename(team), num, time)) else ()
          acc + ((team, num) -> card)
        case Some("r") =>
          acc
        case Some("y") =>
          println("%s %s %s".format(rename(team), num, time))
          acc + ((team, num) -> "r")
      }
  }

}

import java.util.StringTokenizer
import scala.collection.mutable.Map

object _493A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val home = next
  val away = next
  val homeYellow = Map[Int, Int]()
  val awayYellow = Map[Int, Int]()
  val homeRed = Map[Int, Int]()
  val awayRed = Map[Int, Int]()

  val a = (1 to next.toInt).map(i => (1 to 4).map(j => next)).toArray.sortBy(arr => arr(0).toInt)
  for (event <- a) {
    val t = event(0).toInt
    val yellow = if (event(1) == "h") homeYellow else awayYellow
    val red = if(event(1) == "h") homeRed else awayRed
    val player = event(2).toInt
    if (event(3) == "y") {
      if (yellow.contains(player)) {
        yellow(player) = yellow(player) max t
        if (red.contains(player)) red(player) = red(player) min t else red += ((player, yellow(player)))
      }
      else yellow += ((player, t))
    } else {
      if (red.contains(player)) red(player) = red(player) min t
      else red += ((player, t))
    }
  }

  homeRed.toArray.sortBy(pair => pair._1).foreach(pair => println("%s %d %d".format(home, pair._1, pair._2)))
  awayRed.toArray.sortBy(pair => pair._1).foreach(pair => println("%s %d %d".format(away, pair._1, pair._2)))
}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](99)(0)
        val home: Array[Int] = Array.fill[Int](99)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(r(3) == "y") curteam(r(2).toInt) += 1
            if(r(3) == "r" || curteam(r(2).toInt) == 2) {
                println(curname + " " + r(2).toInt + " " + r(0).toInt)
            }
        }
    }
}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](100)(0)
        val home: Array[Int] = Array.fill[Int](100)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(r(3) == "y") curteam(r(2).toInt) += 1
            else curteam(r(2).toInt) += 2
            if(r(3) == "r" || curteam(r(2).toInt) == 2) {
                println(curname + " " + r(2).toInt + " " + r(0).toInt)
            }
        }
    }
}

object Main {
    def main(args: Array[String]) {
        val homename = io.StdIn.readLine()
        val guestname = io.StdIn.readLine()
        val fault_cnt = io.StdIn.readInt()
        val recs: Array[Array[String]] = (1 to fault_cnt).map{ dump =>
            io.StdIn.readLine().split(" ")
        }.toArray
        val guest: Array[Int] = Array.fill[Int](100)(0)
        val home: Array[Int] = Array.fill[Int](100)(0)
        recs.foreach{ r =>
            val curteam = if(r(1) == "a") guest else home
            val curname = if(r(1) == "a") guestname else homename
            if(r(3) == "y") curteam(r(2).toInt) += 1
            if(r(3) == "r" || curteam(r(2).toInt) == 2) {
                println(curname + " " + r(2).toInt + " " + r(0).toInt)
            }
        }
    }
}

import scala.collection.immutable.IndexedSeq

object ProblemARunner extends App {
  ProblemA.run()
}
object ProblemA {
  import scala.io.StdIn._

  private def relevantFouls(fouls: IndexedSeq[Foul]) = {
    val byPlayer = fouls.groupBy(foul => (foul.team, foul.player))
    byPlayer.values.toSeq.collect { case foulsByPlayer if foulsByPlayer.map(_.cards).sum >= 2 =>
        foulsByPlayer.maxBy(_.time)
    }.sortBy(_.time)
  }

  def run(): Unit = {
    val oneTeam = readTeamName()
    val otherTeam = readTeamName()
    val fouls = 1 to readFouls() map { _ =>
      Foul.read(oneTeam, otherTeam)
    }
    val relevant = relevantFouls(fouls)
    printFouls(relevant)
  }

  private def printFouls(fouls: Seq[Foul]) = {
    fouls.foreach(_.toOutput())
  }
  private def readTeamName(): String = {
    readLine()
  }
  private def readFouls(): Int = {
    readInt()
  }
  private case class Foul(time: Int, team: String, player: Int, cards: Int) {
    def toOutput() = {
      println(s"$team $player $time")
    }
  }
  private object Foul {
    def read(oneName: String, otherName: String): Foul = {
      val line = readLine().split(' ')
      val time = line(0).toInt
      val team = line(1) match {
        case "h" => oneName
        case "a" => otherName
      }
      val player = line(2).toInt
      val cards = line(3) match {
        case "y" => 1
        case "r" => 2
      }
      Foul(time, team, player, cards)
    }
  }

}


Как известно, в теплую погоду многие жители крупных городов пользуются сервисами городского велопроката. Вот и Аркадий сегодня будет добираться от школы до дома, используя городские велосипеды.Школа и дом находятся на одной прямой улице, кроме того, на той же улице есть n точек, где можно взять велосипед в прокат или сдать его. Первый велопрокат находится в точке x1 километров вдоль улицы, второй — в точке x2 и так далее, n-й велопрокат находится в точке xn. Школа Аркадия находится в точке x1 (то есть там же, где и первый велопрокат), а дом — в точке xn (то есть там же, где и n-й велопрокат). Известно, что xi < xi + 1 для всех 1 ≤ i < n.Согласно правилам пользования велопроката, Аркадий может брать велосипед в прокат только на ограниченное время, после этого он должен обязательно вернуть его в одной из точек велопроката, однако, он тут же может взять новый велосипед, и отсчет времени пойдет заново. Аркадий может брать не более одного велосипеда в прокат одновременно. Если Аркадий решает взять велосипед в какой-то точке проката, то он сдаёт тот велосипед, на котором он до него доехал, берёт ровно один новый велосипед и продолжает на нём своё движение.За отведенное время, независимо от выбранного велосипеда, Аркадий успевает проехать не больше k километров вдоль улицы. Определите, сможет ли Аркадий доехать на велосипедах от школы до дома, и если да, то какое минимальное число раз ему необходимо будет взять велосипед в прокат, включая первый велосипед? Учтите, что Аркадий не намерен сегодня ходить пешком.

В первой строке следуют два целых числа n и k (2 ≤ n ≤ 1 000, 1 ≤ k ≤ 100 000) — количество велопрокатов и максимальное расстояние, которое Аркадий может проехать на одном велосипеде. В следующей строке следует последовательность целых чисел x1, x2, ..., xn (0 ≤ x1 < x2 < ... < xn ≤ 100 000) — координаты точек, в которых находятся велопрокаты. Гарантируется, что координаты велопрокатов заданы в порядке возрастания.

Если Аркадий не сможет добраться от школы до дома только на велосипедах, выведите -1. В противном случае, выведите минимальное количество велосипедов, которые Аркадию нужно взять в точках проката.

ПримечаниеВ первом примере Аркадий должен взять первый велосипед в первом велопрокате и доехать на нём до второго велопроката. Во втором велопрокате он должен взять новый велосипед, на котором он сможет добраться до четвертого велопроката, рядом с которым и находится его дом. Поэтому Аркадию нужно всего два велосипеда, чтобы добраться от школы до дома.Во втором примере всего два велопроката, расстояние между которыми 10. Но максимальное расстояние, которое можно проехать на одном велосипеде, равно 9. Поэтому Аркадий не сможет добраться от школы до дома только на велосипедах.

  object CF928A extends App {
  val sc = new java.util.Scanner(System.in)
  val n: Int = sc.nextInt()
  val k: Int = sc.nextInt()
  val checkPoints: List[Int] = (1 to n).toList.foldLeft(List.empty[Int]){case (list, _) => list :+ sc.nextInt()}
  def shortWay(checkPoints: List[Int], result: Int): Int = {
    def nextCheckPoint(checkPoints: List[Int], kmRemaining: Int): List[Int] = if (checkPoints.tail.nonEmpty) {
      val a = checkPoints.head + kmRemaining - checkPoints.tail.head
      if (a >= 0){
        nextCheckPoint(checkPoints.tail, a)
      } else {
        checkPoints
      }
    } else checkPoints
    if (checkPoints.tail.nonEmpty) {
      val remainingList = nextCheckPoint(checkPoints, k)
      if (remainingList.tail.nonEmpty) {
        if (remainingList.tail.head - remainingList.head > k || remainingList == checkPoints) {
          -1
        } else {
          shortWay(remainingList, result + 1)
        }
      } else result
    } else result
  }
  println(shortWay(checkPoints, 1))
  }


Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array $$$a$$$ with elements $$$a_1, a_2, \ldots, a_{2k-1}$$$, is the array $$$b$$$ with elements $$$b_1, b_2, \ldots, b_{k}$$$ such that $$$b_i$$$ is equal to the median of $$$a_1, a_2, \ldots, a_{2i-1}$$$ for all $$$i$$$. Omkar has found an array $$$b$$$ of size $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$-10^9 \leq b_i \leq 10^9$$$). Given this array $$$b$$$, Ray wants to test Omkar's claim and see if $$$b$$$ actually is an OmkArray of some array $$$a$$$. Can you help Ray?The median of a set of numbers $$$a_1, a_2, \ldots, a_{2i-1}$$$ is the number $$$c_{i}$$$ where $$$c_{1}, c_{2}, \ldots, c_{2i-1}$$$ represents $$$a_1, a_2, \ldots, a_{2i-1}$$$ sorted in nondecreasing order.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$b$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \leq b_i \leq 10^9$$$) — the elements of $$$b$$$. It is guaranteed the sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one line containing YES if there exists an array $$$a$$$ such that $$$b_i$$$ is the median of $$$a_1, a_2, \dots, a_{2i-1}$$$ for all $$$i$$$, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).

NoteIn the second case of the first sample, the array $$$[4]$$$ will generate an OmkArray of $$$[4]$$$, as the median of the first element is $$$4$$$.In the fourth case of the first sample, the array $$$[3, 2, 5]$$$ will generate an OmkArray of $$$[3, 3]$$$, as the median of $$$3$$$ is $$$3$$$ and the median of $$$2, 3, 5$$$ is $$$3$$$.In the fifth case of the first sample, the array $$$[2, 1, 0, 3, 4, 4, 3]$$$ will generate an OmkArray of $$$[2, 1, 2, 3]$$$ as   the median of $$$2$$$ is $$$2$$$  the median of $$$0, 1, 2$$$ is $$$1$$$  the median of $$$0, 1, 2, 3, 4$$$ is $$$2$$$  and the median of $$$0, 1, 2, 3, 3, 4, 4$$$ is $$$3$$$. In the second case of the second sample, the array $$$[1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]$$$ will generate an OmkArray of $$$[1, 1, 3, 1, 0, -2, -1]$$$, as   the median of $$$1$$$ is $$$1$$$  the median of $$$0, 1, 4$$$ is $$$1$$$  the median of $$$0, 1, 3, 4, 5$$$ is $$$3$$$  the median of $$$-2, -2, 0, 1, 3, 4, 5$$$ is $$$1$$$  the median of $$$-4, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$0$$$  the median of $$$-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$-2$$$  and the median of $$$-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5$$$ is $$$-1$$$ For all cases where the answer is NO, it can be proven that it is impossible to find an array $$$a$$$ such that $$$b$$$ is the OmkArray of $$$a$$$.

//package codeforces

import java.util.TreeSet

object P1536D extends App {

  val cases = lines.next().toInt
  (0 until cases).foreach { _ =>
    lines.next()
    val xs = lines.next().split(" ").map(_.toInt)
    if (solve(xs)) println("YES")
    else println("NO")
  }

  lazy val lines = if (System.getProperty("user.dir").contains("algosscala")) {
    """5
      |4
      |6 2 1 3
      |1
      |4
      |5
      |4 -8 5 6 -7
      |2
      |3 3
      |4
      |2 1 2 3
      |""".stripMargin.linesIterator
  } else {
    io.Source.stdin.getLines()
  }

  def solve(xs: Array[Int]) = {
    val s = new TreeSet[Int]()
    s.add(xs.head)
    var prev = xs.head
    !xs.tail.exists { x =>
      val lowerLimit = Option(s.floor(prev - 1)).getOrElse(Int.MinValue)
      val higherLimit = Option(s.ceiling(prev + 1)).getOrElse(Int.MaxValue)
      if (lowerLimit <= x && x <= higherLimit) {
        s.add(x)
        prev = x
        false
      } else {
        true
      }
    }
  }

}

//package codeforces

object Testing extends  App {
  lazy val lines = if (System.getProperty("user.dir").contains("algosscala")) {
    """2
      |6 4
      |1 2
      |6 7
      |9 12
      |24 24
      |24 25
      |41 50
      |14 24 24 24 24 4
      |1 1
      |42 42
      |24
      |""".stripMargin.linesIterator
  } else {
    io.Source.stdin.getLines()
  }

}