There are $$$n$$$ programmers that you want to split into several non-empty teams. The skill of the $$$i$$$-th programmer is $$$a_i$$$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $$$x$$$.Each programmer should belong to at most one team. Some programmers may be left without a team.Calculate the maximum number of teams that you can assemble.

The first line contains the integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5; 1 \le x \le 10^9$$$) — the number of programmers and the restriction of team skill respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th programmer. The sum of $$$n$$$ over all inputs does not exceed $$$10^5$$$.

For each test case print one integer — the maximum number of teams that you can assemble.

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

    for (_ <- 1 to nextInt) {
      val n, x = nextInt
      val as = nextLongs(n).sorted.reverse
      var res = 0
      var cnt = 0
      for (a <- as) {
        cnt += 1
        if (a * cnt >= x) {
          cnt = 0
          res += 1
        }
      }

      out.println(res)
    }

    out.flush()
  }

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

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, x) = readLine().split(" ").map(_.toInt)
    val an          = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

    val m = an.lastIndexWhere(_ >= x) match {
      case -1 => if (an.head >= x) n else 0
      case i  => i + 1
    }

    val l = an.drop(m).foldLeft((0, 0)) {
      case ((l, r), a) =>
        if ((r + 1) * a >= x) (l + 1, 0)
        else (l, r + 1)
    }._1

    val ans = m + l

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, x) = readLine().split(" ").map(_.toInt)
    val an          = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

    val ans = an
      .foldLeft((0, 0)) {
        case ((count, remains), a) =>
          if (a * (remains + 1) >= x) (count + 1, 0)
          else (count, remains + 1)
      }
      ._1

    println(ans)
  }
}

import scala.io.StdIn._

object C extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val Array(n, x) = readLine().split(" ").map(_.toInt)
    val A           = readLine().split(" ").map(_.toInt).sorted

    var teams   = 0
    var current = 0
    for {
      i <- A.length - 1 to 0 by -1
    } {
      current += 1
      if (A(i) * current >= x) {
        teams += 1
        current = 0
      }
    }
    println(teams)
  }
}

import java.util

object ProblemC extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()
    val k = in.nextInt()
    val a = new Array[Int](n)
    for (i <- a.indices) {
      a(i) = in.nextInt()
    }

    util.Arrays.sort(a)

    var result = 0

    var i = a.length
    var count: Long = 0
    while (i > 0) {
      i = i - 1
      count = count + 1
      if (count * a(i) >= k) {
        result = result + 1
        count = 0
      }
    }

    println(result)
  }
}


Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length $$$k$$$ is vowelly if there are positive integers $$$n$$$ and $$$m$$$ such that $$$n\cdot m = k$$$ and when the word is written by using $$$n$$$ rows and $$$m$$$ columns (the first row is filled first, then the second and so on, with each row filled from left to right), every vowel of the English alphabet appears at least once in every row and every column.You are given an integer $$$k$$$ and you must either print a vowelly word of length $$$k$$$ or print $$$-1$$$ if no such word exists.In this problem the vowels of the English alphabet are 'a', 'e', 'i', 'o' ,'u'.

Input consists of a single line containing the integer $$$k$$$ ($$$1\leq k \leq 10^4$$$) — the required length.

The output must consist of a single line, consisting of a vowelly word of length $$$k$$$ consisting of lowercase English letters if it exists or $$$-1$$$ if it does not. If there are multiple possible words, you may output any of them.

NoteIn the second example, the word "agoeuioaeiruuimaeoieauoweouoiaouimae" can be arranged into the following $$$6 \times 6$$$ grid:  It is easy to verify that every row and every column contain all the vowels.

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) {
  import sc._
  import Main._
  import java.util.Arrays.sort

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

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

  def solve(): Unit = {
    val N = ni()

    val V = "aiueo"

    REP(math.sqrt(N).toInt, 1) { n =>
      if (N % n == 0) {
        val m = N / n
        if (n >= 5 && m >= 5) {
          REP(n) { i =>
            REP(m) { j =>
              out.print(V((i + j) % 5))
            }
          }
          out.println()

          return
        }
      }
    }

    out.println(-1)
  }
}

import scala.math.sqrt
import scala.util.control.Breaks._

object Main extends App {

	def isPrimeNumber (n : Double) : Boolean = {
		var max : Int = sqrt(n).toInt

		for ( i <- 2 to max ) {
			if ( n%i == 0 ) {
				return false
			}
		}

		return true
	}

	var m = Console.readLine
	var n : Int = m.toInt
	var arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')

	if ( isPrimeNumber(n.toDouble) || n < 25 ) {
		println(-1)
		sys.exit(0)
	}

	var row : Int = 5
	var col : Int = 0
	var max : Int = n/5 + 1

	while ( row < max && col == 0) {
		if ( n%row == 0 ) {
			col = n/row - 1
			row -= 1
		} else {
			row += 1
		}
	}

	if ( col < 4 ) {
		println(-1)
		sys.exit(0)
	}

	for ( i <- 0 to row ) {
		for ( j <- 0 to col) {
			print(arrChar((i+j) % 5))
		}
	}

