On a chessboard with a width of $$$10^9$$$ and a height of $$$10^9$$$, the rows are numbered from bottom to top from $$$1$$$ to $$$10^9$$$, and the columns are numbered from left to right from $$$1$$$ to $$$10^9$$$. Therefore, for each cell of the chessboard you can assign the coordinates $$$(x,y)$$$, where $$$x$$$ is the column number and $$$y$$$ is the row number.Every day there are fights between black and white pieces on this board. Today, the black ones won, but at what price? Only the rook survived, and it was driven into the lower left corner — a cell with coordinates $$$(1,1)$$$. But it is still happy, because the victory has been won and it's time to celebrate it! In order to do this, the rook needs to go home, namely — on the upper side of the field (that is, in any cell that is in the row with number $$$10^9$$$).Everything would have been fine, but the treacherous white figures put spells on some places of the field before the end of the game. There are two types of spells:   Vertical. Each of these is defined by one number $$$x$$$. Such spells create an infinite blocking line between the columns $$$x$$$ and $$$x+1$$$.  Horizontal. Each of these is defined by three numbers $$$x_1$$$, $$$x_2$$$, $$$y$$$. Such spells create a blocking segment that passes through the top side of the cells, which are in the row $$$y$$$ and in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. The peculiarity of these spells is that it is impossible for a certain pair of such spells to have a common point. Note that horizontal spells can have common points with vertical spells.    An example of a chessboard. Let's recall that the rook is a chess piece that in one move can move to any point that is in the same row or column with its initial position. In our task, the rook can move from the cell $$$(r_0,c_0)$$$ into the cell $$$(r_1,c_1)$$$ only under the condition that $$$r_1 = r_0$$$ or $$$c_1 = c_0$$$ and there is no blocking lines or blocking segments between these cells (For better understanding, look at the samples).Fortunately, the rook can remove spells, but for this it has to put tremendous efforts, therefore, it wants to remove the minimum possible number of spells in such way, that after this it can return home. Find this number!

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$0 \le n,m \le 10^5$$$) — the number of vertical and horizontal spells. Each of the following $$$n$$$ lines contains one integer $$$x$$$ ($$$1 \le x < 10^9$$$) — the description of the vertical spell. It will create a blocking line between the columns of $$$x$$$ and $$$x+1$$$. Each of the following $$$m$$$ lines contains three integers $$$x_1$$$, $$$x_2$$$ and $$$y$$$ ($$$1 \le x_{1} \le x_{2} \le 10^9$$$, $$$1 \le y < 10^9$$$) — the numbers that describe the horizontal spell. It will create a blocking segment that passes through the top sides of the cells that are in the row with the number $$$y$$$, in columns from $$$x_1$$$ to $$$x_2$$$ inclusive. It is guaranteed that all spells are different, as well as the fact that for each pair of horizontal spells it is true that the segments that describe them do not have common points.

In a single line print one integer — the minimum number of spells the rook needs to remove so it can get from the cell $$$(1,1)$$$ to at least one cell in the row with the number $$$10^9$$$

