You are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.Segment [l1, r1] lies within segment [l2, r2] iff l1 ≥ l2 and r1 ≤ r2.Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

The first line contains one integer n (1 ≤ n ≤ 3·105) — the number of segments. Each of the next n lines contains two integers li and ri (1 ≤ li ≤ ri ≤ 109) — the i-th segment.

Print two distinct indices i and j such that segment ai lies within segment aj. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

NoteIn the first example the following pairs are considered correct:  (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders;  (3, 2), (4, 2), (3, 5), (4, 5) — touch one border;  (5, 2), (2, 5) — match exactly.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader
    val n = r.read[Int]
    val lris = r.read[Array[(Int, Int)]](n).zipWithIndex.sorted.toList

    @annotation.tailrec
    def go(lri: ((Int, Int), Int), lris: List[((Int, Int), Int)]): (Int, Int) = lris match {
      case Nil => (-2, -2)
      case ((l1, r1), i1) :: lris1 => {
        val ((l, r), i) = lri
        if (l == l1) (i, i1)
        else if (r1 <= r) (i1, i)
             else go(((l1, r1), i1), lris1)
      }
    }

    val (i, j) = go(lris.head, lris.tail)
    println(s"${i+1} ${j+1}")
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}


You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 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 10^9$$$).

For each test case, print the answer — the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ if it's possible to do that or -1 if it's impossible to obtain $$$1$$$ from $$$n$$$.

NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $$$15116544$$$:  Divide by $$$6$$$ and get $$$2519424$$$;  divide by $$$6$$$ and get $$$419904$$$;  divide by $$$6$$$ and get $$$69984$$$;  divide by $$$6$$$ and get $$$11664$$$;  multiply by $$$2$$$ and get $$$23328$$$;  divide by $$$6$$$ and get $$$3888$$$;  divide by $$$6$$$ and get $$$648$$$;  divide by $$$6$$$ and get $$$108$$$;  multiply by $$$2$$$ and get $$$216$$$;  divide by $$$6$$$ and get $$$36$$$;  divide by $$$6$$$ and get $$$6$$$;  divide by $$$6$$$ and get $$$1$$$.

//package codeforces.contests._1374

/*
https://codeforces.com/contest/1374/problem/B
 */
object MultiplyByTwoDivideBySix {

  @scala.annotation.tailrec
  def countFactors(n: Int, m: Int, acc: Int = 0): Int =
    if (n == 1 || n % m != 0) acc else countFactors(n / m, m, acc + 1)

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

      val twos = countFactors(n, 2)
      val threes = countFactors(n, 3)

      val noOtherFactors = (math.pow(2, twos) * math.pow(3, threes)).toInt == n

      println {
        if (n == 1) 0
        else if (noOtherFactors && threes >= twos) threes + (threes - twos)
        else -1
      }
    }
  }
}

import scala.io.StdIn._

object CF653_B extends App {
  var t = readInt()
  while (t > 0) {
    t -= 1;

    var n = readInt()
    var (cnt2, cnt3) = (0, 0)
    while (n % 3 == 0) {
      n /= 3
      cnt3 += 1
    }
    while (n % 2 == 0) {
      n /= 2
      cnt2 += 1
    }

    if (n > 1 || cnt3 < cnt2) {
      println(-1)
//      sys.exit()
    } else {
      println(2 * cnt3 - cnt2)
    }
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val n = ni()
      if(n == 1) out.println("0")
      else {
        var cnt3 = 0
        var x = n
        while (x > 0 && x % 3 == 0) {
          cnt3 += 1
          x /= 3
        }

        var cnt2 = 0
        while (x > 0 && x % 2 == 0) {
          cnt2 += 1
          x /= 2
        }

        if(cnt2 > cnt3 || x > 1) out.println("-1")
        else out.println(cnt2 + (cnt3 - cnt2) * 2)
      }
    }
  }

}

object a{
  def main(args: Array[String]) = {
    val n: Int = scala.io.StdIn.readInt()
    for(i <- 1 to n){
      var x: Int = scala.io.StdIn.readInt()
      var ans = 0
      var done = false
      while(!done){
        if(x == 1){
          done = true
        }
        else if(x%6 == 0){
          x /= 6;
          ans += 1
        }
        else if(x%3 == 0){
          x /= 3
          ans += 2
        }
        else{
          ans = -1
          done = true
        }
      }
      println(ans)
    }
  }
}