	println()

}

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

  override def apply(io: IO): io.type = {
    val k = io.read[Int]
    val vowels = "aeiou"

    val ans = (vowels.length to k).find(i => k%i == 0 && k/i >= vowels.length) match {
      case None => "-1"
      case Some(n) =>
        val m = k/n
        Vector.tabulate(n, m)((i, j) => vowels((i + j)%vowels.length)).map(_.mkString).mkString
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

import scala.math.sqrt
import scala.util.control.Breaks._

object Main extends App {

	def isPrimeNumber (n : Double) : Boolean = {
		var max : Int = sqrt(n).toInt

		for ( i <- 2 to max ) {
			if ( n%i == 0 ) {
				return false
			}
		}

		return true
	}

	var m = Console.readLine
	var n : Int = m.toInt
	var arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')

	if ( isPrimeNumber(n.toDouble) || n < 25 ) {
		println(-1)
		sys.exit(0)
	}

	var row : Int = 5
	var col : Int = 0

	while ( col == 0) {
		if ( n%row == 0 ) {
			col = n/row - 1
			row -= 1
		} else {
			row += 1
		}
	}

	for ( i <- 0 to row ) {
		for ( j <- 0 to col) {
			print(arrChar((i+j) % 5))
		}
	}

	println()

}

import scala.math.sqrt
import scala.util.control.Breaks._

object Main extends App {

	def isPrimeNumber (n : Double) : Boolean = {
		var max : Int = sqrt(n).toInt

		for ( i <- 2 to max ) {
			if ( n%i == 0 ) {
				return false
			}
		}

		return true
	}

	var m = Console.readLine
	var n : Int = m.toInt
	var arrChar : Array[Char] = Array('a', 'e', 'i', 'o', 'u')

	if ( isPrimeNumber(n.toDouble) || n < 25 ) {
		println(-1)
		sys.exit(0)
	}

	var row : Int = 5
	var col : Int = 0

	while ( col == 0) {
		if ( n%row == 0 ) {
			col = n/row - 1
			row -= 1
		} else {
			row += 1
		}
	}

	for ( i <- 0 to row ) {
		for ( j <- 0 to col) {
			if ( i < 5 && j < 5) {
				print(arrChar((i+j) % 5))
			} else {
				print('b')
			}
		}
	}

	println()

}

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

  override def apply(io: IO): io.type = {
    val k = io.read[Int]
    val vowels = "aeiou"

    val ans = (vowels.length to k).find(i => k%i == 0 && k/i >= vowels.length) match {
      case None => "-1"
      case _ => Vector.tabulate(k)(i => vowels(i%vowels.length)).mkString
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.

The first line contains integer n (2 ≤ n ≤ 100) — amount of soldiers. Then follow the heights of the soldiers in their order in the circle — n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 1000). The soldier heights are given in clockwise or counterclockwise direction.

Output two integers — indexes of neighbouring soldiers, who should form a reconnaissance unit. If there are many optimum solutions, output any of them. Remember, that the soldiers stand in a circle.

object P034A extends App {
  val n = readInt
  val a = readLine.split(' ').map(_.toInt)
  val next = (x: Int) => (x+1) % n
  val b = for (i <- 0 to n-1) yield math.abs(a(i)-a(next(i)))
  val pos = b.indexOf(b min)
  printf("%d %d\n", pos+1, next(pos)+1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val res = data.sliding(2).map(t => Math.abs(t.last - t.head)).zipWithIndex.min
  val firstLast = Math.abs(data.head - data.last)
  if (firstLast > res._1)
    println(s"${res._2 + 1} ${res._2 + 2}")
  else
    println(s"$n 1")
}

object A34 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val heights = readInts(n)
    var x = 0
    var y = heights.length-1
    var max = math.abs(heights(y)-heights(x))
    for(i <- 0 until heights.length-1) {
      if(math.abs(heights(i)-heights(i+1)) < max) {
        x = i
        y = i + 1
        max = math.abs(heights(i)-heights(i+1))
      }
    }
    out.println(s"${x+1} ${y+1}")
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

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

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  val d: PartialFunction[List[Int], Int] = { case List(i, j) => (A(i) - A(j)).abs }
  val res = List.tabulate(N + 1)(_ % N).sliding(2).toList.sortBy(d).head.map(_ + 1)

  out.println(res.mkString(" "))
  out.close
}

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var n = readInt;
    var arr = readLine.split(" ").zipWithIndex;
    var a = arr.flatMap(x => for (y <- arr if (math.abs(x._2 - y._2) == 1 || math.abs(x._2 - y._2) == n - 1)) yield (x, y));
    var min = a.reduceLeft((a, b) => if (math.abs(a._1._1.toInt - a._2._1.toInt) < math.abs(b._1._1.toInt - b._2._1.toInt)) a else b);
    println((min._1._2 + 1) + " " + (min._2._2 + 1));
  }

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val a1 = a.zipWithIndex
    val a2 = (a1 ++ Seq(a1(0))).sliding(2).map(s => ((s(0)._1 - s(1)._1).abs, (s(0)._2, s(1)._2)))
    val t = a2.toList.sortBy(_._1).apply(0)
    println((t._2._1 + 1) + " " + (t._2._2 + 1))
  }
}


You are given an array $$$a$$$ of length $$$n$$$.You are also given a set of distinct positions $$$p_1, p_2, \dots, p_m$$$, where $$$1 \le p_i < n$$$. The position $$$p_i$$$ means that you can swap elements $$$a[p_i]$$$ and $$$a[p_i + 1]$$$. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$) using only allowed swaps.For example, if $$$a = [3, 2, 1]$$$ and $$$p = [1, 2]$$$, then we can first swap elements $$$a[2]$$$ and $$$a[3]$$$ (because position $$$2$$$ is contained in the given set $$$p$$$). We get the array $$$a = [3, 1, 2]$$$. Then we swap $$$a[1]$$$ and $$$a[2]$$$ (position $$$1$$$ is also contained in $$$p$$$). We get the array $$$a = [1, 3, 2]$$$. Finally, we swap $$$a[2]$$$ and $$$a[3]$$$ again and get the array $$$a = [1, 2, 3]$$$, sorted in non-decreasing order.You can see that if $$$a = [4, 1, 2, 3]$$$ and $$$p = [3, 2]$$$ then you cannot sort the array.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le m < n \le 100$$$) — the number of elements in $$$a$$$ and the number of elements in $$$p$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$). The third line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i < n$$$, all $$$p_i$$$ are distinct) — the set of positions described in the problem statement.

For each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$) using only allowed swaps. Otherwise, print "NO".