NoteIn the first sample, in order for the rook return home, it is enough to remove the second horizontal spell.  Illustration for the first sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the second horizontal spell. It also shows the path, on which the rook would be going home. In the second sample, in order for the rook to return home, it is enough to remove the only vertical spell. If we tried to remove just one of the horizontal spells, it would not allow the rook to get home, because it would be blocked from above by one of the remaining horizontal spells (either first one or second one), and to the right it would be blocked by a vertical spell.  Illustration for the second sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletion of the vertical spell. It also shows the path, on which the rook would be going home. In the third sample, we have two horizontal spells that go through the whole field. These spells can not be bypassed, so we need to remove both of them.  Illustration for the third sample. On the left it shows how the field looked at the beginning. On the right it shows how the field looked after the deletion of the horizontal spells. It also shows the path, on which the rook would be going home. In the fourth sample, we have no spells, which means that we do not need to remove anything.In the fifth example, we can remove the first vertical and third horizontal spells.  Illustration for the fifth sample. On the left it shows how the field looked at the beginning. On the right it shows how it looked after the deletions. It also shows the path, on which the rook would be going home.

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

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

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

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

  def solve(): Unit = {
    val MIN = 1
    val MAX = 1e9.toInt

    val N, M = ni()
    val V = na(N)
    radixSort(V)

    case class Line(from: Int, to: Int)
    val H = mutable.Map[Int, ArrayBuffer[Line]]()
    rep(M) { _ =>
      val l, r, y = ni()
      if (!H.contains(y)) {
        H(y) = ArrayBuffer()
      }
      H(y) += Line(l, r)
    }

    def merge(lines: ArrayBuffer[Line]): Line = {
      if (lines.length == 1) lines.head
      else {
        val sorted = lines.sortBy(_.to)
        var to = sorted.head.to
        rep(sorted.length - 1, 1) { i =>
          val l = sorted(i)
          if (to + 1 < l.from) return Line(sorted.head.from, to)
          to = l.to
        }
        Line(sorted.head.from, to)
      }
    }

    def calcV(lines: ArrayBuffer[Line]): Int = {
      val aLine = merge(lines)
      if (aLine.from > MIN) 0 // 一番左が空いている
      else if (aLine.to == MAX) Integer.MAX_VALUE // 全部埋まってる
      else {
        lowerBound(V, aLine.to + 1)
      }
    }

    val L = Array.ofDim[Int](H.size) // 可変だと面倒なので0もいれることにする
    var li = 0
    H.values.foreach { lines =>
      L(li) = calcV(lines)
      li += 1
    }

    radixSort(L)

    var ans = Integer.MAX_VALUE
    rep(N + 1) { i =>
      val cutH = L.length - lowerBound(L, i + 1)
      val cutV = i
      ans = min(ans, cutH + cutV)
    }

    out.println(ans)
  }

  // あえてコピペ
  // 要はcountLt
  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  /**
    * 正の値のみのときだけ
    */
  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      rep(65536, 1){ i => b(i) += b(i - 1) }
      rep(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

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

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

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

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

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

import java.util

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 Hor(x: Int, y: Int)

  val Array(n, m) = readInts(2)
  val vs = Array.fill(n){ readLine.toInt }.sorted :+ 1000000000

  val hsBuilder = new mutable.ArrayBuilder.ofRef[Hor]
  for (_ <- 0 until m) {
    val Array(x1, x2, y) = readInts(3)
    if (x1 == 1) hsBuilder += Hor(x2, y)
  }
  val hs = hsBuilder.result.sortBy(- _.x)

  val longer = new util.TreeMap[Integer, Integer]
  var count = 0
  for (h <- hs) {
    count += 1
    longer.put(h.x, count)
  }

  val max = hs.length

  var res = Int.MaxValue
  for (i <- vs.indices) {
    val j = longer.ceilingKey(vs(i))
    val total = if (j == null) i else i + longer.get(j)
    if (total < res) res = total
  }

  println(res)
}

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  case class Point(x: Int, y: Int)

  @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val vert = Array.fill(n)(in.nextInt)
    val h = ArrayBuffer[Int]()
    var const = 0
    (1 to m).foreach { _ =>
      val x1, x2 = in.nextInt
      in.nextInt
      if (x1 == 1 && x2 == 1000000000)
        const += 1
      else if (x1 == 1)
        h.append(x2)
    }

    val hor = h.toArray

    util.Arrays.sort(vert)
    util.Arrays.sort(hor)

    var ans = hor.length
    var v = 0
    hor.indices.foreach { x =>
      while (v < n && vert(v) <= hor(x))
        v += 1
      ans = math.min(ans, hor.length - x - 1 + v)
    }

    println(ans + const)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object Main {
  import java.io.PrintStream

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

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

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

  val MOD = 1000000007

  def solve(): Unit = {
    val N, M = ni()
    val V = Array.ofDim[Int](N + 1)
    rep(N) { i =>
      V(i) = ni()
    }
    V(N) = 1e9.toInt
    radixSort(V)

    val H_buff = ArrayBuffer[Int]()
    rep(M) { _ =>
      val x1, x2, _ = ni()
      if (x1 == 1) {
        H_buff += upperBound(V, x2)
      }
    }

    val H = radixSort(H_buff.toArray)
    var ans = 1e9.toInt
    var h = 0
    rep(N + 1) { i =>
      while(h < H.length && H(h) <= i){ h += 1}
      ans = min(ans, i + H.length - h)
    }

    println(ans)
  }

  // 要はcountLe
  def upperBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) > x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  /**
    * 正の値のみのときだけ
    */
  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      rep(65536, 1){ i => b(i) += b(i - 1) }
      rep(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }

  class InputReader(reader: BufferedReader) {
    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(Console.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    rep(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    rep(n) { i =>
      rep(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  case class Point(x: Int, y: Int)

  @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val vert = Array.fill(n)(in.nextInt)
    val hor = ArrayBuffer[Int]()
    var const = 0
    (1 to m).foreach { _ =>
      val x1, x2 = in.nextInt
      in.nextInt
      if (x1 == 1 && x2 == 1000000000)
        const += 1
      else if (x1 == 1)
        hor.append(x2)
    }
    var ans = n + hor.size
    var v = 0
    hor.indices.foreach { x =>
      while (v < n && vert(v) <= hor(x))
        v += 1
      ans = math.min(ans, hor.size - x - 1 + v)
    }

    println(ans + const)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

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

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

object A extends App {

  case class Point(x: Int, y: Int)

  @inline def dist(x1: Int, x2: Int, y1: Int, y2: Int): Int = math.abs(x1 - x2) * 2 + math.abs(y1 - y2) * 2

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val m = in.nextInt
    val vert = Array.fill(n)(in.nextInt)
    val hor = ArrayBuffer[Int]()
    var const = 0
    (1 to m).foreach { _ =>
      val x1, x2 = in.nextInt
      in.nextInt
      if (x1 == 1 && x2 == 1000000000)
        const += 1
      else if (x1 == 1)
        hor.append(x2)
    }
    var ans = hor.size
    var v = 0
    hor.indices.foreach { x =>
      while (v < n && vert(v) <= hor(x))
        v += 1
      ans = math.min(ans, hor.size - x - 1 + v)
    }

    println(ans + const)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}


Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.

Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.

NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.

import io.StdIn.readLine

object A extends App {
  val Array(n, k) = readLine.split(' ').map(_.toInt)
  val xs = readLine.split(' ').map(_.toLong)
  val m = xs.min
  if (xs.exists(x => (x - m) % k != 0)) println("-1")
  else{
    val u = xs.view.map(x => (x - m) / k).sum
    println(u)
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val k = arr(1)
    var secondCount = 0L
    var shares = io.StdIn.readLine().split(" ").map(_.toInt)

    val rest = shares.head % k
    if (shares.exists(_ % k != rest)) println(-1) else {
      val minVal = shares.min
      shares.foreach(i => secondCount += (i - minVal) / k)
      println(secondCount)
    }
  }
}

object _793A 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, k = read[Int]
    val prices = read[Seq, Long](n)
    val smallest = prices.min
    val target = prices.map(_ - smallest)

    val ans = when(target.forall(_%k == 0)) {
      target.sumWith(_/k)
    }

    write(ans.getOrElse(-1))
  }
}
/****************************[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
      }
    }
  }
}

object A extends App {

  val arr = io.StdIn.readLine().split(" ").map(_.toLong);
  val count = arr(1)
  val arr2 = io.StdIn.readLine().split(" ").map(_.toLong);
  val min = arr2.min

  val counts = arr2.map {
    case x if (x - min) % count == 0 => (x - min) / count
    case x if (x - min) % count != 0 => -1
  }
  val answer = counts.find(x => x == -1).getOrElse(counts.sum)
  print(answer)
}

/**
  * Created by ivan-pifagor on 4/23/17.
  */
import scala.io.StdIn.readLine
object Main {
    def main(args: Array[String]): Unit = {
        val K = readLine().split(" ").map(_.toLong)
        val A = readLine().split(" ").map(_.toLong)
        val m = A.min
        if (A.forall(a => ( a - m) % K(1) == 0 )){
            println(A.map(a => (a - m) / K(1)).sum)
        }else {
            println(-1)
        }
    }

}

object Main {
  def main(args: Array[String]): Unit = {
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)
    val n = arr(0)
    val k = arr(1)
    var secondCount = 0
    var shares = io.StdIn.readLine().split(" ").map(_.toInt)

    val rest = shares.head % k
    if (shares.exists(_ % k != rest)) println(-1) else {
      val minVal = shares.min
      shares.foreach(i => secondCount += (i - minVal) / k)
      println(secondCount)
    }
  }
}

object Main {
    def main(args: Array[String]): Unit = {
        val K = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        val A = scala.io.StdIn.readLine().split(" ").map(_.toInt)
        val m = A.min
        if (A.forall(a => ( a - m) % K(1) == 0 )){
            println(A.map(a => (a - m) / K(1)).sum)
        }else {
            println(-1)
        }
    }

}


One day Nikita found the string containing letters "a" and "b" only. Nikita thinks that string is beautiful if it can be cut into 3 strings (possibly empty) without changing the order of the letters, where the 1-st and the 3-rd one contain only letters "a" and the 2-nd contains only letters "b".Nikita wants to make the string beautiful by removing some (possibly none) of its characters, but without changing their order. What is the maximum length of the string he can get?

The first line contains a non-empty string of length not greater than 5 000 containing only lowercase English letters "a" and "b".

Print a single integer — the maximum possible size of beautiful string Nikita can get.

NoteIt the first sample the string is already beautiful.In the second sample he needs to delete one of "b" to make it beautiful.

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

  override def apply(io: IO): io.type = {
    val s = io.read[String]
    val n = s.length

    def count(from: Int, until: Int, prefixSum: IndexedSeq[Int]) = {
      assert(from <= until)
      prefixSum(until) - prefixSum(from)
    }

    val as = s.scanLeft(0) {
      case (i, 'a') => i + 1
      case (i, _) => i
    }

    val bs = s.scanLeft(0) {
      case (i, 'b') => i + 1
      case (i, _) => i
    }

    def length(l: Int, r: Int) = count(0, l, as) + count(l, r, bs) + count(r, n, as)

    var ans = 0
    for {
      i <- 0 to n
      j <- i to n
    } ans = ans max length(i, j)

    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()
}
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
    def toSeq(implicit ev: A =:= B): Seq[A] = Seq(p._1, p._2.asInstanceOf[A])
  }
  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 scala.io.StdIn._
import scala.collection.mutable.ArraySeq

object Codeforces extends App {
  val beauty = readLine()
  var max: Int = 0
  var aCount: Int = 0
  var bCount: Int = 0
  val a = beauty.map(c => {
    if (c == 'a')
      aCount += 1
    aCount
  }).toArray
  val b = beauty.map(c => {
    if (c == 'b')
      bCount += 1
    bCount
  }).toArray
  for (i <- 0 to beauty.length) {
    for (j <- i to beauty.length) {
      var current: Int = 0
      if (i > 0) // left A
        current += a(i - 1)
      if (j > 0) { // center B
        current += b(j - 1)
        if (i > 0)
          current -= b(i - 1)
      }
      if (j > 0)
        current += a(a.length - 1) - a(j - 1)
      max = math.max(max, current)
    }
  }
  println(max)
}


This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hedgehog. In Mashas mind every hedgehog consists of a tail and some spines. She wants to paint the tail that satisfies the following conditions:   Only segments already presented on the picture can be painted;  The tail should be continuous, i.e. consists of some sequence of points, such that every two neighbouring points are connected by a colored segment;  The numbers of points from the beginning of the tail to the end should strictly increase. Masha defines the length of the tail as the number of points in it. Also, she wants to paint some spines. To do so, Masha will paint all the segments, such that one of their ends is the endpoint of the tail. Masha defines the beauty of a hedgehog as the length of the tail multiplied by the number of spines. Masha wants to color the most beautiful hedgehog. Help her calculate what result she may hope to get.Note that according to Masha's definition of a hedgehog, one segment may simultaneously serve as a spine and a part of the tail (she is a little girl after all). Take a look at the picture for further clarifications.

First line of the input contains two integers n and m(2 ≤ n ≤ 100 000, 1 ≤ m ≤ 200 000) — the number of points and the number segments on the picture respectively.  Then follow m lines, each containing two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the numbers of points connected by corresponding segment. It's guaranteed that no two segments connect the same pair of points.

Print the maximum possible value of the hedgehog's beauty.

NoteThe picture below corresponds to the first sample. Segments that form the hedgehog are painted red. The tail consists of a sequence of points with numbers 1, 2 and 5. The following segments are spines: (2, 5), (3, 5) and (4, 5). Therefore, the beauty of the hedgehog is equal to 3·3 = 9.

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

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
    val g = Array.fill(n)(ArrayBuffer[Int]())
    val len = Array.fill(n)(1L)
    val ct = Array.fill(n)(0L)
    for (i <- 0 until m) {
      val Array(u, v) = StdIn.readLine().split(" ").map(_.toInt - 1)
      g(u).append(v)
      g(v).append(u)
      ct(u) += 1
      ct(v) += 1
    }
    for (v <- 0 until n) {
      for (u <- g(v) if u > v) {
        len(u) = len(u).max(len(v) + 1)
      }
    }
    var ans = 0L
    for (v <- 0 until n) {
      ans = ans.max(len(v) * ct(v))
    }
    println(ans)
  }
}

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Long](n)
        val len = new Array[Long](n)
        val edges = new Array[HashSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new HashSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            len(i) = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(len(i) + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(len(i) * spines(i))
        }
        println(result)
    }
}

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

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)

  val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>
    Seq((j, i), (i, j))
  }
  val mapOfSegments = listOfSegments.groupBy(_._1)

  val mapOfTail = mutable.Map[Int, Int]()

  def calcBeauty(point: Int): Long = {
    val listOfSpine = mapOfSegments.getOrElse(point, Nil)
    val tail = listOfSpine.filter { case (s, e) => e < s }.map { p =>
      mapOfTail(p._2)
    } match {
      case l if l.isEmpty => 1
      case l => l.max + 1
    }

    mapOfTail(point) = tail
    tail.toLong * listOfSpine.length
  }

  val output = {
    for {
      i <- 1 to numOfPoints
    } yield {
      calcBeauty(i)
    }
  }.max

  println(output)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val length = Array.ofDim[Int](n)
  val weight = Array.ofDim[Int](n)
  val edgesUp = Array.fill[List[Int]](n){ Nil }
  val edgesDown = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edgesDown(max) ::= min
    edgesUp(min) ::= max
  }

  def calcLength(start: Int): Int = {
    val children = edgesDown(start)
    if (children.isEmpty) {
      1
    } else {
      val childrenLength = length(children.maxBy(length))
      childrenLength + 1
    }
  }

  (0 until n).foreach(i => length(i) = calcLength(i))

  println(length.zip(weight).map(i => i._1.toLong * i._2).max)

}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B 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, m) = readInts(2)

  val degs = Array.fill(n) { 0 }
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u max v) += u min v
    degs(u) += 1
    degs(v) += 1
  }

  val adjs = adjBuilders.map(_.result)
  val maxDepths = Array.fill(n) { 1 }

  for (u <- 0 until n) {
    for (v <- adjs(u)) {
      maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1)
    }
  }

  val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max

  println(res)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B 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, m) = readInts(2)

  val degs = Array.fill(n) { 0 }
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u max v) += u min v
    degs(u) += 1
    degs(v) += 1
  }

  val adjs = adjBuilders.map(_.result)
  val maxDepths = Array.fill(n) { 1 }

  val sortedBuilder = new mutable.ArrayBuilder.ofInt

  val color = Array.fill(n)(0)

  def dfs(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (color(v) == 0) dfs(v)
      i += 1
    }
    color(u) = 2
    sortedBuilder += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs(i)

  val sorted = sortedBuilder.result

  for (u <- sorted) {
    for (v <- adjs(u)) {
      maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1)
    }
  }

  val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max

  println(res)
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B 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, m) = readInts(2)

  val degs = Array.fill(n) { 0 }
  val adjBuilders = Array.fill(n) { new ArrayBuilder.ofInt }

  for (_ <- 1 to m) {
    val Array(u, v) = readInts(2).map(_ - 1)
    adjBuilders(u max v) += u min v
    degs(u) += 1
    degs(v) += 1
  }

  val adjs = adjBuilders.map(_.result)
  val maxDepths = Array.fill(n) { 1 }

  val sorted = mutable.ArrayBuffer.empty[Int]

  val color = Array.fill(n)(0)

  def dfs(u: Int): Unit = {
    color(u) = 1
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      if (color(v) == 0) dfs(v)
      i += 1
    }
    color(u) = 2
    sorted += u
  }

  for (i <- 0 until n) if (color(i) == 0) dfs(i)

  for (u <- sorted) {
    for (v <- adjs(u)) {
      maxDepths(u) = maxDepths(u) max (maxDepths(v) + 1)
    }
  }

  val res = (0 until n).map(i => degs(i).toLong * maxDepths(i)).max

  println(res)
}

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