object B extends App {

  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }

  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val number     = in.nextInt()
      var number2    = number
      var noOfTwos   = 0
      var noOfThrees = 0

      while (number2 % 2 == 0) {
        number2 = number2 / 2
        noOfTwos = noOfTwos + 1
      }

      while (number2 % 3 == 0) {
        number2 = number2 / 3
        noOfThrees = noOfThrees + 1
      }

      if (number == 1) {
        println(0)
      } else if (number2 > 1) {
        println(-1)
      } else {
        if (noOfTwos == noOfThrees) {
          println(noOfTwos)
        } else if (noOfThrees > noOfTwos) {
          val diff = noOfThrees - noOfTwos
          println(noOfTwos + (diff * 2))
        } else {
          println(-1)
        }
      }
    }
  }

  try {
    solve()
  } catch {
    case ex: Exception =>
      println(ex)
      sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

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

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

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

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

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

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

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

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

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

    def lineNumber: Int = reader.getLineNumber

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

    def nextString(): String = next()

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

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

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

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

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

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

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

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

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

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

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

    override def hasNext: Boolean = tokenizer().nonEmpty

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

}

import scala.io.StdIn.readLine
object Main {
  def main(args: Array[String]) = {
    val T = readLine().toInt
    for(cas <- 0 until T) {
      var n = readLine().toInt
      var c1 = 0
      var c2 = 0
      while(n % 2 == 0) {
        n /= 2
        c1 += 1
      }
      while(n % 3 == 0) {
        n /= 3
        c2 += 1
      }
      if(c1 > c2 || n != 1) {
        println("-1")
      } else {
        println(c2 - c1 + c2)
      }
    }
  }
}


There is a frog staying to the left of the string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ characters (to be more precise, the frog initially stays at the cell $$$0$$$). Each character of $$$s$$$ is either 'L' or 'R'. It means that if the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $$$0$$$.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the $$$n+1$$$-th cell. The frog chooses some positive integer value $$$d$$$ before the first jump (and cannot change it later) and jumps by no more than $$$d$$$ cells at once. I.e. if the $$$i$$$-th character is 'L' then the frog can jump to any cell in a range $$$[max(0, i - d); i - 1]$$$, and if the $$$i$$$-th character is 'R' then the frog can jump to any cell in a range $$$[i + 1; min(n + 1; i + d)]$$$.The frog doesn't want to jump far, so your task is to find the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it can jump by no more than $$$d$$$ cells at once. It is guaranteed that it is always possible to reach $$$n+1$$$ from $$$0$$$.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. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case is described as a string $$$s$$$ consisting of at least $$$1$$$ and at most $$$2 \cdot 10^5$$$ characters 'L' and 'R'. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum |s| \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it jumps by no more than $$$d$$$ at once.

NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the third test case of the example, the frog can choose $$$d=3$$$, jump to the cell $$$3$$$ from the cell $$$0$$$ and then to the cell $$$4$$$ from the cell $$$3$$$.In the fourth test case of the example, the frog can choose $$$d=1$$$ and jump $$$5$$$ times to the right.In the fifth test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the sixth test case of the example, the frog can choose $$$d=1$$$ and jump $$$2$$$ times to the right.

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val s = ('R' + ns() + 'R').toCharArray

      val n = s.length
      var prev = 0
      var mx = -1
      REP(n) { i =>
        if(i > 0 && s(i) == 'R') {
          mx = Math.max(mx, i - prev)
          prev = i
        }
      }
      out.println(mx)
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val instrs = io.read[String]

    val ans = ('R' + instrs + 'R')
      .zipWithIndex
      .collect({case ('R', i) => i})
      .sliding(2)
      .map({case Seq(i, j) => j - i})
      .max

    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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[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")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

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


The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).

The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.

Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).

NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val employees = Array.ofDim[Array[Int]](n) // employee -> language
  val markedEmployees = Array.ofDim[Boolean](n) // is employee marked
  val languages = Array.fill[List[Int]](m){List.empty} // language -> employee
  val markedLanguages = Array.ofDim[Boolean](m) // is language marked

  def mark(employee: Int) = {
    if (!markedEmployees(employee)) {
//      println("mark employee " + employee)
      markedEmployees(employee) = true
      employees(employee).foreach { markLanguage }
    }
  }

  def markLanguage(language: Int) {
    if (!markedLanguages(language)) {
//      println("mark language " + language)
      markedLanguages(language) = true
      languages(language).foreach {
        mark
      }
    }
  }

  (0 until n).foreach { j =>
    val data = in.next().split(' ').tail.map(_.toInt - 1)
    employees(j) = data
    data.foreach { i => languages(i) ::= j }
  }
  val res = (0 until n).foldLeft(0) {
    case (acc, j) if markedEmployees(j) => acc
    case (acc, j) =>
      mark(j)
      acc + 1
  }
  println(Math.max(res - 1, employees.count(_.isEmpty)))
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()
    val col = Array.fill[Boolean](n,m)(false)
    val adjA = Array.fill[Boolean](m,m)(false)

    REP(n) { i =>
      val k = ni()
      var prev = -1
      REP(k) { _ =>
        val j = ni()
        col(i)(j-1) = true
        if(prev == -1) prev = j-1
        else {
          adjA(prev)(j-1) = true
          adjA(j-1)(prev) = true
          prev = j-1
        }
      }
    }

    adjL = adjA.map(f => f.zipWithIndex.filter(p => p._1).map(_._2).toList)
    marked = Array.fill(m)(false)
    var count = 0
    var yes = false
    REP(n) { i =>
      val x = col(i).zipWithIndex.find(p => p._1 && marked(p._2))
      if(x.isEmpty) {
        count += 1
        val y: Option[(Boolean, Int)] = col(i).zipWithIndex.find(p => p._1)
        if(y.isDefined) {
          yes = true
          marked(y.get._2) = true
          dfs(y.get._2)
        }
      }
    }
    out.println(if(yes) count-1 else count)
  }

  var adjL: Array[List[Int]] = _
  var marked: Array[Boolean] = _

  def dfs(u: Int): Unit = {
    adjL(u).foreach { p =>
      if(!marked(p)) {
        marked(p) = true
        dfs(p)
      }
    }
  }
}

object tmp extends App {

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

  import scala.collection.mutable

  class MyScanner(br: BufferedReader) {
    var st = new StringTokenizer("")

    def this(is: InputStream) = this(new BufferedReader(new InputStreamReader(is)))

    private def next() = {

      while (!st.hasMoreElements) {
        st = new StringTokenizer(br.readLine())
      }
      st.nextToken()
    }

    def nextInt() = java.lang.Integer.parseInt(next())

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

    def nextLine() = br.readLine()
  }

  val sc = new MyScanner(System.in)
  val n = sc.nextInt()
  val m = sc.nextInt()
  val graph = Array.fill(n + m)(mutable.ArrayBuffer[Int]())
  var empl = 0
  var anyLeng = false
  while (empl < n) {
    val amount = sc.nextInt()
    var k = 0
    while (k < amount) {
      anyLeng = true
      val leng = sc.nextInt() - 1
      graph(empl) += n + leng
      graph(n + leng) += empl
      k += 1
    }
    empl += 1
  }
  val res = if (!anyLeng) n
  else {
    val groups = Array.fill(n)(-1)
    var curGroup = 0
    var v = 0
    while ( {v = 0; while (v < n && groups(v) != -1) v += 1; v < n}) {
      dfs(v)
      curGroup += 1
    }
    def dfs(v: Int): Unit = {
      if (v < n) {
        groups(v) = curGroup
      }
      val graphV = graph(v)
      val size = graphV.size
      var i = 0
      while (i < size) {
        val to = graphV(i)
        if (to >= n || groups(to) == -1) {
          dfs(to)
        }
        i += 1
      }
    }
    curGroup - 1
  }
  println(res)
}

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

object Solution2 {
  class Graph(vertices: List[Int]) {

    val neighbours: Array[List[Int]] = Array.fill(vertices.length)(List.empty)

    def addConnection(a: Int, b: Int): Unit = neighbours(a) = b :: neighbours(a)

    def getNeighbours(v: Int): List[Int] = neighbours(v)

    def dfs(now: Int, visited: Array[Boolean]): Unit = {
      visited(now) = true
      getNeighbours(now) foreach { x => if (!visited(x)) dfs(x, visited) }
    }