import java.io._
import java.util.StringTokenizer

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C624(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C624(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      val m = ni()

      val a = na(n)
      val p = Array.fill[Int](n+1)(0)
      REP(m) { _ =>
        p(ni()) += 1
      }

      var continue = true

      while (continue) {
        continue = false
        REP(n-1) { i =>
          if(a(i) > a(i+1)) {
            if(p(i+1) > 0) {
              val x = a(i+1)
              a(i+1) = a(i)
              a(i) = x
              continue = true
            }
          }
        }
      }
//      out.println(a.mkString(" "))
      REP(n-1) { i =>
        if(a(i) > a(i+1)) {
          continue = true
        }
      }
      if(continue) out.println("NO")
      else out.println("YES")
    }
  }
}

object B extends App {
  import scala.collection.mutable
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      var anyExchange = true
      while(anyExchange) {
        anyExchange = false
        for (i <- 0 until arr.length - 1) {
          if (arr(i) > arr(i + 1)) {
            if (ex.contains(i + 1)) {
              val t = arr(i)
              arr(i) = arr(i + 1)
              arr(i + 1) = t
              anyExchange = true
            }
          }
        }
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          return false
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}

import scala.collection.mutable

object B extends App {
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          if (ex.contains(i + 1)) {
            val t = arr(i)
            arr(i) = arr(i + 1)
            arr(i + 1) = t
          } else {
            return false
          }
        }
      }
      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          return false
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}

import scala.collection.mutable

object B extends App {
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          if (ex.contains(i + 1)) {
            val t = arr(i)
            arr(i) = arr(i + 1)
            arr(i + 1) = t
          } else {
            return false
          }
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}

object B extends App {
  import scala.collection.mutable
  import java.io.{BufferedReader, InputStreamReader, StreamTokenizer}

  solve()

  def solve(): Unit = {
    val in = new StreamTokenizer(new BufferedReader(new InputStreamReader((System.in))))

    @inline def nextInt = {
      in.nextToken()
      in.nval.asInstanceOf[Int]
    }

    @inline def canSort(arr: Array[Int], ex: mutable.Set[Int]): Boolean = {
      if (arr.length == 1) {
        return true
      }

      var anyExchange = true
      while(anyExchange) {
        for (i <- 0 until arr.length - 1) {
          anyExchange = false
          if (arr(i) > arr(i + 1)) {
            if (ex.contains(i + 1)) {
              val t = arr(i)
              arr(i) = arr(i + 1)
              arr(i + 1) = t
              anyExchange = true
            }
          }
        }
      }

      for (i <- 0 until arr.length - 1) {
        if (arr(i) > arr(i + 1)) {
          return false
        }
      }
      true
    }

    val t = nextInt
    for (_ <- 1 to t) {
      val (n, m) = (nextInt, nextInt)
      val array = new Array[Int](n)
      val exchangable = new mutable.HashSet[Int]()

      for (i <- 0 until n) {
        array(i) = nextInt
      }
      for (_ <- 0 until m) {
        exchangable.add(nextInt)
      }

      val can = canSort(array, exchangable)
      println(if(can) "YES" else "NO")
    }
  }

}


There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure:  The crow sets ai initially 0.  The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi + 2 - bi + 3.... Memory gives you the values a1, a2, ..., an, and he now wants you to find the initial numbers b1, b2, ..., bn written in the row? Can you do it?

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of integers written in the row. The next line contains n, the i'th of which is ai ( - 109 ≤ ai ≤ 109) — the value of the i'th number.

Print n integers corresponding to the sequence b1, b2, ..., bn. It's guaranteed that the answer is unique and fits in 32-bit integer type.

NoteIn the first sample test, the crows report the numbers 6, - 4, 8, - 2, and 3 when he starts at indices 1, 2, 3, 4 and 5 respectively. It is easy to check that the sequence 2 4 6 1 3 satisfies the reports. For example, 6 = 2 - 4 + 6 - 1 + 3, and  - 4 = 4 - 6 + 1 - 3.In the second sample test, the sequence 1,  - 3, 4, 11, 6 satisfies the reports. For example, 5 = 11 - 6 and 6 = 6.

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val line = (0 :: lines.next().split(' ').map(_.toInt).reverse.toList).sliding(2).map(_.sum).toList.reverse
  println(line.mkString(" "))
}

object A712 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readLongs(n)
    val res = Array.fill(n)(0L)
    for(i <- in.indices) {
      if(i != n-1) {
        res(i) = in(i) + in(i+1)
      } else {
        res(i) = in(i)
      }
    }
    println(res.mkString(" "))
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

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

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

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

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

}

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

object _712A extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val bs = read[Vector[Int]] :+ 0
    val as = bs.sliding(2).map(_.sum)

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

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

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

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

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

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

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

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

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


Bob got a job as a system administrator in X corporation. His first task was to connect n servers with the help of m two-way direct connection so that it becomes possible to transmit data from one server to any other server via these connections. Each direct connection has to link two different servers, each pair of servers should have at most one direct connection. Y corporation, a business rival of X corporation, made Bob an offer that he couldn't refuse: Bob was asked to connect the servers in such a way, that when server with index v fails, the transmission of data between some other two servers becomes impossible, i.e. the system stops being connected. Help Bob connect the servers.

The first input line contains 3 space-separated integer numbers n, m, v (3 ≤ n ≤ 105, 0 ≤ m ≤ 105, 1 ≤ v ≤ n), n — amount of servers, m — amount of direct connections, v — index of the server that fails and leads to the failure of the whole system.

If it is impossible to connect the servers in the required way, output -1. Otherwise output m lines with 2 numbers each — description of all the direct connections in the system. Each direct connection is described by two numbers — indexes of two servers, linked by this direct connection. The servers are numbered from 1. If the answer is not unique, output any.