object Main {
  def main(args: Array[String]) {
    val Array(n, m) = StdIn.readLine().split(" ").map(_.toInt)
    val g = Array.fill(n)(ArrayBuffer[Int]())
    val len = Array.fill(n)(1)
    val ct = Array.fill(n)(0)
    for (i <- 0 until m) {
      val Array(u, v) = StdIn.readLine().split(" ").map(_.toInt - 1)
      g(u).append(v)
      g(v).append(u)
      ct(u) += 1
      ct(v) += 1
    }
    for (v <- 0 until n) {
      for (u <- g(v) if u > v) {
        len(u) = len(u).max(len(v) + 1)
      }
    }
    var ans = 0
    for (v <- 0 until n) {
      ans = ans.max(len(v) * ct(v))
    }
    println(ans)
  }
}

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Long](n)
        val len = new Array[Long](n)
        val edges = new Array[HashSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new HashSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            var k = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(k + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(len(i) * spines(i))
        }
        println(result)
    }
}

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.TreeSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Int](n)
        val len = new Array[Int](n)
        val edges = new Array[TreeSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new TreeSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            var k = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(k + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(1L * len(i) * spines(i))
        }
        println(result)
    }
}

import scala.io.Source
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

object CF338B {

    def main(args: Array[String]) {
        val r = Source.stdin.bufferedReader()
        var ss = r.readLine().split(" ")
        val n = ss(0).toInt
        val m = ss(1).toInt
        val spines = new Array[Int](n)
        val len = new Array[Int](n)
        val edges = new Array[HashSet[Int]](n)
        for (i <- 0 until n) {
            edges(i) = new HashSet[Int]
        }
        for (i <- 0 until m) {
            ss = r.readLine().split(" ")
            val u = ss(0).toInt - 1
            val v = ss(1).toInt - 1
            spines(u) += 1
            spines(v) += 1
            val min = u.min(v)
            val max = u.max(v)
            edges(min).add(max)
        }
        for (i <- 0 until n) {
            var k = len(i).max(1)
            for (end <- edges(i)) {
                len(end) = len(end).max(k + 1)
            }
        }
        var result = 0L
        for (i <- 0 until n) {
            result = result.max(1L * len(i) * spines(i))
        }
        println(result)
    }
}