    def connectedComponentsAmWithFilter(p: Int => Boolean): Int = {
      val visited: Array[Boolean] = Array.fill(vertices.length)(false)

      (vertices filter p).foldLeft(0) {
        (sol, x) =>
          if (!visited(x)) {
            dfs(x, visited)
            sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine split " " map { _.toInt }
    val g: Graph = new Graph((0 until (n + m)).toList)
    var allZero = true
    0 until n foreach {
      i =>
        val line = readLine split " " map { _.toInt }
        val k = line(0)
        if (k > 0) allZero = false
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang - 1)
          g.addConnection(n - 1 + lang, i)
        }
    }
    if (allZero) println(n)
    else println(g.connectedComponentsAmWithFilter({ x => 0 <= x && x < n}) - 1)
  }
}

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

object Solution2 {
  class Graph(vertices: List[Int]) {

    val neighbours: Array[List[Int]] = Array.fill(vertices.length)(List.empty)

    def addConnection(a: Int, b: Int): Unit = neighbours(a) = b :: neighbours(a)

    def getNeighbours(v: Int): List[Int] = neighbours(v)

    def dfs(now: Int, visited: Array[Boolean], f: Int => Unit): Unit = {
      f(now)
      visited(now) = true
      getNeighbours(now) foreach { x => if (!visited(x)) dfs(x, visited, f) }
    }

    def connectedComponentsAmWithFilter(p: Int => Boolean): Int = {
      val visited: Array[Boolean] = Array.fill(vertices.length)(false)

      (vertices filter p).foldLeft(0) {
        (sol, x) =>
          if (!visited(x)) {
            dfs(x, visited, { x => visited(x) = true })
            sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine split " " map { _.toInt }
    val g: Graph = new Graph((0 until (n + m)).toList)
    var allZero = true
    0 until n foreach {
      i =>
        val line = readLine split " " map { _.toInt }
        val k = line(0)
        if (k > 0) allZero = false
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang - 1)
          g.addConnection(n - 1 + lang, i)
        }
    }
    if (allZero) println(n)
    else println(g.connectedComponentsAmWithFilter({ x => 0 <= x && x < n}) - 1)
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val employees = Array.ofDim[Array[Int]](n) // employee -> language
  val markedEmployees = Array.ofDim[Boolean](n) // is employee marked
  val languages = Array.fill[List[Int]](m){List.empty} // language -> employee
  val markedLanguages = Array.ofDim[Boolean](m) // is language marked

  def mark(employee: Int) = {
    if (!markedEmployees(employee)) {
//      println("mark employee " + employee)
      markedEmployees(employee) = true
      employees(employee).foreach { markLanguage }
    }
  }

  def markLanguage(language: Int) {
    if (!markedLanguages(language)) {
//      println("mark language " + language)
      markedLanguages(language) = true
      languages(language).foreach {
        mark
      }
    }
  }

  (0 until n).foreach { j =>
    val data = in.next().split(' ').tail.map(_.toInt - 1)
    employees(j) = data
    data.foreach { i => languages(i) ::= j }
  }
  val res = (0 until n).foldLeft(0) {
    case (acc, j) if markedEmployees(j) => acc
    case (acc, j) =>
      mark(j)
      acc + 1
  }
  println(res - 1)
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()
    val col = Array.fill[Boolean](n,m)(false)
    val adjA = Array.fill[Boolean](m,m)(false)

    REP(n) { i =>
      val k = ni()
      var prev = -1
      REP(k) { _ =>
        val j = ni()
        col(i)(j-1) = true
        if(prev == -1) prev = j-1
        else {
          adjA(prev)(j-1) = true
          adjA(j-1)(prev) = true
          prev = j-1
        }
      }
    }

    adjL = adjA.map(f => f.zipWithIndex.filter(p => p._1).map(_._2).toList)
    marked = Array.fill(m)(false)
    var count = 0

    REP(n) { i =>
      val x = col(i).zipWithIndex.find(p => p._1 && marked(p._2))
      if(x.isEmpty) {
        count += 1
        val y: Option[(Boolean, Int)] = col(i).zipWithIndex.find(p => p._1)
        if(y.isDefined) {
          marked(y.get._2) = true
          dfs(y.get._2)
        }
      }
    }
    out.println(count-1)
  }

  var adjL: Array[List[Int]] = _
  var marked: Array[Boolean] = _

  def dfs(u: Int): Unit = {
    adjL(u).foreach { p =>
      if(!marked(p)) {
        marked(p) = true
        dfs(p)
      }
    }
  }
}

import scala.collection.mutable

object Solution {

  class Graph[T](vertices: List[T]) {
  type Vertex = T
  type Connections = mutable.Map[Vertex, List[Vertex]]

  val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty

  def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))