object SystemAdministrator22C extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val m = in.nextInt()
    val v = in.nextInt()

    val stringBuilder = new StringBuilder()
    if(m>=n-1 && m <= (((n-1)*(n-2))/2+1)){
      val x = if(v == 1) 2 else 1

      def printEdges(node: Int,edgesToPrint: Int): Int = {

        if(node == v){
          for(i <- 1 to n){

            if(i != v) {
              stringBuilder.append(s"$v $i").append(System.lineSeparator())
            }
          }
          edgesToPrint-(n-1)
        }else{
          if(node == x){
            edgesToPrint
          }else{

            (node +1 to n).foldLeft(edgesToPrint)((edges,i) => {
              if(i == x || i == v || edges == 0){
                edges
              }else{
                stringBuilder.append(s"$node $i").append(System.lineSeparator())
                edges-1
              }
            })

          }
        }
      }

      (1 to n).foldLeft(printEdges(v,m))((restEdges,indx) => {
        if(indx == v || restEdges==0){
          restEdges
        }else{
          printEdges(indx,restEdges)
        }
      })

    }else{
      stringBuilder.append(-1)
    }

    out.println(stringBuilder.toString())

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int = return next().toInt
  }
}

object SystemAdministrator22C extends App {
  import java.io._
  import java.util.StringTokenizer
  solve(System.in,System.out)
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val n = in.nextInt()
    val m = in.nextInt()
    val v = in.nextInt()

    val stringBuilder = new StringBuilder()
    if(m>=n-1 && m <= (((n-1)*(n-2))/2+1)){
      val x = if(v == 1) 2 else 1

      def printEdges(node: Int,edgesToPrint: Int): Int = {

        if(node == v){
          for(i <- 1 to n){

            if(i != v) {
              stringBuilder.append(s"$v $i").append(System.lineSeparator())
            }
          }
          edgesToPrint-(n-1)
        }else{
          if(node == x){
            edgesToPrint
          }else{
            var i = node+1
            var counter = edgesToPrint
            while( counter > 0 && i<=n){
              if(i != x && i != v){
                stringBuilder.append(s"$node $i").append(System.lineSeparator())
                counter -= 1
              }
              i += 1
            }
            counter
          }
        }
      }

      var restEdges = printEdges(v,m)
      var indx = 1

      while(restEdges > 0){
        if(indx != v){
          restEdges = printEdges(indx,restEdges)
        }
        indx += 1

      }

    }else{
      stringBuilder.append(-1)
    }

    out.println(stringBuilder.toString())

  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int = return next().toInt
  }
}