import scala.collection.immutable.TreeMap
import scala.collection.mutable
import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)

  val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>
    Seq((j, i), (i, j))
  }
  val mapOfSegments = TreeMap(listOfSegments.groupBy(_._1).toSeq: _*)

  val mapOfTail = mutable.Map[Int, (Int, Int)]()

  def findTail(point: Int): (Int, Int) = {
    mapOfTail.getOrElseUpdate(point,
      mapOfSegments.getOrElse(point, Nil).filter { case (s, e) => e > s }.map { p =>
        findTail(p._2)
      } match {
        case Nil => (1, point)
        case l =>
          val (len, endPoint) = l.maxBy(_._1)
          (len + 1, endPoint)
      }
    )
  }

  val output = {
    for {
      i <- 1 to numOfPoints
    } yield {
      val (tail, endPoint) = findTail(i)
      val spine = mapOfSegments.get(endPoint).map(_.length).get
      tail * spine
    }
  }.max

  println(output)
}

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

/**
  * Created by hsleep on 2016. 1. 8..
  */
object BSolution extends App {
  val Array(numOfPoints, numOfSegments) = StdIn.readLine().split(' ').map(_.toInt)

  val listOfSegments = (0 until numOfSegments).map(_ => StdIn.readLine().split(' ').map(_.toInt)).flatMap { case Array(i, j) =>
    Seq((j, i), (i, j))
  }
  val mapOfSegments = listOfSegments.groupBy(_._1)