  def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)

  def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {
    f(now)
    getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }
  }

  def connectedComponentsAm(): Int = {
    val visited: Set[Vertex] = Set.empty

    vertices.foldLeft(0) {
      (sol, x) =>
        if (!visited.contains(x)) {
          dfs(x, Set.empty, { x => visited + x }); sol + 1
        }
        else sol
    }
  }
}

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)
    1 to n foreach {
      i =>
        val line = readLine.split(" ").map(_.toInt)
        val k = line(0)
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang)
          g.addConnection(n + lang, i)
        }
    }
    g.connectedComponentsAm()
  }
}

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

object Solution {
  class Graph[T](vertices: List[T]) {
    type Vertex = T
    type Connections = mutable.Map[Vertex, List[Vertex]]

    val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty

    def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))

    def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)

    def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {
      f(now)
      getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }
    }

    def connectedComponentsAmWithFilter(p: Vertex => Boolean): Int = {
      var visited: Set[Vertex] = Set.empty

      (vertices filter p).foldLeft(0) {
        (sol, x) =>
          if (!visited.contains(x)) {
            dfs(x, Set.empty, { x => visited += x })
            sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)
    1 to n foreach {
      i =>
        val line = readLine.split(" ").map(_.toInt)
        val k = line(0)
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang)
          g.addConnection(n + lang, i)
        }
    }
    println(g.connectedComponentsAmWithFilter({ x => 1 <= x && x <= n}) - 1)
  }
}

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

object Solution {
  class Graph[T](vertices: List[T]) {
    type Vertex = T
    type Connections = mutable.Map[Vertex, List[Vertex]]

    val neighbours: mutable.Map[Vertex, List[Vertex]] = mutable.Map.empty

    def addConnection(a: Vertex, b: Vertex): Unit = neighbours.put(a, b :: neighbours.getOrElse(a, List.empty[Vertex]))

    def getNeighbours(v: Vertex): List[Vertex] = neighbours.getOrElse(v, List.empty)

    def dfs(now: Vertex, visited: Set[Vertex], f: Vertex => Unit): Unit = {
      f(now)
      getNeighbours(now) filterNot { x => visited.contains(x) } foreach { x => dfs(x, visited + now, f) }
    }

    def connectedComponentsAm(): Int = {
      val visited: Set[Vertex] = Set.empty

      vertices.foldLeft(0) {
        (sol, x) =>
          if (!visited.contains(x)) {
            dfs(x, Set.empty, { x => visited + x }); sol + 1
          }
          else sol
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toInt)
    val g: Graph[Int] = new Graph[Int]((1 to (n + m)).toList)
    1 to n foreach {
      i =>
        val line = readLine.split(" ").map(_.toInt)
        val k = line(0)
        1 to k foreach { j =>
          val lang = line(j)
          g.addConnection(i, n + lang)
          g.addConnection(n + lang, i)
        }
    }
    println(g.connectedComponentsAm())
  }
}


Okabe and Super Hacker Daru are stacking and removing boxes. There are n boxes numbered from 1 to n. Initially there are no boxes on the stack.Okabe, being a control freak, gives Daru 2n commands: n of which are to add a box to the top of the stack, and n of which are to remove a box from the top of the stack and throw it in the trash. Okabe wants Daru to throw away the boxes in the order from 1 to n. Of course, this means that it might be impossible for Daru to perform some of Okabe's remove commands, because the required box is not on the top of the stack.That's why Daru can decide to wait until Okabe looks away and then reorder the boxes in the stack in any way he wants. He can do it at any point of time between Okabe's commands, but he can't add or remove boxes while he does it.Tell Daru the minimum number of times he needs to reorder the boxes so that he can successfully complete all of Okabe's commands. It is guaranteed that every box is added before it is required to be removed.

The first line of input contains the integer n (1 ≤ n ≤ 3·105) — the number of boxes. Each of the next 2n lines of input starts with a string "add" or "remove". If the line starts with the "add", an integer x (1 ≤ x ≤ n) follows, indicating that Daru should add the box with number x to the top of the stack.  It is guaranteed that exactly n lines contain "add" operations, all the boxes added are distinct, and n lines contain "remove" operations. It is also guaranteed that a box is always added before it is required to be removed.

Print the minimum number of times Daru needs to reorder the boxes to successfully complete all of Okabe's commands.

3
add 1
remove
add 2
add 3
remove
remove

7
add 3
add 2
add 1
remove
add 4
remove
remove
remove
add 6
add 7
add 5
remove
remove
remove

NoteIn the first sample, Daru should reorder the boxes after adding box 3 to the stack.In the second sample, Daru should reorder the boxes after adding box 4 and box 7 to the stack.

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

import scala.collection.mutable

object C {

  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 nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    var posToRemove = 1
    var ans = 0
    var list = scala.collection.immutable.List[Int]()
    var howMuchToSkip = 0
    for (_ <- 0 until 2 * n) {
      val command = next
      if (command.equalsIgnoreCase("add")) {
        val id = nextInt
        howMuchToSkip = 0
        list = id :: list
      } else {
        if (howMuchToSkip > 0) {
          howMuchToSkip -= 1
          posToRemove += 1
        } else if (list.isEmpty || list.head == posToRemove) {
          posToRemove += 1
          if (!list.isEmpty)
            list = list.tail
        } else {
          ans += 1
          posToRemove += 1
          //posToRemove += list.length
          howMuchToSkip = list.length
          list = Nil
        }
      }
    }
    out.println(ans)
    return 0
  }
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n = read[Int]
    val golden, temp = collection.mutable.Stack.empty[Int]
    var ans, expected = 0