You are given a decimal representation of an integer $$$x$$$ without leading zeros.You have to perform the following reduction on it exactly once: take two neighboring digits in $$$x$$$ and replace them with their sum without leading zeros (if the sum is $$$0$$$, it's represented as a single $$$0$$$).For example, if $$$x = 10057$$$, the possible reductions are:   choose the first and the second digits $$$1$$$ and $$$0$$$, replace them with $$$1+0=1$$$; the result is $$$1057$$$;  choose the second and the third digits $$$0$$$ and $$$0$$$, replace them with $$$0+0=0$$$; the result is also $$$1057$$$;  choose the third and the fourth digits $$$0$$$ and $$$5$$$, replace them with $$$0+5=5$$$; the result is still $$$1057$$$;  choose the fourth and the fifth digits $$$5$$$ and $$$7$$$, replace them with $$$5+7=12$$$; the result is $$$10012$$$. What's the largest number that can be obtained?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Each testcase consists of a single integer $$$x$$$ ($$$10 \le x < 10^{200000}$$$). $$$x$$$ doesn't contain leading zeros. The total length of the decimal representations of $$$x$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the largest number that can be obtained after the reduction is applied exactly once. The number should not contain leading zeros.

NoteThe first testcase of the example is already explained in the statement.In the second testcase, there is only one possible reduction: the first and the second digits.

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

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

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

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

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

    val t = readInt()

    for (tt <- 1 to t) {
        val z = '0'.toInt
        val s = readString()
        var c = 0
        var v = 0
        for (i <- 0 to s.length-2) {
            if (s(i).toInt - z + s(i+1).toInt - z >= 10) {
                c = i
            }
        }
        for (i <- 0 until s.length) {
            if (i != c && i != c+1) {
                writer.print(s(i))
            }
            if (i == c) {
                v = s(c).toInt - z + s(c+1).toInt - z
                if (v >= 10) {
                    writer.print('1')
                }
                v %= 10
                writer.print((v + z).toChar)
            }
        }
        writer.println()

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

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

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

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

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

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

    val t = readInt()

    for (tt <- 1 to t) {
        val z = '0'.toInt
        val s = readString()
        var c = s.length - 2
        var v = 0
        for (i <- s.indices) {
            if (i != s.length - 1) {
                if (s(i).toInt - z + s(i+1).toInt - z >= 10) {
                    c = i
                }
            }
        }
        for (i <- s.indices) {
            if (i != c && i != c+1) {
                writer.print(s(i))
            }
            if (i == c) {
                v = s(i).toInt - z + s(i+1).toInt - z
                if (v >= 10) {
                    writer.print((v/10 + z).toChar)
                }
                writer.print((v%10 + z).toChar)
            }
        }
        writer.println()

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


The King of Berland Polycarp LXXXIV has $$$n$$$ daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are $$$n$$$ other kingdoms as well.So Polycarp LXXXIV has enumerated his daughters from $$$1$$$ to $$$n$$$ and the kingdoms from $$$1$$$ to $$$n$$$. For each daughter he has compiled a list of kingdoms princes of which she wanted to marry.Polycarp LXXXIV is very busy, so he finds a couple for his daughters greedily one after another.For the first daughter he takes the kingdom with the lowest number from her list and marries the daughter to their prince. For the second daughter he takes the kingdom with the lowest number from her list, prince of which hasn't been taken already. If there are no free princes in the list then the daughter marries nobody and Polycarp LXXXIV proceeds to the next daughter. The process ends after the $$$n$$$-th daughter.For example, let there be $$$4$$$ daughters and kingdoms, the lists daughters have are $$$[2, 3]$$$, $$$[1, 2]$$$, $$$[3, 4]$$$, $$$[3]$$$, respectively.  In that case daughter $$$1$$$ marries the prince of kingdom $$$2$$$, daughter $$$2$$$ marries the prince of kingdom $$$1$$$, daughter $$$3$$$ marries the prince of kingdom $$$3$$$, leaving daughter $$$4$$$ nobody to marry to.Actually, before starting the marriage process Polycarp LXXXIV has the time to convince one of his daughters that some prince is also worth marrying to. Effectively, that means that he can add exactly one kingdom to exactly one of his daughter's list. Note that this kingdom should not be present in the daughter's list.Polycarp LXXXIV wants to increase the number of married couples.Unfortunately, what he doesn't have the time for is determining what entry to add. If there is no way to increase the total number of married couples then output that the marriages are already optimal. Otherwise, find such an entry that the total number of married couples increases if Polycarp LXXXIV adds it.If there are multiple ways to add an entry so that the total number of married couples increases then print any of them.For your and our convenience you are asked to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of daughters and the number of kingdoms. Each of the next $$$n$$$ lines contains the description of each daughter's list. The first integer $$$k$$$ ($$$0 \le k \le n$$$) is the number of entries in the $$$i$$$-th daughter's list. After that $$$k$$$ distinct integers follow $$$g_i[1], g_i[2], \dots, g_i[k]$$$ ($$$1 \le g_i[j] \le n$$$) — the indices of the kingdoms in the list in the increasing order ($$$g_i[1] < g_i[2] < \dots < g_i[k]$$$). It's guaranteed that the total number of daughters over all test cases does not exceed $$$10^5$$$. It's also guaranteed that the total number of kingdoms in lists over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it. Print "IMPROVE" in the first line if Polycarp LXXXIV can add some kingdom to some of his daughter's list so that the total number of married couples increases. The second line then should contain two integers — the index of the daughter and the index of the kingdom Polycarp LXXXIV should add to that daughter's list. If there are multiple ways to add an entry so that the total number of married couples increases then print any of them. Otherwise the only line should contain one word "OPTIMAL".

IMPROVE
4 4
IMPROVE
1 1
OPTIMAL
OPTIMAL
OPTIMAL

NoteThe first test case is depicted in the statement. Adding the fourth kingdom to the list of the fourth daughter makes her marry the prince of the fourth kingdom.In the second test case any new entry will increase the number of marriages from $$$0$$$ to $$$1$$$.In the third and the fourth test cases there is no way to add an entry.In the fifth test case there is no way to change the marriages by adding any entry.

import scala.util.control.Breaks

object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val tC = in.readLine().toInt
    for (t <- 0 until tC) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      for (i <- 0 until n) {
        val l=in.readLine()
        if(l.length>1)
          arr(i)=l.substring(l.indexOf(" ")+1).split(" ").map(_.toInt-1)
        else
          arr(i)=new Array[Int](0)
      }
      val p=Array.fill[Boolean](n)(false)
      val m=Array.fill[Boolean](n)(false)
      var um=0
      for (i <- 0 until n) {
        Breaks.breakable {
          for (j <- 0 until arr(i).length) {
            if(p(arr(i)(j))==false){
              p(arr(i)(j))=true
              m(i)=true
              Breaks.break()
            }
          }
          um+=1
        }
      }
      if(um==0){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        var pri=0
        var gri=0
        if (um!=0){
          um-=1
          while (p(pri)) pri+=1
          while (m(gri)) gri+=1
          m(gri)=true
          p(pri)=true
          println((gri+1)+" "+(pri+1))
        }
      }
    }
  }
}

import scala.util.control.Breaks
import scala.collection.mutable.HashSet

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      val unmarriedPrinces=HashSet[Int]()
      for (i <- 0 until n) {
        unmarriedPrinces+=i
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      var unmarriedPrincessIndex= -1
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (unmarriedPrinces.contains(arr(i)(j))) {
                unmarriedPrinces-=(arr(i)(j))
                Breaks.break()
              }
            }
          }
          unmarriedPrincessIndex=i
        }
      }
      if(unmarriedPrincessIndex== -1){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        println((unmarriedPrincessIndex+1)+" "+(unmarriedPrinces.head+1))
      }
    }
  }
}

import scala.util.control.Breaks

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      for (i <- 0 until n) {
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      val marriedPrinces=Array.fill[Boolean](n)(false)
      val marriedPrincesses=Array.fill[Boolean](n)(false)
      var unmarriedPrincesses=0
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (marriedPrinces(arr(i)(j)) == false) {
                marriedPrinces(arr(i)(j)) = true
                marriedPrincesses(i) = true
                Breaks.break()
              }
            }
          }
          unmarriedPrincesses+=1
        }
      }
      if(unmarriedPrincesses==0){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        var unmarriedPriceIndex=0
        var unmarriedPrincessIndex=0
        /*if (unmarriedPrincesses!=0){
          unmarriedPrincesses-=1*/
          while (marriedPrinces(unmarriedPriceIndex)) {
            unmarriedPriceIndex+=1
          }
          while (marriedPrincesses(unmarriedPrincessIndex)) {
            unmarriedPrincessIndex+=1
          }
          marriedPrincesses(unmarriedPrincessIndex)=true
          marriedPrinces(unmarriedPriceIndex)=true

          println((unmarriedPrincessIndex+1)+" "+(unmarriedPriceIndex+1))
        //}
      }
    }
  }
}

