Dora the explorer has decided to use her money after several years of juicy royalties to go shopping. What better place to shop than Nlogonia?There are $$$n$$$ stores numbered from $$$1$$$ to $$$n$$$ in Nlogonia. The $$$i$$$-th of these stores offers a positive integer $$$a_i$$$.Each day among the last $$$m$$$ days Dora bought a single integer from some of the stores. The same day, Swiper the fox bought a single integer from all the stores that Dora did not buy an integer from on that day.Dora considers Swiper to be her rival, and she considers that she beat Swiper on day $$$i$$$ if and only if the least common multiple of the numbers she bought on day $$$i$$$ is strictly greater than the least common multiple of the numbers that Swiper bought on day $$$i$$$.The least common multiple (LCM) of a collection of integers is the smallest positive integer that is divisible by all the integers in the collection.However, Dora forgot the values of $$$a_i$$$. Help Dora find out if there are positive integer values of $$$a_i$$$ such that she beat Swiper on every day. You don't need to find what are the possible values of $$$a_i$$$ though.Note that it is possible for some values of $$$a_i$$$ to coincide in a solution.

The first line contains integers $$$m$$$ and $$$n$$$ ($$$1\leq m \leq 50$$$, $$$1\leq n \leq 10^4$$$) — the number of days and the number of stores. After this $$$m$$$ lines follow, the $$$i$$$-th line starts with an integer $$$s_i$$$ ($$$1\leq s_i \leq n-1$$$), the number of integers Dora bought on day $$$i$$$, followed by $$$s_i$$$ distinct integers, the indices of the stores where Dora bought an integer on the $$$i$$$-th day. The indices are between $$$1$$$ and $$$n$$$.

Output must consist of a single line containing "possible" if there exist positive integers $$$a_i$$$ such that for each day the least common multiple of the integers bought by Dora is strictly greater than the least common multiple of the integers bought by Swiper on that day. Otherwise, print "impossible". Note that you don't have to restore the integers themselves.

NoteIn the first sample, a possible choice for the values of the $$$a_i$$$ is $$$3, 4, 3, 5, 2$$$. On the first day, Dora buys the integers $$$3, 4$$$ and $$$3$$$, whose LCM is $$$12$$$, while Swiper buys integers $$$5$$$ and $$$2$$$, whose LCM is $$$10$$$. On the second day, Dora buys $$$3, 5$$$ and $$$2$$$, whose LCM is $$$30$$$, and Swiper buys integers $$$3$$$ and $$$4$$$, whose LCM is $$$12$$$.

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 M, N = ni()
    val sets = Array.fill[mutable.Set[Int]](N)(mutable.Set())
    REP(M) { i =>
      REP(ni()) { _ =>
        sets(i) += ni() - 1
      }
    }

    var ok = true
    REP(M) { i =>
      REP(M) { j =>
        if (i != j) {
          if (!sets(i).exists(sets(j).contains)) ok = false
        }
      }
    }

    if (ok) out.println("possible")
    else out.println("impossible")
  }
}


Permutation p is an ordered set of integers p1,  p2,  ...,  pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1,  p2,  ...,  pn.You have a sequence of integers a1, a2, ..., an. In one move, you are allowed to decrease or increase any number by one. Count the minimum number of moves, needed to build a permutation from this sequence.

The first line contains integer n (1 ≤ n ≤ 3·105) — the size of the sought permutation. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).

Print a single number — the minimum number of moves. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample you should decrease the first number by one and then increase the second number by one. The resulting permutation is (2, 1).In the second sample you need 6 moves to build permutation (1, 3, 2).

import java.util.StringTokenizer

object _285C extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toLong).sorted
  val b = (a zip (1 to n)).map(i => (i._1 - i._2).abs)
  println(b.sum)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var changes = 0l
  var counts = Array.ofDim[Int](n)
  data.foreach{i => if (i < 1) {
      counts(0) += 1
      changes += -i + 1
    } else if (i > n) {
      counts(n - 1) += 1
      changes += i - n
    } else {
      counts(i - 1) += 1
    }
  }
  var leftZero = 0
  while (leftZero != n && counts(leftZero) != 0)
    leftZero += 1
  var leftMoreOne = 0
  while (leftMoreOne != n && counts(leftMoreOne) < 2)
    leftMoreOne += 1

  while (leftZero < n && leftMoreOne < n) {

    changes += Math.abs(leftZero - leftMoreOne)
    counts(leftZero) = 1
    while (leftZero != n && counts(leftZero) != 0)
      leftZero += 1
    counts(leftMoreOne) -= 1
    while (leftMoreOne != n && counts(leftMoreOne) < 2)
      leftMoreOne += 1
  }

  println(changes)
}

object C285 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readLongs(n).sorted.zipWithIndex.map{case (x, y) => (x, y+1)}
    println(in.map{case (a, b) => math.abs(a-b)}.sum)
  }

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

}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextLong
  val s = (v.sorted, (1 to n)).zipped.map((x, y) => scala.math.abs(x - y)).sum
  out.println(s)

  out.flush
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt
  val s = v.sorted.view.zip(1 to n).map(x => scala.math.abs(x._1 - x._2).toLong).sum
  out.println(s)

  out.flush
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextLong
  val s = v.sorted.view.zip(1 to n).map(x => scala.math.abs(x._1 - x._2)).sum
  out.println(s)

  out.flush
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt.toLong
  val s = v.sorted.view.zipWithIndex.map(x => scala.math.abs(x._1 - (x._2 + 1))).sum
  out.println(s)

  out.flush
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt
  val s = v.sorted.zip(1 to n).map(x => scala.math.abs(x._1 - x._2).toLong).sum
  out.println(s)

  out.flush
}

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

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

  val N = sc.nextInt
  val as0 = Array.fill(N)(sc.nextLong).sorted
  val as = new Array[Long](N + 1)
  as0.copyToArray(as, 1)

  val answer: Long = {
    @tailrec
    def loop(acc: Long, i: Int): Long =
      if (i > N) acc
      else loop(acc + math.abs(as(i) - i), i + 1)
    loop(0, 1)
  }

  out.println(answer)
  out.close
}

import scala.io.StdIn

object BuildingPermutation {

  def dist2(l:List[Long]):Long = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n

    ((OneN zip ls).map { x => Math.abs(x._1-x._2) }).sum
  }

  def dist(l:List[Long]):Long = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n
    //
    val minl = ls filter (x=>{x<=1})
    //System.err.println("minl:"+ minl)
    val maxl = ls filter (x=>{x>=n})
    //System.err.println("maxl:" + maxl)
    val midl = ls filter (x=>{x>1 && x<n})
    //System.err.println("midl:" + midl)

    val OneNLeft = OneN filter (x=>{!(midl contains x)})
    //System.err.println("OneNLeft:" + OneNLeft.toList)
    val common = OneN filter (x=>(midl contains x))
    //System.err.println("common:" + common)
    val midlLeft = midl diff common
    //System.err.println("mildLeft:" + midlLeft)

    val lowerOneNLeft = OneNLeft take (minl.length)
    //System.err.println("lowerOneNLeft:" + lowerOneNLeft.toList)

    val upperOneNLeft = OneNLeft takeRight (maxl.length)
   // System.err.println("upperOneNLeft:" + upperOneNLeft.toList)

    val midOneNLeft = OneNLeft.slice(minl.length, n-maxl.length)
    //System.err.println("midOneNLeft:" + midOneNLeft.toList)

    ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum +
    ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum +
    ((midlLeft zip midOneNLeft) map {x=>Math.abs(x._1-x._2)}).sum
  }

  def main(arg:Array[String]){
    val n = StdIn.readLine().toInt;
    val il:List[Long] = (StdIn.readLine().split(" ").map { x => x.toLong }).toList
    println(dist2(il))
  }
}

import annotation.tailrec
import java.io._

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

  val n = readInt
  def ans = readInts.sorted.zip(1 to n).map(_.productIterator.map(_.asInstanceOf[Int]).reduceLeft(_-_).abs.toLong).sum

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

import scala.annotation.tailrec
import scala.math._
object C
{
    def main(args: Array[String])
    {
        val n = readLine.toInt
        val a = readLine split(" ") map(_ toInt) sortWith(_ < _)
        @tailrec
        def solve(pos : Int = 0, ans : Long = 0): Long = {
            if(pos<a.length){
                solve(pos+1,ans+abs(a(pos)-(pos+1)))
            }
            else{ans}
        }
        println(solve())
    }
}