    repeat(2*n) {
      val cmd = read[String]
      cmd match {
        case "add" => temp.push(read[Int])
        case "remove" =>
          expected += 1
          val popped = if (temp.isEmpty) {
            golden.pop()
          } else if (temp.head == expected) {
            temp.pop()
          } else {
            ans += 1
            golden.pushAll(temp.sorted.reverse)
            temp.clear()
            golden.pop()
          }
          //assert(popped == expected)
      }
      //debug(cmd, golden, temp, expected, ans)
    }

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

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

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

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

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

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

  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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

import scala.collection.mutable

object C {

  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 nextBoolean: Boolean = next.equalsIgnoreCase("1")

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

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

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }

    override def toString = s"MultiHashSet($map)"
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    *
    * @param values      Array of Int
    * @param commutative function like min, max, sum
    * @param zero        zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    var posToRemove = 1
    var ans = 0
    val set = new mutable.TreeSet[Int]()
    var list = scala.collection.immutable.List[Int]()
    var howMuchToSkip = 0
    for (_ <- 0 until 2 * n) {
      val command = next
      if (command.equalsIgnoreCase("add")) {
        val id = nextInt
        set.add(id)
        list = id :: list
      } else {
        if (howMuchToSkip > 0) {
          howMuchToSkip -= 1
        }
        else if (list.head == posToRemove) {
          set.remove(list.head)
          posToRemove += 1
          list = list.tail
        } else {
          ans += 1
          set.clear()
          posToRemove += list.length
          howMuchToSkip = list.length
          list = Nil
        }
      }
    }
    out.println(ans)
    return 0
  }
}


Omkar is standing at the foot of Celeste mountain. The summit is $$$n$$$ meters away from him, and he can see all of the mountains up to the summit, so for all $$$1 \leq j \leq n$$$ he knows that the height of the mountain at the point $$$j$$$ meters away from himself is $$$h_j$$$ meters. It turns out that for all $$$j$$$ satisfying $$$1 \leq j \leq n - 1$$$, $$$h_j < h_{j + 1}$$$ (meaning that heights are strictly increasing).Suddenly, a landslide occurs! While the landslide is occurring, the following occurs: every minute, if $$$h_j + 2 \leq h_{j + 1}$$$, then one square meter of dirt will slide from position $$$j + 1$$$ to position $$$j$$$, so that $$$h_{j + 1}$$$ is decreased by $$$1$$$ and $$$h_j$$$ is increased by $$$1$$$. These changes occur simultaneously, so for example, if $$$h_j + 2 \leq h_{j + 1}$$$ and $$$h_{j + 1} + 2 \leq h_{j + 2}$$$ for some $$$j$$$, then $$$h_j$$$ will be increased by $$$1$$$, $$$h_{j + 2}$$$ will be decreased by $$$1$$$, and $$$h_{j + 1}$$$ will be both increased and decreased by $$$1$$$, meaning that in effect $$$h_{j + 1}$$$ is unchanged during that minute.The landslide ends when there is no $$$j$$$ such that $$$h_j + 2 \leq h_{j + 1}$$$. Help Omkar figure out what the values of $$$h_1, \dots, h_n$$$ will be after the landslide ends. It can be proven that under the given constraints, the landslide will always end in finitely many minutes.Note that because of the large amount of input, it is recommended that your code uses fast IO.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$).  The second line contains $$$n$$$ integers $$$h_1, h_2, \dots, h_n$$$ satisfying $$$0 \leq h_1 < h_2 < \dots < h_n \leq 10^{12}$$$ — the heights.