import scala.util.control.Breaks

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      for (i <- 0 until n) {
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      val marriedPrinces=Array.fill[Boolean](n)(false)
      val marriedPrincesses=Array.fill[Boolean](n)(false)
      var unmarriedPrincesses=0
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (marriedPrinces(arr(i)(j)) == false) {
                marriedPrinces(arr(i)(j)) = true
                marriedPrincesses(i) = true
                Breaks.break()
              }
            }
          }
          unmarriedPrincesses+=1
        }
      }
      if(unmarriedPrincesses==0){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        var unmarriedPriceIndex=0
        var unmarriedPrincessIndex=0
        if (unmarriedPrincesses!=0){
          unmarriedPrincesses-=1
          while (marriedPrinces(unmarriedPriceIndex)) {
            unmarriedPriceIndex+=1
          }
          while (marriedPrincesses(unmarriedPrincessIndex)) {
            unmarriedPrincessIndex+=1
          }
          marriedPrincesses(unmarriedPrincessIndex)=true
          marriedPrinces(unmarriedPriceIndex)=true

          println((unmarriedPrincessIndex+1)+" "+(unmarriedPriceIndex+1))
        }
      }
    }
  }
}

import scala.util.control.Breaks
import scala.collection.mutable.HashSet

//https://codeforces.com/problemset/problem/1327/B
object PrincessesAndPrinces {
  def main(args: Array[String]): Unit = {
    val in = scala.io.StdIn
    val testCases = in.readLine().toInt
    for (t <- 0 until testCases) {
      val n = in.readLine().toInt
      val arr=new Array[Array[Int]](n)
      val unmarriedPrinces=HashSet[Int]()
      var unmarriedPrincessIndex= -1
      for (i <- 0 until n) {
        unmarriedPrinces+=i
        val l=in.readLine()
        if(l.length>1) {
          arr(i) = l.substring(l.indexOf(" ") + 1).split(" ").map(_.toInt - 1)
        }
      }
      for (i <- 0 until n) {
        Breaks.breakable {
          if( arr(i)!=null) {
            for (j <- 0 until arr(i).length) {
              if (unmarriedPrinces.contains(arr(i)(j))) {
                unmarriedPrinces-=(arr(i)(j))
                Breaks.break()
              }
            }
          }
          unmarriedPrincessIndex=i
        }
      }
      if(unmarriedPrincessIndex== -1){
        println("OPTIMAL")
      }else{
        println("IMPROVE")
        println((unmarriedPrincessIndex+1)+" "+(unmarriedPrinces.head+1))
      }
    }
  }
}

object Main {

  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    val maxN = 100002

    val ps = Array.fill(maxN)(true)
    val lista = Array.fill(maxN)(List.empty[Int])
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      ps(0) = false
      (1 to n).foreach{ i =>

        ps(i) = true
      }

      (1 to n).foreach{ i =>
        val k = in.nextInt()
        lista(i) = (1 to k).map(_ => in.nextInt()).toList
      }
      var dsFree = -1
      (1 to n).foreach{ i =>
        lista(i).find(ps) match {
          case Some(p) => ps(p) = false
          case None => dsFree = i
        }
      }
      if(dsFree == -1){
        out.println("OPTIMAL")
      }else{
        val psFree = ps.indexWhere(p => p)
        out.println("IMPROVE")
        out.println(s"$dsFree $psFree")
      }

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


You and your friend Ilya are participating in an individual programming contest consisting of multiple stages. A contestant can get between $$$0$$$ and $$$100$$$ points, inclusive, for each stage, independently of other contestants.Points received by contestants in different stages are used for forming overall contest results. Suppose that $$$k$$$ stages of the contest are completed. For each contestant, $$$k - \lfloor \frac{k}{4} \rfloor$$$ stages with the highest scores are selected, and these scores are added up. This sum is the overall result of the contestant. (Here $$$\lfloor t \rfloor$$$ denotes rounding $$$t$$$ down.)For example, suppose $$$9$$$ stages are completed, and your scores are $$$50, 30, 50, 50, 100, 10, 30, 100, 50$$$. First, $$$7$$$ stages with the highest scores are chosen — for example, all stages except for the $$$2$$$-nd and the $$$6$$$-th can be chosen. Then your overall result is equal to $$$50 + 50 + 50 + 100 + 30 + 100 + 50 = 430$$$.As of now, $$$n$$$ stages are completed, and you know the points you and Ilya got for these stages. However, it is unknown how many more stages will be held. You wonder what the smallest number of additional stages is, after which your result might become greater than or equal to Ilya's result, at least in theory. Find this number!

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of completed stages. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$) — your points for the completed stages. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$0 \le b_i \le 100$$$) — Ilya's points for the completed stages. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print a single integer — the smallest number of additional stages required for your result to be able to become greater than or equal to Ilya's result. If your result is already not less than Ilya's result, print $$$0$$$.