object Main {
  def main(args: Array[String]) {
    val n = readLong
    val a = readLine().split(" ").map(_.toLong)
    val count = a.sorted.zipWithIndex.foldLeft(0L) { (a, t) =>
      a + (t._2 + 1 - t._1).abs
    }
    println(count)
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readInt()
    val list = readLine split (" ") map (_ toInt) sortWith (_ < _)
    val dList = 1.to(N).map(i => (list(i - 1) - i).abs.toLong);
    print(dList.sum)
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readLine.toInt
    val list = readLine split (" ") map (_ toInt) sortWith (_ < _)
    @tailrec
    def loop(pos: Int = 0, ans: Long = 0): Long = {
      if (pos < list.length) {
        loop(pos + 1, ans + abs(list(pos) - (pos + 1)))
      } else {
        ans
      }
    }
    println(loop())
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readInt()
    val list = readLine split(" ") map(_ toInt) sortWith(_ < _)

    @tailrec
    def loop(step: Int = 0, acc: Long = 0): Long = {
      if (step == N) {
        acc
      } else {
        loop(step + 1, acc + abs(list(step) - (step + 1)))
      }
    }
    val ans = loop()
    print(ans)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var changes = 0
  var counts = Array.ofDim[Int](n)
  data.foreach{i => if (i < 1) {
      counts(0) += 1
      changes += -i + 1
    } else if (i > n) {
      counts(n - 1) += 1
      changes += i - n
    } else {
      counts(i - 1) += 1
    }
  }
  var leftZero = 0
  while (leftZero != n && counts(leftZero) != 0)
    leftZero += 1
  var leftMoreOne = 0
  while (leftMoreOne != n && counts(leftMoreOne) < 2)
    leftMoreOne += 1

  while (leftZero < n && leftMoreOne < n) {

    changes += Math.abs(leftZero - leftMoreOne)
    counts(leftZero) = 1
    while (leftZero != n && counts(leftZero) != 0)
      leftZero += 1
    counts(leftMoreOne) -= 1
    while (leftMoreOne != n && counts(leftMoreOne) != 0)
      leftMoreOne += 1
  }

  println(changes)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  var changes = 0
  var counts = Array.ofDim[Int](n)
  data.foreach{i => if (i < 1) {
      counts(0) += 1
      changes += -i + 1
    } else if (i > n) {
      counts(n - 1) += 1
      changes += i - n
    } else {
      counts(i - 1) += 1
    }
  }
  var leftZero = 0
  while (leftZero != n && counts(leftZero) != 0)
    leftZero += 1
  var leftMoreOne = 0
  while (leftMoreOne != n && counts(leftMoreOne) < 2)
    leftMoreOne += 1

  while (leftZero < n && leftMoreOne < n) {

    changes += Math.abs(leftZero - leftMoreOne)
    counts(leftZero) = 1
    while (leftZero != n && counts(leftZero) != 0)
      leftZero += 1
    counts(leftMoreOne) -= 1
    while (leftMoreOne != n && counts(leftMoreOne) < 2)
      leftMoreOne += 1
  }

  println(changes)
}

object CF285C extends App {
  val in = new java.util.Scanner(System.in)
  val out = new java.io.PrintWriter(System.out)

  val n = in.nextInt
  val v = for (i <- 1 to n) yield in.nextInt
  val s = v.sorted.zip(1 to n).map(x => scala.math.abs(x._1 - x._2)).sum
  out.println(s)

  out.flush
}

import scala.io.StdIn

object BuildingPermutation {

  def dist(l:List[Long]):Long = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n
    //
    val minl = ls filter (x=>{x<=1})
    //System.err.println("minl:"+ minl)
    val maxl = ls filter (x=>{x>=n})
    //System.err.println("maxl:" + maxl)
    val midl = ls filter (x=>{x>1 && x<n})
    //System.err.println("midl:" + midl)

    val OneNLeft = OneN filter (x=>{!(midl contains x)})
    //System.err.println("OneNLeft:" + OneNLeft.toList)
    val lowerOneNLeft = OneNLeft take (minl.length)
    //System.err.println("lowerOneNLeft:" + lowerOneNLeft.toList)
    val upperOneNLeft = OneNLeft takeRight (maxl.length)
    //System.err.println("upperOneNLeft:" + upperOneNLeft.toList)

    ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum +
    ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum
  }

  def main(arg:Array[String]){
    val n = StdIn.readLine().toInt;
    val il:List[Long] = (StdIn.readLine().split(" ").map { x => x.toLong }).toList
    println(dist(il))
  }
}

import scala.io.StdIn

object BuildingPermutation {

  def dist(l:List[Int]):Int = {
    val n = l.length
    val ls = l.sorted
    val OneN = 1 to n
    //
    val minl = ls filter (x=>{x<=1})
    System.err.println("minl:"+ minl)
    val maxl = ls filter (x=>{x>=n})
    System.err.println("maxl:" + maxl)
    val midl = ls filter (x=>{x>1 && x<n})
    System.err.println("midl:" + midl)

    val OneNLeft = OneN filter (x=>{!(midl contains x)})
    System.err.println("OneNLeft:" + OneNLeft.toList)
    val lowerOneNLeft = OneNLeft take (minl.length)
    System.err.println("lowerOneNLeft:" + lowerOneNLeft.toList)
    val upperOneNLeft = OneNLeft takeRight (maxl.length)
    System.err.println("upperOneNLeft:" + upperOneNLeft.toList)

    ((lowerOneNLeft zip minl).map { x => x._1 - x._2 }).sum +
    ((maxl zip upperOneNLeft).map {x=>x._1-x._2}).sum
  }

  def main(arg:Array[String]){
    val n = StdIn.readLine().toInt;
    val il:List[Int] = (StdIn.readLine().split(" ").map { x => x.toInt }).toList
    println(dist(il))
  }
}

import annotation.tailrec
import java.io._

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

  val n = readInt
  def ans = readInts.sorted.zip(1 to n).map(_.productIterator.map(_.asInstanceOf[Int]).reduceLeft(_-_).abs).sum

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

import scala.annotation.tailrec
import scala.math._
object C
{
    def main(args: Array[String])
    {
        val n = readLine.toInt
        val a = readLine split(" ") map(_ toInt) sortWith(_ < _)
        @tailrec
        def solve(pos : Int = 0, ans : Int = 0): Int = {
            if(pos<a.length){
                solve(pos+1,ans+abs(a(pos)-(pos+1)))
            }
            else{ans}
        }
        println(solve())
    }
}

object Main {
  def main(args: Array[String]) {
    val n = readLong
    val a = readLine().split(" ").map(_.toLong)
    val step1 = a.foldLeft(0L) { (a, e) =>
      if (e < 1) a + 1 - e
      else if (e > n) a + e - n
      else a
    }
    val a1 = a.map{ e =>
      if (e < 1) 1
      else if (e > n) n
      else e
    }
    val step2 = (a1.sum - n * (n + 1) / 2).abs
    println(step1 + step2)
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt
    val a = readLine().split(" ").map(_.toInt)
    val step1 = a.foldLeft(0) { (a, e) =>
      if (e < 1) a + 1 - e
      else if (e > n) a + e - n
      else a
    }
    val a1 = a.map{ e =>
      if (e < 1) 1
      else if (e > n) n
      else e
    }
    val step2 = (a1.sum - n * (n + 1) / 2).abs
    println(step1 + step2)
  }
}

import scala.annotation.tailrec
import scala.math._
object Main {

  def main(args: Array[String]): Unit = {
    val N = readInt()
    val list = readLine split (" ") map (_ toInt) sortWith (_ < _)
    val dList = 1.to(N).map(i => (list(i - 1) - i).abs);
    print(dList.sum)
  }
}


You are given a string $$$s$$$, consisting of brackets of two types: '(', ')', '[' and ']'.A string is called a regular bracket sequence (RBS) if it's of one of the following types:   empty string;  '(' + RBS + ')';  '[' + RBS + ']';  RBS + RBS. where plus is a concatenation of two strings.In one move you can choose a non-empty subsequence of the string $$$s$$$ (not necessarily consecutive) that is an RBS, remove it from the string and concatenate the remaining parts without changing the order.What is the maximum number of moves you can perform?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains a non-empty string, consisting only of characters '(', ')', '[' and ']'. The total length of the strings over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the maximum number of moves you can perform on a given string $$$s$$$.

NoteIn the first example you can just erase the whole string.In the second example you can first erase the brackets on positions $$$1$$$ and $$$2$$$: "[]()", then "()" is left. After that you can erase it whole. You could erase the whole string from the beginning but you would get one move instead of two.In the third example you can first erase the brackets on positions $$$1$$$ and $$$3$$$: "([)]". They form an RBS "()". Then "[]" is left, so you can erase it whole.In the fourth example there is no subsequence that is an RBS, so you can't perform a move at all.In the fifth example you can erase the brackets on positions $$$2$$$ and $$$4$$$: ")[(]" and get ")(" as a result. You can erase nothing from it.