Output $$$n$$$ integers, where the $$$j$$$-th integer is the value of $$$h_j$$$ after the landslide has stopped.

NoteInitially, the mountain has heights $$$2, 6, 7, 8$$$.In the first minute, we have $$$2 + 2 \leq 6$$$, so $$$2$$$ increases to $$$3$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$3, 5, 7, 8$$$.In the second minute, we have $$$3 + 2 \leq 5$$$ and $$$5 + 2 \leq 7$$$, so $$$3$$$ increases to $$$4$$$, $$$5$$$ is unchanged, and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 5, 6, 8$$$.In the third minute, we have $$$6 + 2 \leq 8$$$, so $$$6$$$ increases to $$$7$$$ and $$$8$$$ decreases to $$$7$$$, leaving $$$4, 5, 7, 7$$$.In the fourth minute, we have $$$5 + 2 \leq 7$$$, so $$$5$$$ increases to $$$6$$$ and $$$7$$$ decreases to $$$6$$$, leaving $$$4, 6, 6, 7$$$.In the fifth minute, we have $$$4 + 2 \leq 6$$$, so $$$4$$$ increases to $$$5$$$ and $$$6$$$ decreases to $$$5$$$, leaving $$$5, 5, 6, 7$$$.In the sixth minute, nothing else can change so the landslide stops and our answer is $$$5, 5, 6, 7$$$.

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

    val n = nextInt
    val hs = nextLongs(n)
    var sum = hs.sum

    var i = 0
    var prev = 0L
    while (i < n) {

      @annotation.tailrec
      def binSearch(low: Long, hi: Long): Long = {
        if (hi < low) low
        else {
          val mid = (low + hi) / 2
          if (can(mid)) binSearch(low, mid - 1)
          else binSearch(mid + 1, hi)
        }
      }

      def can(x: Long): Boolean = {
        val rem = n - i - 1
        val maxLast = x + rem
        val maxRem = (x + 1 + maxLast) * rem / 2
        x + maxRem >= sum
      }

      val rem = n - i
      val x = binSearch(prev, sum / rem + 1)
      hs(i) = x
      prev = x
      sum -= x

      i += 1
    }

    out.println(hs.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 F {
  import InOut._
  def main(args: Array[String]): Unit = {

    val n = nextInt
    val hs = nextLongs(n)
    var sum = hs.sum

    var i = 0
    while (i < n) {

      @annotation.tailrec
      def binSearch(low: Long, hi: Long): Long = {
        if (hi < low) low
        else {
          val mid = (low + hi) / 2
          if (can(mid)) binSearch(low, mid - 1)
          else binSearch(mid + 1, hi)
        }
      }

      def can(x: Long): Boolean = {
        val rem = n - i - 1
        val maxLast = x + rem
        val maxRem = (x + 1 + maxLast) * rem / 2
        x + maxRem >= sum
      }

      val x = binSearch(0, sum)
      hs(i) = x
      sum -= x

      i += 1
    }

    out.println(hs.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
  }
}


You are given four integer values $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$.Check if there exists a string that contains:   $$$a$$$ letters 'A';  $$$b$$$ letters 'B';  $$$c$$$ letters 'C';  no other letters;  exactly $$$m$$$ pairs of adjacent equal letters (exactly $$$m$$$ such positions $$$i$$$ that the $$$i$$$-th letter is equal to the $$$(i+1)$$$-th one).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Each of the next $$$t$$$ lines contains the description of the testcase — four integers $$$a$$$, $$$b$$$, $$$c$$$ and $$$m$$$ ($$$1 \le a, b, c \le 10^8$$$; $$$0 \le m \le 10^8$$$).

For each testcase print "YES" if there exists a string that satisfies all the requirements. Print "NO" if there are no such strings. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first testcase strings "ABCAB" or "BCABA" satisfy the requirements. There exist other possible strings.In the second testcase there's no way to put adjacent equal letters if there's no letter that appears at least twice.In the third testcase string "CABBCC" satisfies the requirements. There exist other possible strings.

object B extends App {

  /** Assumption: a >= b >= c
    *
    * - Upper bound: (a - 1) + (b - 1) + (c - 1)
    *   Example: "aaaaabbbc"
    *
    * - Lower bound: a - b - c - 1
    *   Example: "abacabacababaaa"
    */
  def check(a: Int, b: Int, c: Int, m: Int): Boolean =
    m >= 2 * (a max b max c) - a - b - c - 1 && m <= a + b + c - 3

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        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)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.util.Sorting.quickSort
import util.control.Breaks._

object Solution {
    val writer =  new PrintWriter(System.out)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {
        while (!st.hasMoreTokens) {
            st = new StringTokenizer(reader.readLine())
        }
        st.nextToken()
    }

    def readInt() = next.toInt
    def readLong() = next.toLong
    def readString() = next()

    def pow(a: Int, b: Int): Long = {
        if (b == 0) return 1

        val rs = pow(a, b / 2)
        rs * rs * (if (b % 2 == 0) 1 else a)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def LCM(a: Int, b: Int): Int = (a / GCD(a,b)) * b

    def root(u: Int, p: Array[Int]): Int = {
        if (p(u) < 0) return u
        p(u) = root(p(u), p)
        p(u)
    }

    def join(u: Int, v: Int, p: Array[Int]): Unit = {
        var x = root(u, p)
        var y = root(v, p)
        if (x == y) return

        if (p(y) < p(x)) {
            val t = x
            x = y
            y = t
        }
        p(x) += p(y)
        p(y) = x
    }

    def main(args: Array[String]) {
        var t = readInt()
        while (t > 0) {
            t -= 1
            val (a,b,c,m) = (readInt(),readInt(),readInt(),readInt())

            val s = Array(a,b,c)
            val maxS = s.max
            val sumS = s.sum
            val maxP = sumS - 3
            val minP = maxS - (sumS - maxS) - 1
            if (m <= maxP && m >= minP) writer.println("YES")
            else writer.println("NO")

        }
        writer.close()
    }
}

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

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

    def main(args: Array[String]): Unit = {
        val t = readInt()
        for (tt <- 1 to t) {
            val a = readInt()
            val b = readInt()
            val c = readInt()
            val m = readInt()
            val sum = a + b + c
            val valid = max(0, a - 1) + max(0, b - 1) + max(0, c - 1)
            val mx = max(a, max(b, c))
            if (m > valid || m < mx-1-(sum-mx))
                writer.println("NO")
            else
                writer.println("YES")

            writer.flush()
        }
    }
}

object B extends App {

  /** Assumption: a >= b >= c
    *
    * - Upper bound: (a - 1) + (b - 1) + (c - 1)
    *   Example: "aaaaabbbc"
    *
    * - Lower bound: a - b - c - 1
    *   Example: "abacabacababaaa"
    */
  def check(a: Int, b: Int, c: Int, m: Int): Boolean =
    m >= 2 * ((a max b max c) + (a min b min c)) - a - b - c - 1 && m <= a + b + c - 3

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        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)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {

  /** Assumption: a >= b >= c
    *
    * - Upper bound: (a - 1) + (b - 1) + (c - 1)
    *   Example: "aaaaabbbc"
    *
    * - Lower bound: a - b - c - 1
    *   Example: "abacabacababaaa"
    */
  def check(a: Int, b: Int, c: Int, m: Int): Boolean =
    m >= a - b - c - 1 && m <= a + b + c - 3

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        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)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}

object B extends App {

  @annotation.tailrec
  def check(a: Int, b: Int, c: Int, m: Int, iter: Int = 0): Boolean =
    if (iter > 100) false
    else {
      val n = a + b + c

      if (a < b || a < c || b < c)
        check(a max b max c, n - (a max b max c) - (a min b min c), a min b min c, m, iter)
      else
        m match {
          case 0 => a <= (n + 1) / 2
          case m =>
            val ka = m min (a / 2)

            if (ka > 0 && a - ka <= (n - m + 1) / 2) check(a - 2 * ka, b, c, m - ka, iter + 1)
            else false
        }

    }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val Array(a, b, c, m) = nextInts(4)

    check(a, b, c, m) match {
      case true  =>
        out.println("YES")
        out.flush()
      case false =>
        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)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

    def nextToken(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens())
        tokenizer = new java.util.StringTokenizer(in.readLine())
      tokenizer.nextToken()
    }
  }
}