  val mapOfTail = mutable.Map[Int, Int]()

  def calcBeauty(point: Int): Long = {
    val listOfSpine = mapOfSegments.getOrElse(point, Nil)
    val tail = listOfSpine.filter { case (s, e) => e < s }.map { p =>
      mapOfTail(p._2)
    } match {
      case l if l.isEmpty => 1
      case l => l.max + 1
    }

    mapOfTail(point) = tail
    tail * listOfSpine.length
  }

  val output = {
    for {
      i <- 1 to numOfPoints
    } yield {
      calcBeauty(i)
    }
  }.max

  println(output)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.ofDim[Boolean](n)
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start)) max
    else {
     visited(start) = true
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)).max)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.fill[Int](n){ -1 }
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start) >= length) max
    else {
      visited(start) = length
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)).max)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.ofDim[Int](n)
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start) >= length) max
    else {
      visited(start) = length
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).sorted.map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)).max)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val visited = Array.ofDim[Boolean](n)
  val weight = Array.ofDim[Int](n)
  val edges = Array.fill[List[Int]](n){ Nil }

  in.take(m).map(_.split(' ').map(_.toInt - 1)).foreach { i =>
    val min = Math.min(i.head, i.last)
    val max = Math.max(i.head, i.last)
    weight(min) += 1
    weight(max) += 1
    edges(min) ::= max
  }

  def result(start: Int, max: Int, length: Int): Int = {
    if (visited(start)) max
    else {
//      visited(start) = true
      val nLength = length + 1
      val nMax = Math.max(max, nLength * weight(start))
      edges(start).map(to => result(to, nMax, nLength)).sorted.reverse.headOption.getOrElse(nMax)
    }
  }

  println((0 until n).map(i => result(i, 0, 0)))

}