import scala.io.StdIn._

object Main extends App {
  val t = readInt()
  // val t = 2
  (0 until t).foreach(_ => {
    val s = readLine()
    // val s = "[(])"
    val ans = run(s, '[', ']') + run(s, '(', ')')
    println(ans)
  })

  def run(s: String, a: Char, b: Char): Int = {
    var ans = 0
    var left = 0
    for (c <- s) {
      if (c == a) {
          left += 1
      } else if (c == b && left > 0) {
          ans += 1
          left -= 1
      }
    }
    ans
  }
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App {
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(y => {

    val splitted = readLine().split("")
    var a = 0
    var b = 0
   res(y) = 0
    splitted.foreach(x => {
      if (x == "(")
        a += 1
      else if(x == ")" && a > 0) {
        a-= 1
        res(y) +=1
      }else if(x == "[")
        b +=1
      else if(x == "]" && b > 0){
        b -=1
        res(y) +=1
      }
    })
  })

  (0 until sets).foreach(x => {
    println(res(x))
  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
   // println("        " + a)
    var splitted = readLine().split("")

    while (splitted.contains("[") && splitted.contains("]") ){
      val s = splitted.indexOf("[")
     // println("s: " + s)
      val f = splitted.indexOf("]")
     // println("f: " + f)

      //println(splitted)

     // println(splitted)
     // println()

      if (s< f) {
        res(a) += 1
        //println("+")
        splitted(s) = "a"
        splitted(f) = "a"
      }else{
        splitted(f) = "a"
      }
    }

    while(splitted.contains("(") && splitted.contains(")")) {

      val s = splitted.indexOf("(")
      //println("s: " + s)
      val f = splitted.indexOf(")")
      //println("f: " + f)

      splitted(s) = "a"
      splitted(f) = "a"

      //println(splitted)
     // println()
      if (s< f) {
        res(a) += 1
        //println("+")
        splitted(s) = "a"
        splitted(f) = "a"
      }else{
        splitted(f) = "a"
      }

    }

    /*val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi*/

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

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

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
    val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App {
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(y => {

    val splitted = readLine().split("")
    var a = 0
    var b = 0
   res(y) = 0
    splitted.foreach(x => {
      if (x == "(")
        a += 1
      else if(x == ")" && a > 0) {
        a-= 1
        res(y) +=1
      }else if(x == "[")
        b +=1
      else if(b > 0){
        b -=1
        res(y) +=1
      }
    })
  })

  (0 until sets).foreach(x => {
    println(res(x))
  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

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

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
    var splitted = readLine().split("").toList

    while (splitted.contains("[") && splitted.contains("]") ){
      val s = splitted.indexOf("[")
      val f = splitted.indexOf("]")

      splitted = splitted.drop(s)
      splitted = splitted.drop(f)

      if (s< f) {
        res(a) += 1
      }
    }

    while(splitted.contains("(") && splitted.contains(")")) {

      val s = splitted.indexOf("(")
      val f = splitted.indexOf(")")

      splitted = splitted.drop(s)
      splitted = splitted.drop(f)

      if (s< f) {
        res(a) += 1
      }

    }

    /*val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi*/

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskC extends App{
  val sets = readInt()

  val res = new Array[Int](sets)

  (0 until sets).foreach(a => {
   // println("        " + a)
    var splitted = readLine().split("")

    while (splitted.contains("[") && splitted.contains("]") ){
      val s = splitted.indexOf("[")
     // println("s: " + s)
      val f = splitted.indexOf("]")
     // println("f: " + f)

      //println(splitted)
      splitted(s) = "a"
      splitted(f) = "a"

     // println(splitted)
     // println()

      if (s< f) {
        res(a) += 1
        //println("+")
      }
    }

    while(splitted.contains("(") && splitted.contains(")")) {

      val s = splitted.indexOf("(")
      //println("s: " + s)
      val f = splitted.indexOf(")")
      //println("f: " + f)

      splitted(s) = "a"
      splitted(f) = "a"

      //println(splitted)
     // println()
      if (s< f) {
        res(a) += 1
       // println("+")
      }

    }

    /*val splitted = readLine().split("")
    val oc = splitted.count(x => x == "[")
    val cc = splitted.count(x => x == "]")
    val ob = splitted.count(x => x == "(")
    val cb = splitted.count(x => x == ")")

    var totalc = 0
    var totalb = 0

    var minc = 0
    var minb = 0
    (0 until splitted.length).foreach(x => {
      if(splitted(x) == "]") totalc-=1
      if(splitted(x) == "[") totalc+=1

      if(splitted(x) == ")") totalb-=1
      if(splitted(x) == "(") totalb+=1

      minc = min(totalc, minc)
      minb = min(totalb, minb)
    })

    val resi = min(oc, cc)+minc + min(ob, cb)+minb
    if (resi < 0) res(a) = 0
    else res(a) = resi*/

  })

  (0 until sets).foreach(x => {
    println(res(x))

  })
}


Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:  In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to zero.  When all elements of the array become equal to zero, the array explodes. Nastya is always busy, so she wants to explode the array as fast as possible. Compute the minimum time in which the array can be exploded.

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains n integers a1, a2, ..., an ( - 105 ≤ ai ≤ 105) — the elements of the array.

Print a single integer — the minimum number of seconds needed to make all elements of the array equal to zero.

NoteIn the first example you can add  - 1 to all non-zero elements in one second and make them equal to zero.In the second example you can add  - 2 on the first second, then the array becomes equal to [0, 0,  - 3]. On the second second you can add 3 to the third (the only non-zero) element.

object a992 {
  def main(args: Array[String]): Unit = {
    scala.io.StdIn.readLine()
    println(scala.io.StdIn.readLine().split(" ").filter(_!="0").distinct.length)
  }
}

object A extends App {

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

  val Array(n) = readInts(1)
  val as = readInts(n)

  println(as.filter(_ != 0).distinct.size)
}

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

object Solution {
  def main(args: Array[String]) {
    val n = io.StdIn.readLine.trim.toInt
    val a = io.StdIn.readLine.split(" ").map(_.trim.toInt)

    val set = a.toSet
    if (set.contains(0)) println(set.size - 1)
    else println(set.size)
  }
 }

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

  override def apply(io: IO): io.type = {
    val nums = io.read[Seq[Int]]
    val ans = nums.filter(_ != 0).distinct.size
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val a = StdIn.readLine().split(" ").map(item => item.toInt)
    println(a.distinct.count(item => item != 0))
  }
}

object Main extends App {
  readInt
  val array = readLine.split(" ").map(_.toInt)
  println(array.distinct.length - (if (array.contains(0)) 1 else 0))
}


You are given an undirected connected graph consisting of n vertices and m edges. There are no loops and no multiple edges in the graph.You are also given two distinct vertices s and t, and two values ds and dt. Your task is to build any spanning tree of the given graph (note that the graph is not weighted), such that the degree of the vertex s doesn't exceed ds, and the degree of the vertex t doesn't exceed dt, or determine, that there is no such spanning tree.The spanning tree of the graph G is a subgraph which is a tree and contains all vertices of the graph G. In other words, it is a connected graph which contains n - 1 edges and can be obtained by removing some of the edges from G.The degree of a vertex is the number of edges incident to this vertex.

The first line of the input contains two integers n and m (2 ≤ n ≤ 200 000, 1 ≤ m ≤ min(400 000, n·(n - 1) / 2)) — the number of vertices and the number of edges in the graph.  The next m lines contain the descriptions of the graph's edges. Each of the lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — the ends of the corresponding edge. It is guaranteed that the graph contains no loops and no multiple edges and that it is connected. The last line contains four integers s, t, ds, dt (1 ≤ s, t ≤ n, s ≠ t, 1 ≤ ds, dt ≤ n - 1).

If the answer doesn't exist print "No" (without quotes) in the only line of the output.  Otherwise, in the first line print "Yes" (without quotes). In the each of the next (n - 1) lines print two integers — the description of the edges of the spanning tree. Each of the edges of the spanning tree must be printed exactly once. You can output edges in any order. You can output the ends of each edge in any order. If there are several solutions, print any of them.

import scala.collection.mutable._

object CF375_6B extends App {
  val nm = readLine.split(" ").map(_.toInt)
  val va = new Array[Int](nm(1))
  val vb = new Array[Int](nm(1))
  for (i <- 0 until nm(1)) {
    val ab = readLine.split(" ").map(_.toInt)
    va(i) = ab(0)
    vb(i) = ab(1)
  }
  val spl = readLine.split(" ").map(_.toInt)
  val res = solve(nm(0), va, vb, spl(0), spl(1), spl(2), spl(3))
  if (res == null) {
    println("No");
  } else {
    println("Yes");
    for (ab <- res)
      println(ab._1 + " " + ab._2)
  }

  def solve(n: Int, va: Array[Int], vb: Array[Int], s: Int, t: Int, ds1: Int, dt1: Int): ArrayBuffer[(Int, Int)] = {
    val uf = new UF(n)
    val vs = new ArrayBuffer[Int]()
    val vt = new ArrayBuffer[Int]()
    var st_found = false
    val res = new ArrayBuffer[(Int, Int)]()

    for (i <- 0 until va.length) {
      val (a, b) = (va(i), vb(i))
      if (a == s || b == s) {
        if (a == t || b == t)
          st_found = true
        else
          vs += {if (a == s) b else a}
      } else if (a == t)
        vt += b
      else if (b == t)
        vt += a
      else {
        if (uf.unite(a, b)) {
          res += (a -> b)
        }
      }
    }

    val(rs, rt, rts) = getComp(vs, vt, uf)
    var ds = ds1 - rs.length
    var dt = dt1 - rt.length
    for (i <- rs)
      res += (s -> i)
    for (i <- rt)
      res += (t -> i)

    var f = 0
    if (st_found && rts.length == 0) {
      res += (s -> t)
    }
    else {
      res += (s -> rts(0)._1)
      res += (t -> rts(0)._2)
      f = 1
    }
    ds -= 1
    dt -= 1
    for (i <- f until rts.length) {
     if (ds > 0) {
       ds -= 1
       res += (s -> rts(i)._1)
     } else {
       dt -= 1
       res += (t -> rts(i)._2)
     }
    }

    return if (ds >= 0 && dt >= 0) res else null;
  }

  def toHashMap(v : ArrayBuffer[Int], uf : UF) = {
    var res = new HashMap[Int, Int]()
    for (i <- v)
      res += (uf.getRoot(i) -> i)
    res
  }

  def getComp(vs : ArrayBuffer[Int], vt : ArrayBuffer[Int], uf : UF) = {
    val hs = toHashMap(vs, uf)
    val ht = toHashMap(vt, uf)
    val rs = new ArrayBuffer[Int]()
    val rt = new ArrayBuffer[Int]()
    val rts = new ArrayBuffer[(Int, Int)]()

    for (kv <- hs) {
      if (ht.contains(kv._1)) {
        rts += (kv._2 -> ht(kv._1))
        ht -= kv._1
      }
      else
        rs += kv._2
    }
    for (kv <- ht)
      rt += kv._2
    (rs, rt, rts)
  }
}

class UF(N:Int) {
  private[this] val parents = Array.fill(N+1)(-1)

  def getRoot(x: Int) : Int = {
    var t = x
    while (parents(t) >= 0)
      t = parents(t)
    t
  }

  def sameComponent(x : Int, y : Int) = {
    getRoot(x) == getRoot(y)
  }

  def unite(x : Int, y : Int) : Boolean = {
    val rx = getRoot(x)
    val ry = getRoot(y)
    if (rx == ry)
      return false
    if (parents(rx) < parents(ry)) {
      // y to x
      parents(rx) += parents(ry)
      parents(ry) = rx
    } else {
      // x to y
      parents(ry) += parents(rx)
      parents(rx) = ry
    }
    true
  }
}

import scala.collection.mutable._

object CF375_6B extends App {
  val nm = readLine.split(" ").map(_.toInt)
  val va = new Array[Int](nm(1))
  val vb = new Array[Int](nm(1))
  for (i <- 0 until nm(1)) {
    val ab = readLine.split(" ").map(_.toInt)
    va(i) = ab(0)
    vb(i) = ab(1)
  }
  val spl = readLine.split(" ").map(_.toInt)
  val res = solve(nm(1), va, vb, spl(0), spl(1), spl(2), spl(3))
  if (res == null) {
    println("No");
  } else {
    println("Yes");
    for (ab <- res)
      println(ab._1 + " " + ab._2)
  }

  def solve(n: Int, va: Array[Int], vb: Array[Int], s: Int, t: Int, ds1: Int, dt1: Int): ArrayBuffer[(Int, Int)] = {
    val uf = new UF(n)
    val vs = new ArrayBuffer[Int]()
    val vt = new ArrayBuffer[Int]()
    var st_found = false
    val res = new ArrayBuffer[(Int, Int)]()

    for (i <- 0 until va.length) {
      val (a, b) = (va(i), vb(i))
      if (a == s || b == s) {
        if (a == t || b == t)
          st_found = true
        else
          vs += {if (a == s) b else a}
      } else if (a == t)
        vt += b
      else if (b == t)
        vt += a
      else {
        if (uf.unite(a, b)) {
          res += (a -> b)
        }
      }
    }

    val(rs, rt, rts) = getComp(vs, vt, uf)
    var ds = ds1 - rs.length
    var dt = dt1 - rt.length
    for (i <- rs) {
      res += (s -> i)
      ds -= 1;
    }
    for (i <- rt) {
      res += (t -> i)
      dt -= 1
    }

    var f = 0
    if (st_found && rts.length == 0) {
      res += (s -> t)
    }
    else {
      res += (s -> rts(0)._1)
      res += (t -> rts(0)._2)
      f = 1
    }
    ds -= 1
    dt -= 1
    for (i <- f until rts.length) {
     if (ds > 0) {
       ds -= 1
       res += (s -> rts(i)._1)
     } else {
       dt -= 1
       res += (t -> rts(i)._2)
     }
    }

    return if (ds >= 0 && dt >= 0) res else null;
  }

  def toHashMap(v : ArrayBuffer[Int], uf : UF) = {
    var res = new HashMap[Int, Int]()
    for (i <- v)
      res += (uf.getRoot(i) -> i)
    res
  }

  def getComp(vs : ArrayBuffer[Int], vt : ArrayBuffer[Int], uf : UF) = {
    val hs = toHashMap(vs, uf)
    val ht = toHashMap(vt, uf)
    val rs = new ArrayBuffer[Int]()
    val rt = new ArrayBuffer[Int]()
    val rts = new ArrayBuffer[(Int, Int)]()

    for (kv <- hs) {
      if (ht.contains(kv._1)) {
        rts += (kv._2 -> ht(kv._1))
        ht -= kv._1
      }
      else
        rs += kv._2
    }
    for (kv <- ht)
      rt += kv._2
    (rs, rt, rts)
  }
}

class UF(N:Int) {
  private[this] val parents = Array.fill(N+1)(-1)

  def getRoot(x: Int) : Int = {
    var t = x
    while (parents(t) >= 0)
      t = parents(t)
    t
  }

  def sameComponent(x : Int, y : Int) = {
    getRoot(x) == getRoot(y)
  }

  def unite(x : Int, y : Int) : Boolean = {
    val rx = getRoot(x)
    val ry = getRoot(y)
    if (rx == ry)
      return false
    if (parents(rx) < parents(ry)) {
      // y to x
      parents(rx) += parents(ry)
      parents(ry) = rx
    } else {
      // x to y
      parents(ry) += parents(rx)
      parents(rx) = ry
    }
    true
  }
}


In some country there are exactly n cities and m bidirectional roads connecting the cities. Cities are numbered with integers from 1 to n. If cities a and b are connected by a road, then in an hour you can go along this road either from city a to city b, or from city b to city a. The road network is such that from any city you can get to any other one by moving along the roads.You want to destroy the largest possible number of roads in the country so that the remaining roads would allow you to get from city s1 to city t1 in at most l1 hours and get from city s2 to city t2 in at most l2 hours.Determine what maximum number of roads you need to destroy in order to meet the condition of your plan. If it is impossible to reach the desired result, print -1.

The first line contains two integers n, m (1 ≤ n ≤ 3000, ) — the number of cities and roads in the country, respectively.  Next m lines contain the descriptions of the roads as pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi). It is guaranteed that the roads that are given in the description can transport you from any city to any other one. It is guaranteed that each pair of cities has at most one road between them. The last two lines contains three integers each, s1, t1, l1 and s2, t2, l2, respectively (1 ≤ si, ti ≤ n, 0 ≤ li ≤ n).

Print a single number — the answer to the problem. If the it is impossible to meet the conditions, print -1.

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.immutable.Queue
import scala.collection.mutable.ArrayBuffer

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def lowerBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (!(array(mid) < value)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  var graph: Array[ArrayBuffer[Int]] = null

  def Bfs(start: Int, dist: Array[Int]): Unit = {
    var queue = collection.mutable.Queue.empty[Int]
    dist(start) = 0
    queue += start
    while (queue.nonEmpty) {
      val start = queue.front
      queue = queue.tail
      graph(start).foreach(i =>
        if (dist(i) > dist(start) + 1) {
          dist(i) = dist(start) + 1
          queue += i
        }
      )
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[ArrayBuffer[Int]](n)
    Range(0, n).foreach(
      graph(_) = new ArrayBuffer[Int]()
    )

    Range(0, m).foreach(i => {
      var (a, b) = (nextInt - 1, nextInt - 1)
      graph(a) += b
      graph(b) += a
    })

    val dist = Array.fill[Int](n, n)(n + 1)
    Range(0, n).foreach(i => Bfs(i, dist(i)))

    val (s0, t0, l0) = (nextInt - 1, nextInt - 1, nextInt)
    val (s1, t1, l1) = (nextInt - 1, nextInt - 1, nextInt)
    if (dist(s0)(t0) > l0 || dist(s1)(t1) > l1) {
      out.println(-1)
    } else {
      var res = dist(s0)(t0) + dist(s1)(t1)
      for (i <- Range(0, n); j <- Range(i + 1, n)) {
        val d0 = math.min(dist(s0)(i) + dist(i)(j) + dist(j)(t0),
          dist(s0)(j) + dist(j)(i) + dist(i)(t0))
        val d1 = math.min(dist(s1)(i) + dist(i)(j) + dist(j)(t1),
          dist(s1)(j) + dist(j)(i) + dist(i)(t1))
        if (d0 <= l0 && d1 <= l1) {
          res = math.min(res, d0 + d1 - dist(i)(j))
        }
      }
      out.println(m - res)
    }
  }

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

/**
 *
 * Created by ronaflx on 15-4-3.
 */

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

import scala.Ordering.Implicits._
import scala.collection.immutable.Queue
import scala.collection.mutable.ArrayBuffer

object Codeforces {
  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

  def lowerBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (!(array(mid) < value)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  def upperBound[T: Ordering](array: Array[T], value: T) = {
    var low = 0
    var high = array.length
    var res = array.length
    while (low <= high) {
      val mid = (low + high) / 2
      if (value < array(mid)) {
        res = mid
        high = mid - 1
      } else {
        low = mid + 1
      }
    }
    res
  }

  var graph: Array[ArrayBuffer[Int]] = null

  def Bfs(start: Int, dist: Array[Int]): Unit = {
    var queue = collection.mutable.Queue.empty[Int]
    dist(start) = 0
    queue += start
    while (queue.nonEmpty) {
      val start = queue.front
      queue = queue.tail
      graph(start).foreach(i =>
        if (dist(i) > dist(start) + 1) {
          dist(i) = dist(start) + 1
          queue += i
        }
      )
    }
  }

  def solve(): Unit = {
    val (n, m) = (nextInt, nextInt)
    graph = new Array[ArrayBuffer[Int]](n)
    Range(0, n).foreach(
      graph(_) = new ArrayBuffer[Int]()
    )

    Range(0, m).foreach(i => {
      var (a, b) = (nextInt - 1, nextInt - 1)
      graph(a) += b
      graph(b) += a
    })

    val dist = Array.fill[Int](n, n)(n + 1)
    Range(0, n).foreach(i => Bfs(i, dist(i)))

    val (s0, t0, l0) = (nextInt - 1, nextInt - 1, nextInt)
    val (s1, t1, l1) = (nextInt - 1, nextInt - 1, nextInt)
    if (dist(s0)(t0) > l0 || dist(s1)(t1) > l1) {
      out.println(-1)
    } else {
      var res = dist(s0)(t0) + dist(s1)(t1)
      for (i <- Range(0, n); j <- Range(i + 1, n)) {
        if ((dist(s0)(i) + dist(i)(j) + dist(j)(t0) <= l0 ||
          dist(s0)(j) + dist(j)(i) + dist(i)(t0) <= l0) &&
          (dist(s1)(i) + dist(i)(j) + dist(j)(t1) <= l1 ||
            dist(s1)(j) + dist(j)(i) + dist(i)(t1) <= l1)) {
          res = math.min(res, dist(s0)(t0) + dist(s1)(t1) - dist(i)(j))
        }
      }
      out.println(m - res)
    }
  }

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


Phoenix has $$$n$$$ blocks of height $$$h_1, h_2, \dots, h_n$$$, and all $$$h_i$$$ don't exceed some value $$$x$$$. He plans to stack all $$$n$$$ blocks into $$$m$$$ separate towers. The height of a tower is simply the sum of the heights of its blocks. For the towers to look beautiful, no two towers may have a height difference of strictly more than $$$x$$$. Please help Phoenix build $$$m$$$ towers that look beautiful. Each tower must have at least one block and all blocks must be used.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$x$$$ ($$$1 \le m \le n \le 10^5$$$; $$$1 \le x \le 10^4$$$) — the number of blocks, the number of towers to build, and the maximum acceptable height difference of any two towers, respectively.  The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le h_i \le x$$$) — the heights of the blocks.  It is guaranteed that the sum of $$$n$$$ over all the test cases will not exceed $$$10^5$$$.

For each test case, if Phoenix cannot build $$$m$$$ towers that look beautiful, print NO. Otherwise, print YES, followed by $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$, where $$$y_i$$$ ($$$1 \le y_i \le m$$$) is the index of the tower that the $$$i$$$-th block is placed in. If there are multiple solutions, print any of them.

NoteIn the first test case, the first tower has height $$$1+2+3=6$$$ and the second tower has height $$$1+2=3$$$. Their difference is $$$6-3=3$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.In the second test case, the first tower has height $$$1$$$, the second tower has height $$$1+2=3$$$, and the third tower has height $$$3$$$. The maximum height difference of any two towers is $$$3-1=2$$$ which doesn't exceed $$$x=3$$$, so the towers are beautiful.

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val n, m, x = nextInt
      val hs = nextInts(n).zipWithIndex.sorted.reverse
      val res = Array.ofDim[Int](n)
      val towers = Array.fill(m)(0L)

      val pq = new mutable.PriorityQueue[Int]()(Ordering.by(towers).reverse)
      for (i <- 0 until m) {
        res(hs(i)._2) = i + 1
        towers(i) = hs(i)._1
        pq += i
      }
      var i = m
      while (i < n) {
        val t = pq.dequeue()
        res(hs(i)._2) = t + 1
        towers(t) += hs(i)._1
        pq += t
        i += 1
      }
      val ok = (towers.max - towers.min) <= x
      if (ok) {
        out.println("YES")
        out.println(res.mkString(" "))
      } else {
        out.println("NO")
      }
    }

    out.flush()
  }

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


You have a playlist consisting of $$$n$$$ songs. The $$$i$$$-th song is characterized by two numbers $$$t_i$$$ and $$$b_i$$$ — its length and beauty respectively. The pleasure of listening to set of songs is equal to the total length of the songs in the set multiplied by the minimum beauty among them. For example, the pleasure of listening to a set of $$$3$$$ songs having lengths $$$[5, 7, 4]$$$ and beauty values $$$[11, 14, 6]$$$ is equal to $$$(5 + 7 + 4) \cdot 6 = 96$$$.You need to choose at most $$$k$$$ songs from your playlist, so the pleasure of listening to the set of these songs them is maximum possible.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$) – the number of songs in the playlist and the maximum number of songs you can choose, respectively. Each of the next $$$n$$$ lines contains two integers $$$t_i$$$ and $$$b_i$$$ ($$$1 \le t_i, b_i \le 10^6$$$) — the length and beauty of $$$i$$$-th song.

Print one integer — the maximum pleasure you can get.

NoteIn the first test case we can choose songs $$${1, 3, 4}$$$, so the total pleasure is $$$(4 + 3 + 6) \cdot 6 = 78$$$.In the second test case we can choose song $$$3$$$. The total pleasure will be equal to $$$100 \cdot 100 = 10000$$$.

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

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

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

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

  def solve(): Unit = {
    import java.util.Comparator
    val N, K = ni()
    case class Song(t: Int, b: Int) extends Comparable[Song] {
      override def compareTo(o: Song): Int = Integer.compare(t, o.t) // PriorityQueueでtが低い順に抜けていって欲しい
    }

    val S = Array.ofDim[Song](N)
    REP(N) { i =>
      val t, b = ni()
      S(i) = Song(t, b)
    }

    // bの降順で並べる
    Arrays.sort(S, new Comparator[Song] {
      override def compare(o1: Song, o2: Song): Int = Integer.compare(o2.b, o1.b)
    })

    debug(S.mkString(","))

    val q = new java.util.PriorityQueue[Song]
    var ans = 0L
    var s = 0L
    REP(N) { i =>
      if (i < K) {
        s += S(i).t
        q.add(S(i))
        ans = max(ans, s * S(i).b) // 数がK以下のときはbが大きい順に選ぶだけ。そうでないと数を増やした方が得になる
      } else {
        q.add(S(i))
        s += S(i).t
        s -= q.poll().t
        ans = max(ans, s * S(i).b)
      }
    }
    out.println(ans)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

  def debug(as: Array[Boolean]): Unit = DEBUG {
    debug(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = DEBUG {
    debug(as.mkString(" "))
  }

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

import scala.collection.mutable

object C extends App {

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

  case class Song(t: Long, b: Long)

  val Array(n, k) = readInts(2)
  val songs = Array.fill(n) {
    val Array(t, b) = readLongs(2)
    Song(t, b)
  }.sortBy(-_.b)

  var max = 0L
  val pq = new mutable.PriorityQueue[Song]()(Ordering.by(-_.t))
  var len = 0L

  for (song <- songs) {
    pq += song
    len += song.t
    if (pq.size > k) {
      val r = pq.dequeue()
      len -= r.t
    }
    val score = song.b * len
    if (score > max) max = score
  }

  println(max)
}

import scala.collection.mutable

object C extends App {

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

  case class Song(t: Long, b: Long)

  val Array(n, k) = readInts(2)
  val songs = Array.fill(n) {
    val Array(t, b) = readLongs(2)
    Song(t, b)
  }.sortBy(-_.b)

  var max = 0L
  val pq = new mutable.PriorityQueue[Song]()(Ordering.by(-_.b))
  var len = 0L

  for (song <- songs) {
    pq += song
    len += song.t
    if (pq.size > k) {
      val r = pq.dequeue()
      len -= r.t
    }
    val score = song.b * len
    if (score > max) max = score
  }

  println(max)
}

import scala.collection.mutable

object C extends App {

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

  case class Song(t: Long, b: Long)

  val Array(n, k) = readInts(2)
  val songs = Array.fill(n) {
    val Array(t, b) = readLongs(2)
    Song(t, b)
  }.sortBy(-_.b)

  var max = 0L
  val pq = new mutable.PriorityQueue[Song]()(Ordering.by(_.b))
  var len = 0L

  for (song <- songs) {
    pq += song
    len += song.t
    if (pq.size > k) {
      val r = pq.dequeue()
      len -= r.t
    }
    val score = song.b * len
    if (score > max) max = score
  }

  println(max)
}


You are given an array $$$a$$$ of length $$$n$$$ consisting of zeros. You perform $$$n$$$ actions with this array: during the $$$i$$$-th action, the following sequence of operations appears:  Choose the maximum by length subarray (continuous subsegment) consisting only of zeros, among all such segments choose the leftmost one;  Let this segment be $$$[l; r]$$$. If $$$r-l+1$$$ is odd (not divisible by $$$2$$$) then assign (set) $$$a[\frac{l+r}{2}] := i$$$ (where $$$i$$$ is the number of the current action), otherwise (if $$$r-l+1$$$ is even) assign (set) $$$a[\frac{l+r-1}{2}] := i$$$. Consider the array $$$a$$$ of length $$$5$$$ (initially $$$a=[0, 0, 0, 0, 0]$$$). Then it changes as follows:  Firstly, we choose the segment $$$[1; 5]$$$ and assign $$$a[3] := 1$$$, so $$$a$$$ becomes $$$[0, 0, 1, 0, 0]$$$;  then we choose the segment $$$[1; 2]$$$ and assign $$$a[1] := 2$$$, so $$$a$$$ becomes $$$[2, 0, 1, 0, 0]$$$;  then we choose the segment $$$[4; 5]$$$ and assign $$$a[4] := 3$$$, so $$$a$$$ becomes $$$[2, 0, 1, 3, 0]$$$;  then we choose the segment $$$[2; 2]$$$ and assign $$$a[2] := 4$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 0]$$$;  and at last we choose the segment $$$[5; 5]$$$ and assign $$$a[5] := 5$$$, so $$$a$$$ becomes $$$[2, 4, 1, 3, 5]$$$. Your task is to find the array $$$a$$$ of length $$$n$$$ after performing all $$$n$$$ actions. Note that the answer exists and unique.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the array $$$a$$$ of length $$$n$$$ after performing $$$n$$$ actions described in the problem statement. Note that the answer exists and unique.

//package codeforces.contests._1353

object ConstructingTheArray {

  import math.abs
  import scala.collection.mutable

  def main(args: Array[String]): Unit = {
    println {
      {
        for (_ <- 1 to io.StdIn.readInt) yield {
          val n = io.StdIn.readInt

          val arr = new Array[Int](n)

          implicit val tuple2Ordering: Ordering[(Int, Int)] = Ordering.fromLessThan[(Int, Int)] {
            case ((x, y), (l, r)) =>
              if (abs(x - y) == abs(l - r)) x > l else abs(x - y) < abs(l - r)
          }

          val queue = mutable.PriorityQueue[(Int, Int)](1 -> n)

          @scala.annotation.tailrec
          def loop(i: Int): Unit =
            if (i <= n) {
              val (l, r) = queue.dequeue()
              val m = (l + r) / 2

              arr(m - 1) = i

              if (l != m)
                queue.enqueue(l -> (m - 1))
              if (l != r)
                queue.enqueue((m + 1) -> r)

              loop(i + 1)
            }

          loop(1)

          arr.mkString(" ")
        }
      }.mkString("\n")
    }

  }
}

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

object D {

  def solution(n: Int): Array[Int] = {
    val result = Array.ofDim[Int](n)
    val subsByLength =
      mutable.SortedMap((n - 1) -> mutable.SortedSet(0))

    def add(length: Int, start: Int): Unit =
      subsByLength
        .getOrElseUpdate(length - 1, mutable.SortedSet.empty[Int])
        .add(start)

    var iteration = 1
    while (subsByLength.nonEmpty) {
      val length = subsByLength.lastKey + 1
      subsByLength.remove(length - 1).foreach { subs =>
        subs.foreach { start =>
          length match {
            case 1 =>
              result(start) = iteration
            case 2 =>
              result(start) = iteration
              add(1, start + 1)
            case _ =>
              val halfLength = length / 2
              if (length % 2 == 0) {
                add(halfLength - 1, start)
                result(start + halfLength - 1) = iteration
                add(halfLength, start + halfLength)
              } else {
                add(halfLength, start)
                result(start + halfLength) = iteration
                add(halfLength, start + halfLength + 1)
              }
          }
          iteration += 1
        }
      }
    }
    result
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val n = readLine.toInt
      println(solution(n).mkString(" "))
    }
  }
}

object D extends App {
  import InOut._
  import scala.collection.mutable.TreeSet

  object SegOrdering extends Ordering[(Int, Int)] {
    implicit def compare(x: (Int, Int), y: (Int, Int)): Int = {
      val (l1, r1)     = x
      val (l2, r2)     = y
      val (len1, len2) = (r1 - l1 + 1, r2 - l2 + 1)

      if (len1 > len2) -1
      else if (len1 < len2) 1
      else if (l1 < l2) -1
      else if (l1 > l2) 1
      else 0
    }
  }

  val t = nextInt

  (0 until t).foreach { _ =>
    val n = nextInt

    var an   = Array.ofDim[Int](n)
    var segs = TreeSet[(Int, Int)]((0, n - 1))(SegOrdering)

    (1 to n).foreach { v =>
      val (l, r) = segs.head

      val i = (l + r) / 2

      segs -= ((l, r))
      if (i > l) segs += ((l, i - 1))
      if (i < r) segs += ((i + 1, r))

      an(i) = v
    }

    out.println(an.mkString(" "))
    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 ProblemDD extends App {
  import java.io.{BufferedReader, IOException, 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;
    }
  }

  case class SmartPair(left: Int, right: Int) {
    val size: Int = right - left
  }

  implicit val ordering: Ordering[SmartPair] = new Ordering[SmartPair]() {
    override def compare(x: SmartPair, y: SmartPair): Int = if (x.size != y.size) {
      y.size - x.size
    } else {
      x.left - y.left
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    val n = in.nextInt()

    val result = new Array[Int](n)

    val pairs = scala.collection.mutable.SortedSet[SmartPair]()
    pairs += SmartPair(1, n)
    var step = 1
    while (pairs.nonEmpty) {
      val xy = pairs.head
      val x = xy.left
      val y = xy.right
      pairs.remove(xy)

      if (x <= y) {
        if ((y - x + 1) % 2 == 1) {
          val mid = (y + x) / 2
          result(mid - 1) = step
          if (y != x) {
            pairs += SmartPair(x, mid - 1)
            pairs += SmartPair(mid + 1, y)
          }
        } else {
          val mid = (y + x - 1) / 2
          result(mid - 1) = step
          pairs += SmartPair(mid + 1, y)
          pairs += SmartPair(x, mid - 1)
        }
        step = step + 1
      }

    }

    println(result.mkString(" "))
  }

}

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

object D {

  def solution(n: Int): Seq[Int] = {
    val a = Array.fill(n)(0)
    val m = mutable.Map(n -> mutable.Set(0))
    for(i <- 0 until n)
      m(i) = mutable.Set.empty[Int]
    var (len, i) = (n, 1)
    while (len > 0) {
      m.remove(len).foreach { s =>
        s.toSeq.sorted.foreach { start =>
          val l2 = len / 2
          if (len % 2 == 0) {
            m(l2 - 1).add(start)
            a(start + l2 - 1) = i
            m(l2).add(start + l2)
          } else {
            m(l2).add(start)
            a(start + l2) = i
            m(l2).add(start + l2 + 1)
          }
          i += 1
        }
      }
      len -= 1
    }
    a.toSeq
  }

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


Petya got an array $$$a$$$ of numbers from $$$1$$$ to $$$n$$$, where $$$a[i]=i$$$.He performed $$$n$$$ operations sequentially. In the end, he received a new state of the $$$a$$$ array.At the $$$i$$$-th operation, Petya chose the first $$$i$$$ elements of the array and cyclically shifted them to the right an arbitrary number of times (elements with indexes $$$i+1$$$ and more remain in their places). One cyclic shift to the right is such a transformation that the array $$$a=[a_1, a_2, \dots, a_n]$$$ becomes equal to the array $$$a = [a_i, a_1, a_2, \dots, a_{i-2}, a_{i-1}, a_{i+1}, a_{i+2}, \dots, a_n]$$$.For example, if $$$a = [5,4,2,1,3]$$$ and $$$i=3$$$ (that is, this is the third operation), then as a result of this operation, he could get any of these three arrays:  $$$a = [5,4,2,1,3]$$$ (makes $$$0$$$ cyclic shifts, or any number that is divisible by $$$3$$$);  $$$a = [2,5,4,1,3]$$$ (makes $$$1$$$ cyclic shift, or any number that has a remainder of $$$1$$$ when divided by $$$3$$$);  $$$a = [4,2,5,1,3]$$$ (makes $$$2$$$ cyclic shifts, or any number that has a remainder of $$$2$$$ when divided by $$$3$$$). Let's look at an example. Let $$$n=6$$$, i.e. initially $$$a=[1,2,3,4,5,6]$$$. A possible scenario is described below.  $$$i=1$$$: no matter how many cyclic shifts Petya makes, the array $$$a$$$ does not change.  $$$i=2$$$: let's say Petya decided to make a $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{2}, \textbf{1}, 3, 4, 5, 6]$$$.  $$$i=3$$$: let's say Petya decided to make $$$1$$$ cyclic shift, then the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{1}, 4, 5, 6]$$$.  $$$i=4$$$: let's say Petya decided to make $$$2$$$ cyclic shifts, the original array will look like $$$a = [\textbf{1}, \textbf{4}, \textbf{3}, \textbf{2}, 5, 6]$$$.  $$$i=5$$$: let's say Petya decided to make $$$0$$$ cyclic shifts, then the array won't change.  $$$i=6$$$: let's say Petya decided to make $$$4$$$ cyclic shifts, the array will look like $$$a = [\textbf{3}, \textbf{2}, \textbf{5}, \textbf{6}, \textbf{1}, \textbf{4}]$$$. You are given a final array state $$$a$$$ after all $$$n$$$ operations. Determine if there is a way to perform the operation that produces this result. In this case, if an answer exists, print the numbers of cyclical shifts that occurred during each of the $$$n$$$ operations.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases in the test. The descriptions of the test cases follow. The first line of the description of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2\cdot10^3$$$) — the length of the array $$$a$$$. The next line contains the final state of the array $$$a$$$: $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) are written. All $$$a_i$$$ are distinct. It is guaranteed that the sum of $$$n$$$ values over all test cases does not exceed $$$2\cdot10^3$$$.

For each test case, print the answer on a separate line. Print -1 if the given final value $$$a$$$ cannot be obtained by performing an arbitrary number of cyclic shifts on each operation. Otherwise, print $$$n$$$ non-negative integers $$$d_1, d_2, \dots, d_n$$$ ($$$d_i \ge 0$$$), where $$$d_i$$$ means that during the $$$i$$$-th operation the first $$$i$$$ elements of the array were cyclic shifted to the right $$$d_i$$$ times. If there are several possible answers, print the one where the total number of shifts is minimal (that is, the sum of $$$d_i$$$ values is the smallest). If there are several such answers, print any of them.

NoteThe first test case matches the example from the statement.The second set of input data is simple. Note that the answer $$$[3, 2, 1]$$$ also gives the same permutation, but since the total number of shifts $$$3+2+1$$$ is greater than $$$0+0+1$$$, this answer is not correct.

object Solution {

  import scala.io.StdIn.readLine

  def rotate(i: Int, xs: List[Int]): List[Int] = {
    if (i == 1) List(0)
    else {
      val idx = xs.indexOf(i)
      if (idx + 1 == i) 0 :: rotate(i - 1, xs.take(xs.length - 1))
      else {
        val (left, right) = xs.splitAt(idx)
        val nxs = right.drop(1) ++ left
        left.length + 1 :: rotate(i - 1, nxs)
      }
    }
  }

  def f() = {
    val i = readLine().toInt
    val xs = readLine().split("\\s+").map(_.toInt).toList
    println(rotate(i, xs).reverse.mkString(" "))
  }

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

    val cases = readLine().toInt
    for (
      i <- 0 until cases
    ) f()

  }

}


Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the impulse of You-Know-Who's magic spell flies at a speed of q meters per second.The impulses are moving through the corridor toward each other, and at the time of the collision they turn round and fly back to those who cast them without changing their original speeds. Then, as soon as the impulse gets back to it's caster, the wizard reflects it and sends again towards the enemy, without changing the original speed of the impulse.Since Harry has perfectly mastered the basics of magic, he knows that after the second collision both impulses will disappear, and a powerful explosion will occur exactly in the place of their collision. However, the young wizard isn't good at math, so he asks you to calculate the distance from his position to the place of the second meeting of the spell impulses, provided that the opponents do not change positions during the whole fight.

The first line of the input contains a single integer l (1 ≤ l ≤ 1 000) — the length of the corridor where the fight takes place. The second line contains integer p, the third line contains integer q (1 ≤ p, q ≤ 500) — the speeds of magical impulses for Harry Potter and He-Who-Must-Not-Be-Named, respectively.

Print a single real number — the distance from the end of the corridor, where Harry is located, to the place of the second meeting of the spell impulses. Your answer will be considered correct if its absolute or relative error will not exceed 10 - 4.  Namely: let's assume that your answer equals a, and the answer of the jury is b. The checker program will consider your answer correct if .

NoteIn the first sample the speeds of the impulses are equal, so both of their meetings occur exactly in the middle of the corridor.

import scala.io.StdIn._
object program {
	def main(args: Array[String]) {
		var l = readInt(); var a = readInt(); var b = readInt()
		println((l.toDouble/ (a + b)) * a);
	}
}

import java.nio.channels.Pipe.SourceChannel

import scala.math._
import scala.io._

object A5 {
  def solution(d : Int, s1 : Int, s2 : Int) : Double = {
    val (ds1,ds2, maxs) = (s1.toDouble, s2.toDouble, max(s1,s2).toDouble)
    val b = Iterator.iterate((0.0,0.0))(a =>(a._1 + ds1/maxs/10000, a._2+ds2/maxs/10000)).dropWhile(a=>a._1 +a._2 < d).take(1).toArray
    b(0)._1
  }
  def main(args: Array[String]): Unit = {
   val xs = Source.stdin.getLines().take(3).map(_.toInt).toArray
    //assert(abs(solution(100,50,50)-50) < 1e-4)
    //assert(abs(solution(199,60,40)-119.4)<1e-4)
    println(solution(xs(0),xs(1), xs(2)))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val l = in.next().toInt
  val p = in.next().toInt
  val q = in.next().toInt
  println(p * l / (p + q).toFloat)
}

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

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(l) = readInts(1)
    val Array(p) = readInts(1)
    val Array(q) = readInts(1)

    println((p.toDouble * l)/(p.toDouble + q.toDouble))
  }
}

import scala.collection._

object A extends App {

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

  val Array(l) = readDoubles(1)
  val Array(p) = readDoubles(1)
  val Array(q) = readDoubles(1)

  val t = l / (p + q)

  println(p * t)
}

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

object A {

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

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  def solve: Int = {
    val l = nextInt
    val p = nextInt
    val q = nextInt
    val t = (1.0d * l) / (1.0d * p + q * 1.0d)
    val first = 1.0d * t * p
    println(first)
    return 0
  }
}

import scala.annotation.tailrec
import scala.collection.mutable
import scala.util._
import scala.math.Ordering.Implicits._

import CodeForcesApp._

object _591A extends CodeForcesApp {
  override type Result = Double

  override def solve(scanner: Scanner) = {
    import scanner._
    val (l, p, q) = (nextInt(), nextInt(), nextInt())
    p*l.toDouble/(p + q)
  }

  override def format(result: Result) = super.format(result)
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String = result.toString
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val mod: Int = 1000000007
  final val eps: Double = 1e-9
  @inline final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  @inline final def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  @inline final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}
/********************************[Scala Scanner]*********************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/7018
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines: Iterator[String] = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  def tokens: Iterator[String] = for {
    line <- lines
    tokenizer = new StringTokenizer(line)
    _ <- Iterator.continually(tokenizer).takeWhile(_.hasMoreTokens)
  } yield tokenizer.nextToken()

  private[this] var current = tokens
  override def hasNext = current.hasNext
  @inline override def next() = current.next()

  /**
   * @return Unlike the Java scanner which returns till end of current line, this actually returns the next line
   */
  def nextLine(): String = {
    current = tokens   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def nextString(): String = next()
  def nextChar(): Char = next().head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

import scala.io.StdIn._

object A extends App {
  val L = readLine().toInt
  val p = readLine().toInt
  val q = readLine().toInt

  val t = L * 1.0 / (p + q)
  val answer = p * t
  println("%.4f".format(answer))
}

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

object A {

  def main(args: Array[String]): Unit = {
    var debugV = false
    def db(x: => String) = if (debugV)  println(x) // nullary function

    val is = System.in

    //COMMENT ME !
//    val is = new ByteArrayInputStream(sa1.trim.getBytes("ISO-8859-1"))
//    debugV = true

    val bis = new BufferedInputStream(is);
    val br = new BufferedReader(new InputStreamReader(bis));

    //---------------------------- parameters reading ------------------------------------
    val l = br.readLine().toInt
    val p = br.readLine().toInt
    val q = br.readLine().toInt
    //---------------------------- parameters reading end --------------------------------

    val sumSpeed = p + q
    val firstColT = l/sumSpeed.toDouble
    val distP1 = firstColT * p
    val secondColT = (l*2) / sumSpeed.toDouble
    val distP2 = (p*secondColT - distP1)

    println(distP2)
  }

//========================= samples ========================
val sa1 = """

"""

//========================= samples end ====================
}

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

object Codeforces591A extends App {
  def Harry(l: Double, p: Int, q: Int): Double = {
    val time = l / (p + q)
    p * time
  }

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

  val l = in.nextInt
  val p = in.nextInt
  val q = in.nextInt

  print(Harry(l, p, q))
}

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

object Codeforces591A extends App {
  def Harry(l: Double, p: Int, q: Int): Double = {
    val time = l / (p + q)
    p * time
  }

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

  val l = in.nextInt
  val p = in.nextInt
  val q = in.nextInt

  out.write(Harry(l, p, q).toString)
}


$$$ \def\myred#1{\color{red}{\underline{\bf{#1}}}} \def\myblue#1{\color{blue}{\overline{\bf{#1}}}} $$$ $$$\def\RED{\myred{Red}} \def\BLUE{\myblue{Blue}}$$$You are given a sequence of $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Initially, all the elements of the sequence are unpainted. You can paint each number $$$\RED$$$ or $$$\BLUE$$$ (but not both), or leave it unpainted. For a color $$$c$$$, $$$\text{Count}(c)$$$ is the number of elements in the sequence painted with that color and $$$\text{Sum}(c)$$$ is the sum of the elements in the sequence painted with that color.For example, if the given sequence is $$$[2, 8, 6, 3, 1]$$$ and it is painted this way: $$$[\myblue{2}, 8, \myred{6}, \myblue{3}, 1]$$$ (where $$$6$$$ is painted red, $$$2$$$ and $$$3$$$ are painted blue, $$$1$$$ and $$$8$$$ are unpainted) then $$$\text{Sum}(\RED)=6$$$, $$$\text{Sum}(\BLUE)=2+3=5$$$, $$$\text{Count}(\RED)=1$$$, and $$$\text{Count}(\BLUE)=2$$$.Determine if it is possible to paint the sequence so that $$$\text{Sum}(\RED) > \text{Sum}(\BLUE)$$$ and $$$\text{Count}(\RED) < \text{Count}(\BLUE)$$$.

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 an integer $$$n$$$ ($$$3\le n\le 2\cdot 10^5$$$) — the length of the given sequence.  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 given sequence. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print YES if it is possible to paint the given sequence satisfying the above requirements, and NO otherwise. You can output YES and NO in any case (for example, strings yEs, yes, Yes and YES will be recognized as a positive response).

NoteIn the first test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\myblue{1},\myblue{2},\myred{3}]$$$ (where $$$3$$$ is painted red, $$$1$$$ and $$$2$$$ are painted blue) then $$$\text{Count}(\RED)=1 < \text{Count}(\BLUE)=2$$$, but $$$\text{Sum}(\RED)=3 \ngtr \text{Sum}(\BLUE)=3$$$. So, this is not a possible way to paint the sequence.In the second test case, a possible way to paint the sequence is described in the statement. We can see that $$$\text{Sum}(\RED)=6 > \text{Sum}(\BLUE)=5$$$ and $$$\text{Count}(\RED)=1 < \text{Count}(\BLUE)=2$$$.In the third test case, there is no possible way to paint the sequence. For example, if you paint the sequence this way: $$$[\myred{3},\myred{5},\myblue{4}, \myblue{2}]$$$ (where $$$3$$$ and $$$5$$$ are painted red, $$$4$$$ and $$$2$$$ are painted blue) then $$$\text{Sum}(\RED) = 8 > \text{Sum}(\BLUE) = 6$$$ but $$$\text{Count}(\RED) = 2 \nless \text{Count}(\BLUE) = 2$$$. So, this is not a possible way to paint the sequence.In the fourth test case, it can be proven that there is no possible way to paint the sequence satisfying sum and count constraints.

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import scala.collection.mutable.ArrayBuffer

object QualityVsQuantity {
  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                            val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//                "4\n3\n1 2 3\n5\n2 8 6 3 1\n4\n3 5 4 2\n5\n1000000000 1000000000 1000000000 1000000000 1000000000".getBytes)))

    var t = file.readLine.toInt
    while (t > 0) {
      t = t - 1
      file.readLine
      val nums = file.readLine.split(" ").map(_.toLong)
      val s = nums.sorted
      if (s.length == 3) {
        if (s(2) > s(0) + s(1)) println("yes")
        else println("no")
      } else {
        var i = 1; var j = s.length - 1
        var si = s(0) + s(1); var sj = s(j)
        var ci = 2; var cj = 1
        var res = "no"
        while (i < j && !(ci <= cj && si >= sj) && res != "yes") {
          if (ci > cj && si < sj) {
            res = "yes"
          } else if (ci > cj && si >= sj) {
            j = j - 1; cj = cj + 1; sj = sj + s(j)
          } else if (ci <= cj && si < sj) {
            i = i + 1; ci = ci + 1; si = si + s(i)
          }
        }
        println(res)
      }
    }
  }
}

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import scala.collection.mutable.ArrayBuffer

object QualityVsQuantity {
  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                            val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//                "4\n3\n1 2 3\n5\n2 8 6 3 1\n4\n3 5 4 2\n5\n1000000000 1000000000 1000000000 1000000000 1000000000".getBytes)))

    var t = file.readLine.toInt
    while (t > 0) {
      t = t - 1
      file.readLine
      val nums = file.readLine.split(" ").map(_.toInt)
      val s = nums.sorted
      if (s.length == 3) {
        if (s(2) > s(0) + s(1)) println("yes")
        else println("no")
      } else {
        var i = 1; var j = s.length - 1
        var si = s(0) + s(1); var sj = s(j)
        var ci = 2; var cj = 1
        var res = "no"
        while (i < j && !(ci <= cj && si >= sj) && res != "yes") {
          if (ci > cj && si < sj) {
            res = "yes"
          } else if (ci > cj && si >= sj) {
            j = j - 1; cj = cj + 1; sj = sj + s(j)
          } else if (ci <= cj && si < sj) {
            i = i + 1; ci = ci + 1; si = si + s(i)
          }
        }
        println(res)
      }
    }
  }
}