NoteIn the first test case, you have scored $$$100$$$ points for the first stage, while Ilya has scored $$$0$$$. Thus, your overall result ($$$100$$$) is already not less than Ilya's result ($$$0$$$).In the second test case, you have scored $$$0$$$ points for the first stage, while Ilya has scored $$$100$$$. A single stage with an opposite result is enough for both your and Ilya's overall scores to become equal to $$$100$$$.In the third test case, your overall result is $$$30 + 40 + 50 = 120$$$, while Ilya's result is $$$100 + 100 + 100 = 300$$$. After three additional stages your result might become equal to $$$420$$$, while Ilya's result might become equal to $$$400$$$.In the fourth test case, your overall result after four additional stages might become equal to $$$470$$$, while Ilya's result might become equal to $$$400$$$. Three stages are not enough.

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, n << 1, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 200000, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 500000, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 175000, score) - n

    println(ans)
  }
}

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

  def binarySearch(left: Int, right: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }

    go(left, right)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(stages: Int): Boolean = {
      val selected = stages - stages / 4

      val ascore = {
        val hundreds = 0 max (stages - n)
        val previous = 0 max (selected - hundreds)
        100 * hundreds + aprefix(n) - aprefix(n - previous)
      }

      val bscore = bprefix(n) - bprefix(0 max (n - selected))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else binarySearch(n, 100000, score) - n

    println(ans)
  }
}

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

  def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }
    go(l, r)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(k: Int): Boolean = {
      val r = k - k / 4

      val ascore =
        if (k <= n) aprefix(n) - aprefix(n - r)
        else {
          val e = r min (k - n)
          e * 100 + aprefix(n) - aprefix(n - r + e)
        }

      val bscore = bprefix(n) - bprefix(0 max (n - r))

      ascore >= bscore
    }

    val ans =
      if (score(n)) 0
      else {
        val right = {
          @annotation.tailrec
          def go(r: Int): Int = if (score(r)) r else go(r << 1)
          go(1)
        }
        binarySearch(n, right, score) - n
      }

    println(ans)
  }
}

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

  def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }
    go(l, r)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(k: Int): Boolean = {
      val r = k - k / 4

      val (ascore, bscore) =
        if (k <= n) (aprefix(n) - aprefix(n - r), bprefix(n) - bprefix(n - r))
        else {
          val e = r min (k - n)
          (e * 100 + aprefix(n) - aprefix(n - r + e), bprefix(n))
        }

      ascore >= bscore
    }

    val ans = if (score(n)) 0 else binarySearch(n, 100005, score) - n

    println(ans)
  }
}

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

  def binarySearch(l: Int, r: Int, f: Int => Boolean): Int = {
    @annotation.tailrec
    def go(l: Int, r: Int): Int =
      if (l + 1 >= r) r
      else {
        val m = (l + r) / 2
        f(m) match {
          case true => go(l, m)
          case _    => go(m, r)
        }
      }
    go(l, r)
  }

  val t = readInt()

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

    val (aprefix, bprefix) = (an.scanLeft(0)(_ + _), bn.scanLeft(0)(_ + _))

    def score(k: Int): Boolean = {
      val r = k - k / 4

      val (ascore, bscore) =
        if (k <= n) (aprefix(n) - aprefix(n - r), bprefix(n) - bprefix(n - r))
        else {
          val e = r min (k - n)
          (e * 100 + aprefix(n) - aprefix(n - r + e), bprefix(n))
        }

      ascore >= bscore
    }

    val ans = if (score(n)) 0 else binarySearch(n, 200, score) - n

    println(ans)
  }
}


"The zombies are lurking outside. Waiting. Moaning. And when they come...""When they come?""I hope the Wall is high enough."Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segments. We call on you for help. Go forth and explore the wall! Report how many disconnected segments there are.The wall is a two-dimensional structure made of bricks. Each brick is one unit wide and one unit high. Bricks are stacked on top of each other to form columns that are up to R bricks high. Each brick is placed either on the ground or directly on top of another brick. Consecutive non-empty columns form a wall segment. The entire wall, all the segments and empty columns in-between, is C columns wide.

The first line of the input consists of two space-separated integers R and C, 1 ≤ R, C ≤ 100. The next R lines provide a description of the columns as follows:    each of the R lines contains a string of length C,  the c-th character of line r is B if there is a brick in column c and row R - r + 1, and . otherwise.  B

The number of wall segments in the input configuration.

NoteIn the first sample case, the 2nd and 3rd columns define the first wall segment, and the 5th column defines the second.

/**
  * Created by John Compitello on 7/25/16.
  */
object Easy {
  def main(args: Array[String]) = {
    val lines: Array[String] = (for (ln <- io.Source.stdin.getLines) yield (ln)).toArray
    val wallSegments = lines(lines.length - 1).split("\\.").filter(_ != "")
    println(wallSegments.length)
  }
}


You've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1 < i ≤ n) holds ci ≤ ci - 1. Let's denote s as the total number of cells of table a, that is, . We know that each cell of the table contains a single integer from 1 to s, at that all written integers are distinct. Let's assume that the cells of the i-th row of table a are numbered from 1 to ci, then let's denote the number written in the j-th cell of the i-th row as ai, j. Your task is to perform several swap operations to rearrange the numbers in the table so as to fulfill the following conditions:  for all i, j (1 < i ≤ n; 1 ≤ j ≤ ci) holds ai, j > ai - 1, j;  for all i, j (1 ≤ i ≤ n; 1 < j ≤ ci) holds ai, j > ai, j - 1. In one swap operation you are allowed to choose two different cells of the table and swap the recorded there numbers, that is the number that was recorded in the first of the selected cells before the swap, is written in the second cell after it. Similarly, the number that was recorded in the second of the selected cells, is written in the first cell after the swap.Rearrange the numbers in the required manner. Note that you are allowed to perform any number of operations, but not more than s. You do not have to minimize the number of operations.

The first line contains a single integer n (1 ≤ n ≤ 50) that shows the number of rows in the table. The second line contains n space-separated integers ci (1 ≤ ci ≤ 50; ci ≤ ci - 1) — the numbers of cells on the corresponding rows. Next n lines contain table а. The i-th of them contains ci space-separated integers: the j-th integer in this line represents ai, j. It is guaranteed that all the given numbers ai, j are positive and do not exceed s. It is guaranteed that all ai, j are distinct.

In the first line print a single integer m (0 ≤ m ≤ s), representing the number of performed swaps. In the next m lines print the description of these swap operations. In the i-th line print four space-separated integers xi, yi, pi, qi (1 ≤ xi, pi ≤ n; 1 ≤ yi ≤ cxi; 1 ≤ qi ≤ cpi). The printed numbers denote swapping the contents of cells axi, yi and api, qi. Note that a swap operation can change the contents of distinct table cells. Print the swaps in the order, in which they should be executed.

object JungTables extends App {
  // reading data
  var moves:List[(Int, Int, Int, Int)] = List()
  val n = Console.readLine() toInt
  var aa = Array.fill(n, 1)(0)
  val cc = Console.readLine() split(" ") map (_.toInt)
  for (i <- 0 until n) {
    aa(i) = Console.readLine() split(" ") map (_.toInt)
  }