You invited $$$n$$$ guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the $$$i$$$-th guest wants to have a least $$$l_i$$$ free chairs to the left of his chair, and at least $$$r_i$$$ free chairs to the right. The "left" and "right" directions are chosen assuming all guests are going to be seated towards the center of the circle. Note that when a guest is the only one in his circle, the $$$l_i$$$ chairs to his left and $$$r_i$$$ chairs to his right may overlap.What is smallest total number of chairs you have to use?

First line contains one integer $$$n$$$  — number of guests, ($$$1 \leqslant n \leqslant 10^5$$$).  Next $$$n$$$ lines contain $$$n$$$ pairs of space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \leqslant l_i, r_i \leqslant 10^9$$$).

Output a single integer — the smallest number of chairs you have to use.

NoteIn the second sample the only optimal answer is to use two circles: a circle with $$$5$$$ chairs accomodating guests $$$1$$$ and $$$2$$$, and another one with $$$10$$$ chairs accomodationg guests $$$3$$$ and $$$4$$$.In the third sample, you have only one circle with one person. The guest should have at least five free chairs to his left, and at least six free chairs to his right to the next person, which is in this case the guest herself. So, overall number of chairs should be at least 6+1=7.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val L, R = Array.ofDim[Int](N)
    rep(N) { i =>
      L(i) = ni()
      R(i) = ni()
    }

    radixSort(L)
    radixSort(R)

    var ans = 0L
    ans += N
    rep(N) { i =>
      ans += max(L(i), R(i))
    }
    out.println(ans)
  }

  def radixSort(f: Array[Int]): Array[Int] = radixSort(f, f.length)
  def radixSort(as: Array[Int], n: Int): Array[Int] = {
    val n = as.length
    val xs = Array(as, new Array[Int](n))
    val b = Array.ofDim[Int](65537)

    def step(k: Int, x: Int): Unit = {
      rep(n){ i => b(1 + (xs(x)(i) >>> k & 0xffff)) += 1 }
      rep(65536, 1){ i => b(i) += b(i - 1) }
      rep(n){ i =>
        val j = xs(x)(i) >>> k & 0xffff
        xs(x ^ 1)(b(j)) = xs(x)(i)
        b(j) += 1
      }
    }

    step(0, 0)
    java.util.Arrays.fill(b, 0)
    step(16, 1)

    as
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val L, R = Array.ofDim[Int](N)
    rep(N) { i =>
      L(i) = ni()
      R(i) = ni()
    }

    val ans = max(sumL(L), sumL(R)) + N
    out.println(ans)
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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


Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right.Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting balls (one at a time) to the boxes with numbers i + 1, i + 2, i + 3 and so on. If Vasya puts a ball into the box number n, then the next ball goes to box 1, the next one goes to box 2 and so on. He did it until he had no balls left in his hands. It is possible that Vasya puts multiple balls to the same box, and it is also possible that one or more balls will go to the box number i. If i = n, Vasya puts the first ball into the box number 1, then the next ball goes to box 2 and so on. For example, let's suppose that initially Vasya had four boxes, and the first box had 3 balls, the second one had 2, the third one had 5 and the fourth one had 4 balls. Then, if i = 3, then Vasya will take all five balls out of the third box and put them in the boxes with numbers: 4, 1, 2, 3, 4. After all Vasya's actions the balls will lie in the boxes as follows: in the first box there are 4 balls, 3 in the second one, 1 in the third one and 6 in the fourth one.At this point Vasya has completely forgotten the original arrangement of the balls in the boxes, but he knows how they are arranged now, and the number x — the number of the box, where he put the last of the taken out balls.He asks you to help to find the initial arrangement of the balls in the boxes.

The first line of the input contains two integers n and x (2 ≤ n ≤ 105, 1 ≤ x ≤ n), that represent the number of the boxes and the index of the box that got the last ball from Vasya, correspondingly. The second line contains n space-separated integers a1, a2, ..., an, where integer ai (0 ≤ ai ≤ 109, ax ≠ 0) represents the number of balls in the box with index i after Vasya completes all the actions.  Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

Print n integers, where the i-th one represents the number of balls in the box number i before Vasya starts acting. Separate the numbers in the output by spaces. If there are multiple correct solutions, you are allowed to print any of them.

import scala.language.postfixOps
import java.io._

object CF_260C {

    def main(args: Array[String]) {
        val stdin = new BufferedReader(new InputStreamReader(System.in));
        val stdout = new PrintWriter(new BufferedOutputStream(System.out));
        val inp_args = stdin.readLine.split(" ");
        val n = inp_args(0).toLong;
        val x = inp_args(1).toLong - 1;
        val end_list = stdin.readLine.split(" ").toArray.map(_.toLong);
        val min = end_list.min
        val min_inds = {
            for( i <- 0 until end_list.length if end_list(i) == min )
                yield(i)
        }
        val lower_mins = min_inds filter(_ <= x);
        val start_pos: Int = {
            if( lower_mins.isEmpty )
                min_inds.last
            else
                lower_mins.last
        }
        val tmp_list = end_list.map(_ - min);
        val start_pos_value : Long = min * n + { if( x >= start_pos ) x - start_pos else x + n - start_pos };
        val start_list: Array[Long] =
            for( i <- 0 until tmp_list.length toArray ) yield
                if( i == start_pos )
                    start_pos_value
                else if( ( x >= start_pos && i > start_pos && i <= x ) || ( x < start_pos && ( i > start_pos || i <= x ) ) )
                    tmp_list(i) - 1
                else
                    tmp_list(i)

        for( i <- 0 until start_list.length )
            stdout.print(start_list(i).toString + " ");

        stdout.println();
        stdout.close();
    }
}

object CF260C extends App {

  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

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

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve = {
    val n = nextInt
    val x = nextInt - 1
    var a = (for (i <- 0 until n) yield nextLong).toArray

    var c = 0l
    var min = a.min
    if (min > 0) {
      a = a map { _ - min }
      c = min * n
    }

    var finished = false
    var i = x
    while (!finished) {
      if (a(i) == 0) {
        finished = true
        a(i) = c
      } else {
        a(i) -= 1
        c += 1
        i = if (i == 0) n - 1 else i - 1
      }
    }

    a foreach((x) => out.print(x + " "))
    out.println()
  }

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

import java.io._

object CF_260C {

    def main(args: Array[String]) {
        val stdin = new BufferedReader(new InputStreamReader(System.in));
        val stdout = new PrintWriter(new BufferedOutputStream(System.out));
        val inp_args = stdin.readLine.split(" ");
        val n = inp_args(0).toInt;
        val x = inp_args(1).toInt - 1;
        val end_list = stdin.readLine.split(" ").toArray.map(_.toInt);
        val min = end_list.min
        val min_inds = {
            for( i <- 0 until end_list.length if end_list(i) == min )
                yield(i)
        }
        val lower_mins = min_inds filter(_ <= x);
        val start_pos: Int = {
            if( lower_mins.isEmpty )
                min_inds.last
            else
                lower_mins.last
        }
        val tmp_list = end_list.map(_ - min);
        val start_pos_value = min * n + { if( x >= start_pos ) x - start_pos else x + n - start_pos };
        val start_list =
            for( i <- 0 until tmp_list.length ) yield
                if( i == start_pos )
                    start_pos_value
                else if( ( x >= start_pos && i > start_pos ) || ( x < start_pos && ( i > start_pos || i <= x ) ) )
                    tmp_list(i) - 1
                else
                    tmp_list(i)

        for( i <- 0 until start_list.length )
            stdout.print(start_list(i).toString + " ");

        stdout.println();
        stdout.close();
    }
}


«Polygon» is a system which allows to create programming tasks in a simple and professional way. When you add a test to the problem, the corresponding form asks you for the test index. As in most cases it is clear which index the next test will have, the system suggests the default value of the index. It is calculated as the smallest positive integer which is not used as an index for some previously added test.You are to implement this feature. Create a program which determines the default index of the next test, given the indexes of the previously added tests.

The first line contains one integer n (1 ≤ n ≤ 3000) — the amount of previously added tests. The second line contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ 3000) — indexes of these tests.

Output the required default value for the next test index.

object P027A {
  def main(args: Array[String]) = {
    var s = scala.collection.mutable.Set((1 to readInt+1) :_*)
    readLine.split(' ').map(x => x.toInt).foreach(x => s.remove(x))
    println(s min)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).toSet
  println((1 to 3001).find{i => !data.contains(i)}.get)
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt).toSet
    val rest = Set() ++ ((1 to 3001)) -- a
    println(rest.min)
  }
}


You have a board represented as a grid with $$$2 \times n$$$ cells.The first $$$k_1$$$ cells on the first row and first $$$k_2$$$ cells on the second row are colored in white. All other cells are colored in black.You have $$$w$$$ white dominoes ($$$2 \times 1$$$ tiles, both cells are colored in white) and $$$b$$$ black dominoes ($$$2 \times 1$$$ tiles, both cells are colored in black).You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.Can you place all $$$w + b$$$ dominoes on the board if you can place dominoes both horizontally and vertically?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$k_1$$$ and $$$k_2$$$ ($$$1 \le n \le 1000$$$; $$$0 \le k_1, k_2 \le n$$$). The second line of each test case contains two integers $$$w$$$ and $$$b$$$ ($$$0 \le w, b \le n$$$).

For each test case, print YES if it's possible to place all $$$w + b$$$ dominoes on the board and NO, otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first test case, $$$n = 1$$$, $$$k_1 = 0$$$ and $$$k_2 = 1$$$. It means that $$$2 \times 1$$$ board has black cell $$$(1, 1)$$$ and white cell $$$(2, 1)$$$. So, you can't place any white domino, since there is only one white cell.In the second test case, the board of the same size $$$2 \times 1$$$, but both cell are white. Since $$$w = 0$$$ and $$$b = 0$$$, so you can place $$$0 + 0 = 0$$$ dominoes on the board.In the third test case, board $$$2 \times 3$$$, but fully colored in black (since $$$k_1 = k_2 = 0$$$), so you can't place any white domino.In the fourth test case, cells $$$(1, 1)$$$, $$$(1, 2)$$$, $$$(1, 3)$$$, and $$$(2, 1)$$$ are white and other cells are black. You can place $$$2$$$ white dominoes at positions $$$((1, 1), (2, 1))$$$ and $$$((1, 2), (1, 3))$$$ and $$$2$$$ black dominoes at positions $$$((1, 4), (2, 4))$$$ $$$((2, 2), (2, 3))$$$.

object cf1499a {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		for (nCase <- 1 to cases) {
			val l1 = readInts()
			val l2 = readInts()
			val n = l1(0) // row length (columns)
			val k1 = l1(1) // whites on r1
			val k2 = l1(2) // whites on r2
			val w	=	l2(0)
			val b = l2(1)