  def findMin(ia: Int, ja:Int) : (Int, Int, Int) = {
    var mn=aa(ia)(ja)
    var ii=ia
    var jj=ja
    for {
      i <- Range(ia, n)
      j <- Range(ja, cc(i))
    } if (aa(i)(j) < mn) {
      mn = aa(i)(j);  ii = i; jj=j
    }
    (mn, ii, jj)
  }

  def fixPoint(ia:Int, ja:Int) = {
    val (mn, ii, jj) = findMin(ia, ja)
    if (ii != ia || jj != ja) {
      val temp = aa(ia)(ja)
      aa(ia)(ja) = aa(ii)(jj)
      aa(ii)(jj) = temp
      moves = (ia+1, ja+1, ii+1, jj+1) :: moves
    }
  }

  for {
    i <- 0 until n
    j <- 0 until cc(i)
  } fixPoint(i,j)
  moves = moves reverse;
  println(moves length)
  for ((a,b,c,d) <- moves)
    println(a + " " + b + " " + c + " " + d)
}


You are given an array $$$a$$$ with $$$n$$$ non-negative integers. You can apply the following operation on it.   Choose two indices $$$l$$$ and $$$r$$$ ($$$1 \le l < r \le n$$$).  If $$$a_l + a_r$$$ is odd, do $$$a_r := a_l$$$. If $$$a_l + a_r$$$ is even, do $$$a_l := a_r$$$. Find any sequence of at most $$$n$$$ operations that makes $$$a$$$ non-decreasing. It can be proven that it is always possible. Note that you do not have to minimize the number of operations.An array $$$a_1, a_2, \ldots, a_n$$$ is non-decreasing if and only if $$$a_1 \le a_2 \le \ldots \le a_n$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$)  — the array itself. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print one integer $$$m$$$ ($$$0 \le m \le n$$$), the number of operations, in the first line. Then print $$$m$$$ lines. Each line must contain two integers $$$l_i, r_i$$$, which are the indices you chose in the $$$i$$$-th operation ($$$1 \le l_i < r_i \le n$$$). If there are multiple solutions, print any of them.

NoteIn the second test case, $$$a$$$ changes like this:  Select indices $$$3$$$ and $$$4$$$. $$$a_3 + a_4 = 3$$$ is odd, so do $$$a_4 := a_3$$$. $$$a = [1, 1000000000, 3, 3, 5]$$$ now.  Select indices $$$1$$$ and $$$2$$$. $$$a_1 + a_2 = 1000000001$$$ is odd, so do $$$a_2 := a_1$$$. $$$a = [1, 1, 3, 3, 5]$$$ now, and it is non-decreasing. In the first and third test cases, $$$a$$$ is already non-decreasing.

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
    val n = readInt()
    val a: Array[Int] = readLine().split(" ").map(_.toInt)
    println(n - 1)
    if(n != 1) println(s"1 $n")
    val pivot = if((a(0) + a(n-1)) % 2 == 0) a(n-1) else a(0)
    for(i <- 2 to (n - 1)){
      if((a(i - 1) + pivot) % 2 == 0)
        println(s"$i $n")
      else
        println(s"1 $i")
    }

  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}

// To execute Scala code, please define an object named Solution that extends App
import scala.io.StdIn._
object Solution extends App {

  private def solve(): Unit = {
    val n = readInt()
    val a: Array[Int] = readLine().split(" ").map(_.toInt)
    println(n - 1)
    println(s"1 $n")
    val pivot = if((a(0) + a(n-1)) % 2 == 0) a(n-1) else a(0)
    for(i <- 2 to (n - 1)){
      if((a(i - 1) + pivot) % 2 == 0)
        println(s"$i $n")
      else
        println(s"1 $i")
    }

  }

  val test_cases: Int = readInt()
  for(i <- 0 until test_cases)
    solve()
}


Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $$$n$$$ hotels, where the $$$i$$$-th hotel is located in the city with coordinate $$$x_i$$$. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $$$d$$$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $$$n$$$ hotels to the new one is equal to $$$d$$$.

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1\leq n\leq 100$$$, $$$1\leq d\leq 10^9$$$) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains $$$n$$$ different integers in strictly increasing order $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9\leq x_i\leq 10^9$$$) — coordinates of Sonya's hotels.

Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $$$d$$$.

NoteIn the first example, there are $$$6$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$-6$$$, $$$5$$$, $$$6$$$, $$$12$$$, $$$13$$$, and $$$19$$$.In the second example, there are $$$5$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$2$$$, $$$6$$$, $$$13$$$, $$$16$$$, and $$$21$$$.

import scala.io.StdIn

object Solution extends App {
  val array1 = StdIn.readLine().split(" ").map(_.toInt)
  var n = array1(0)
  var d = array1(1)

  var count = 2

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

  for (i <- 0 until arr.size - 1)
    {
      val a = arr(i) + d
      val b = arr(i + 1) - d
      if (a <= b)
        {
          if (a != b) count = count + 2 else count = count + 1
        }
    }
  println(count)
}

import scala.io.StdIn.readLine

object a1004 {
  def main(args: Array[String]): Unit = {
    def getInts() =  readLine().split(" ").map(_.toInt)
    val Array(n, d) = getInts()
    val hs = getInts()
    println((hs zip hs.tail map{ a=> val c = a._2 - a._1 -1 - (2*(d-1)) ; if (c<0) 0 else if (c>2) 2 else c} sum) + 2)
  }
}

object A1004 extends App {
  def read: Array[Int] = readLine.split(" ").map(_.toInt)

  val (n, d) = {
    val fl = read
    (fl(0), fl(1))
  }

  val hotels = read

  def result = {
    (0 to n - 1)
      .map { i =>
        if (i == n - 1) 1
        else {
          val diff = (hotels(i + 1) - hotels(i)) / d
          val residual = (hotels(i + 1) - hotels(i)) % d
          if (diff == 2 && residual > 0 || diff > 2) 2
          else if (diff == 2) 1
          else 0
        }
      }
      .reduce(_ + _) + 1
  }

  println(result)
}