			val (mink, maxk) = if (k1 < k2) (k1, k2) else (k2, k1)
			val wfits = (w <= (mink + (maxk-mink)/2))
			lazy val bfits = (b <= (n-maxk + (maxk-mink)/2))
			if (wfits && bfits)
				println("YES")
			else
				println ("NO")
    }
  }
}


Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases by $$$1$$$. If he manages to finish the level successfully then the number of clears increases by $$$1$$$ as well. Note that both of the statistics update at the same time (so if the player finishes the level successfully then the number of plays will increase at the same time as the number of clears).Polycarp is very excited about his level, so he keeps peeking at the stats to know how hard his level turns out to be.So he peeked at the stats $$$n$$$ times and wrote down $$$n$$$ pairs of integers — $$$(p_1, c_1), (p_2, c_2), \dots, (p_n, c_n)$$$, where $$$p_i$$$ is the number of plays at the $$$i$$$-th moment of time and $$$c_i$$$ is the number of clears at the same moment of time. The stats are given in chronological order (i.e. the order of given pairs is exactly the same as Polycarp has written down).Between two consecutive moments of time Polycarp peeked at the stats many players (but possibly zero) could attempt the level.Finally, Polycarp wonders if he hasn't messed up any records and all the pairs are correct. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then he considers his records correct.Help him to check the correctness of his records.For your convenience you have to answer multiple independent test cases.

The first line contains a single integer $$$T$$$ $$$(1 \le T \le 500)$$$ — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of moments of time Polycarp peeked at the stats. Each of the next $$$n$$$ lines contains two integers $$$p_i$$$ and $$$c_i$$$ ($$$0 \le p_i, c_i \le 1000$$$) — the number of plays and the number of clears of the level at the $$$i$$$-th moment of time. Note that the stats are given in chronological order.

For each test case print a single line. If there could exist such a sequence of plays (and clears, respectively) that the stats were exactly as Polycarp has written down, then print "YES". Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case at the third moment of time the number of clears increased but the number of plays did not, that couldn't have happened.The second test case is a nice example of a Super Expert level.In the third test case the number of plays decreased, which is impossible.The fourth test case is probably an auto level with a single jump over the spike.In the fifth test case the number of clears decreased, which is also impossible.Nobody wanted to play the sixth test case; Polycarp's mom attempted it to make him feel better, however, she couldn't clear it.

object A extends App {
  case class Stat(p: Int, c: Int)

  implicit def arr2stat(arr: Array[Int]): Stat = arr match {
    case Array(p, c) => Stat(p, c)
    case _           => throw new IllegalArgumentException
  }

  private def isCorrect(s: Stat): Boolean = s.p >= s.c

  private def isCorrect(s1: Stat, s2: Stat): Boolean =
    isCorrect(s1) && isCorrect(s2) &&
      s1.p <= s2.p && s1.c <= s2.c && (s2.c - s1.c) <= (s2.p - s1.p)

  @scala.annotation.tailrec
  private def isCorrect(stats: List[Stat]): Boolean = stats match {
    case Nil              => true
    case s :: Nil         => isCorrect(s)
    case s1 :: s2 :: rest => isCorrect(s1, s2) && isCorrect(s2 :: rest)
  }

  val t = scala.io.StdIn.readInt()

  val stats = (0 until t)
    .foldLeft(List.empty[List[Stat]]) { (acc1, _) =>
      val n = scala.io.StdIn.readInt()

      val ss = (0 until n)
        .foldLeft(List.empty[Stat]) { (acc2, _) =>
          val s = scala.io.StdIn.readLine().split(" ").map(_.toInt)
          s :: acc2
        }
        .reverse

      ss :: acc1
    }
    .reverse

  val answers = stats.map(isCorrect)

  answers.foreach(if (_) println("YES") else println("NO"))
}

import scala.io.StdIn.readLine

object Main {
    def main(args: Array[String]) = {
        val T = readLine.toInt
        for (_ <- 0 until T) {
            val n = readLine.toInt
            val (p, c) = (0 until n)
                                    .map(_ => readLine.split(' ').map(_.toInt))
                                    .map{ case Array(x, y) => (x, y) }
                                    .unzip
            val p_diff =  p.zip(p drop 1) map {case (x, y) => y - x}
            val c_diff =  c.zip(c drop 1) map {case (x, y) => y - x}

            if (c_diff.forall(_ >= 0) && (c_diff zip p_diff).forall{case (c, p) => c <= p} && c.head <= p.head) {
                println("YES")
            } else {
                println("NO")
            }
        }
    }
}

import scala.io.StdIn.readLine

object Main {
    def main(args: Array[String]) = {
        val T = readLine.toInt
        for (_ <- 0 until T) {
            val n = readLine.toInt
            val (p, c) = (0 until n)
                                    .map(_ => readLine.split(' ').map(_.toInt))
                                    .map{ case Array(x, y) => (x, y) }
                                    .unzip
            val p_diff =  p.zip(p drop 1) map {case (x, y) => y - x}
            val c_diff =  c.zip(c drop 1) map {case (x, y) => y - x}

            if (c_diff.forall(_ >= 0) && (c_diff zip p_diff).forall{case (c, p) => c <= p}) {
                println("YES")
            } else {
                println("NO")
            }
        }
    }
}