This problem is same as the next one, but has smaller constraints.Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.For each of the $$$n$$$ days since the day Shiro moved to the new house, there will be exactly one cat coming to the Shiro's house. The cat coming in the $$$i$$$-th day has a ribbon with color $$$u_i$$$. Shiro wants to know the largest number $$$x$$$, such that if we consider the streak of the first $$$x$$$ days, it is possible to remove exactly one day from this streak so that every ribbon color that has appeared among the remaining $$$x - 1$$$ will have the same number of occurrences.For example, consider the following sequence of $$$u_i$$$: $$$[2, 2, 1, 1, 5, 4, 4, 5]$$$. Then $$$x = 7$$$ makes a streak, since if we remove the leftmost $$$u_i = 5$$$, each ribbon color will appear exactly twice in the prefix of $$$x - 1$$$ days. Note that $$$x = 8$$$ doesn't form a streak, since you must remove exactly one day. Since Shiro is just a cat, she is not very good at counting and needs your help finding the longest streak.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the total number of days. The second line contains $$$n$$$ integers $$$u_1, u_2, \ldots, u_n$$$ ($$$1 \leq u_i \leq 10$$$) — the colors of the ribbons the cats wear.

Print a single integer $$$x$$$ — the largest possible streak of days.

NoteIn the first example, we can choose the longest streak of $$$13$$$ days, since upon removing the last day out of the streak, all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, and $$$4$$$ will have the same number of occurrences of $$$3$$$. Note that the streak can also be $$$10$$$ days (by removing the $$$10$$$-th day from this streak) but we are interested in the longest streak.In the fourth example, if we take the streak of the first $$$6$$$ days, we can remove the third day from this streak then all of the remaining colors $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$ and $$$5$$$ will occur exactly once.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

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

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val C = Array.ofDim[Int](10)
    var ans = 0

    def test: Boolean = {
      map(10) { i =>
        if (C(i) > 0) {
          C(i) -= 1

          var num = 0
          var ok = true
          REP(10) { j =>
            if (C(j) != 0) {
              if (num != 0 && num != C(j)) {
                ok = false
              } else {
                num = C(j)
              }
            }
          }

          C(i) += 1
          ok
        } else {
          false
        }
      }.exists(identity)
    }

    REP(N) { i =>
      val u = ni() - 1
      C(u) += 1

      debug(C)
      if (test) ans = i + 1
    }

    out.println(ans)
  }
}

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

  override def apply(io: IO): io.type = {
    val nums = io.read[Vector[Int]]

    val numToCount, countToMap = mutable.Map.empty[Int, Int].withDefaultValue(0)
    val ans = nums map {i =>
      val curr = numToCount(i)
      if (curr > 0) {
        countToMap(curr) -= 1
        if (countToMap(curr) <= 0) countToMap.remove(curr)
      }
      numToCount(i) = curr + 1
      countToMap(curr + 1) += 1

      val it = countToMap.keysIterator

      val res = countToMap.size match {
        case 1 =>
          val c1 = it.next()
          c1 == 1 || countToMap(c1) == 1
        case 2 =>
          val _c1, _c2 = it.next()
          val c1 = _c1 min _c2
          val c2 = _c1 max _c2

          ((c1 == 1) && countToMap(c1) == 1) ||
          (c1 == c2 - 1 && countToMap(c2) == 1)
        case _ => false
      }
      //debug(i, numToCount, countToMap, res)
      res
    }

    io.write(ans.lastIndexWhere(identity) + 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()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

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

object Codeforces1163B {

  def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {
    val isStreak = new Array[Boolean](n)
    val colorFrequencyMap = new mutable.HashMap[Int, Int]()
    val countTracker = new FrequencyCountTracker
    for (i <- 0 until n) {
      val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)
      colorFrequencyMap(u(i)) = previousFrequency + 1

      countTracker.decreaseCount(previousFrequency)
      countTracker.increaseCount(previousFrequency + 1)

      isStreak(i) = countTracker.isEqualFrequencyByRemovingOne
    }
    for (i <- isStreak.indices.reverse) {
      if (isStreak(i)) return i + 1
    }
    1
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val u = StdIn.readLine().trim.split(" ").map(_.toInt)
    val longestPossibleStreak = getLongestPossibleStreak(n, u)
    println(longestPossibleStreak)
  }

  class FrequencyCountTracker {
    val frequencyCountMap = new mutable.HashMap[Int, Int]()

    def increaseCount(frequency: Int): Unit = {
      val previousFrequencyCount = frequencyCountMap.getOrElse(frequency, 0)
      frequencyCountMap(frequency) = previousFrequencyCount + 1
    }

    def decreaseCount(frequency: Int): Unit = {
      if (frequency == 0) return
      val previousFrequencyCount = frequencyCountMap(frequency)
      previousFrequencyCount match {
        case 1 => frequencyCountMap.remove(frequency)
        case _ => frequencyCountMap(frequency) = previousFrequencyCount - 1
      }
    }

    def isEqualFrequencyByRemovingOne: Boolean = {
      frequencyCountMap.keys.size match {
        case 1 =>
          frequencyCountMap.keys.head == 1 || frequencyCountMap.values.head == 1
        case 2 =>
          val maxFrequency = frequencyCountMap.keys.max
          val minFrequency = frequencyCountMap.keys.min
          if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true
          else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true
          else false
        case _ =>
          false
      }
    }
  }

}

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

object Codeforces1163B {

  def getLongestPossibleStreak(n: Int, u: Seq[Int]): Int = {
    val isStreak = new Array[Boolean](n)
    val colorFrequencyMap = new mutable.HashMap[Int, Int]()
    val countTracker = new FrequencyCountTracker
    for (i <- 0 until n) {
      val previousFrequency = colorFrequencyMap.getOrElse(u(i), 0)
      colorFrequencyMap(u(i)) = previousFrequency + 1

      countTracker.decreaseCount(previousFrequency)
      countTracker.increaseCount(previousFrequency + 1)

      isStreak(i) = countTracker.isEqualFrequencyByRemovingOne
    }
    for (i <- isStreak.indices.reverse) {
      if (isStreak(i)) return i + 1
    }
    1
  }

  def main(args: Array[String]): Unit = {
    val n = StdIn.readLine().trim.toInt
    val u = StdIn.readLine().trim.split(" ").map(_.toInt)
    val longestPossibleStreak = getLongestPossibleStreak(n, u)
    println(longestPossibleStreak)
  }

  class FrequencyCountTracker {
    val frequencyCountMap = new mutable.HashMap[Int, Int]()

    def increaseCount(frequency: Int): Unit = {
      val previousCount = frequencyCountMap.getOrElse(frequency, 0)
      frequencyCountMap(frequency) = previousCount + 1
    }

    def decreaseCount(frequency: Int): Unit = {
      if (frequency == 0) return
      val previousCount = frequencyCountMap(frequency)
      previousCount match {
        case 1 => frequencyCountMap.remove(frequency)
        case _ => frequencyCountMap(frequency) = previousCount - 1
      }
    }

    def isEqualFrequencyByRemovingOne: Boolean = {
      frequencyCountMap.keys.size match {
        case 1 =>
          frequencyCountMap.keys.head == 1
        case 2 =>
          val maxFrequency = frequencyCountMap.keys.max
          val minFrequency = frequencyCountMap.keys.min
          if (minFrequency == 1 && frequencyCountMap(minFrequency) == 1) true
          else if (minFrequency == maxFrequency - 1 && frequencyCountMap(maxFrequency) == 1) true
          else false
        case _ =>
          false
      }
    }
  }

}


The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:   ti < ti + 1 for each odd i < n;  ti > ti + 1 for each even i < n. For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.

The first line of the input contains one integer n (2 ≤ n ≤ 150 000) — the length of the sequence. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 150 000) — the initial sequence. It's guaranteed that the given sequence is not nice.

Print the number of ways to swap two elements exactly once in order to get a nice sequence.

NoteIn the first sample, there are two ways to get a nice sequence with one swap:   Swap t2 = 8 with t4 = 7.  Swap t1 = 2 with t5 = 7. In the second sample, there is only one way — Limak should swap t1 = 200 with t4 = 50.

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      val res = data.indices.foldLeft(0l) {
        case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
        case (sum, i) => sum
      }

      val doubles = invalid.map(i => validChanges(data, invalid, i)).sum
      println(res + doubles)
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      val res = data.indices.foldLeft(0l) {
        case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
        case (sum, i) => sum
      }

      val doubles = invalid.toList.map(i => validChanges(data, invalid, i)).sum / 2
      println(res + doubles)
    }
  }

}

import scala.collection.mutable.ArrayBuffer

object C extends App {

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

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

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int, z: Int, x: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = i != j && isValid(i) && isValid(j) && isValid(u) && isValid(v) && isValid(z) && isValid(x)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b, b, b)) res += 1
      for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a, a, a)) res += 1
    case Seq(a, b, c) =>
      if (canSwapWithCheck(a, c, b, b, b, b)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c, a, a)) res += 1
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d, a, a)) res += 1
      if (canSwapWithCheck(a, d, b, c, a, a)) res += 1
      if (canSwapWithCheck(b, c, a, d, a, a)) res += 1
      if (canSwapWithCheck(b, d, a, c, a, a)) res += 1
    case Seq(a, b, c, d, e) =>
      if (canSwapWithCheck(b, d, a, c, e, a)) res += 1
      if (canSwapWithCheck(b, e, a, c, d, a)) res += 1
      if (canSwapWithCheck(a, d, b, c, e, a)) res += 1
    case Seq(a, b, c, d, e, f) =>
      if (canSwapWithCheck(b, e, a, c, d, f)) res += 1
    case _ =>
  }

  println(res)
}

import scala.io.Source

object Solution extends App {

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

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }

    val doubles = invalid.indices.count(i => validChanges(data, invalid, i) != 0) / 2
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0l) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

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

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0l) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

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

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

//import scala.io.Source
//
//object Solution extends App {
//  val in = Source.stdin.getLines()
//  val n = in.next().toInt
//  val data = in.next().split(' ').map(_.toInt)
//  val indexValue = data.indices.foldLeft(Map.empty[Int, (Int, Int)]) {
//    case (acc, i) if !acc.contains(data(i)) =>
//      acc + (data(i) -> (i, 0))
//    case (acc, i) if acc(data(i))._2 == -1 => acc
//    case (acc, i) if acc(data(i))._2 == 0 =>
//      acc + (data(i) -> (i, i - acc(data(i))._1))
//    case (acc, i) =>
//      val distance = i - acc(data(i))._1
//      acc + (data(i) -> (i, if (acc(data(i))._2 == distance) distance else - 1))
//  }
//  println(indexValue.filter(_._2._2 >= 0).keys.toList.sorted.map{case v => s"$v ${indexValue(v)._2}"}.mkString("\n"))
//
//}ё

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      println(data.indices.foldLeft(0l) {
        case (sum, i) => sum + validChanges(data, invalid, i)
      } - 1)
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      val res = data.indices.foldLeft(0l) {
        case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
        case (sum, i) => sum
      }

      val doubles = invalid.map(i => validChanges(data, invalid, i)).sum
      println(res + doubles)
    }
  }

}

import scala.io.Source

object Solution extends App {

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

  def isValid(data: Array[Int], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Int], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }

    val doubles = invalid.indices.map(i => validChanges(data, invalid, i)).sum / 2
    println(res - doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet

    val res = data.indices.foldLeft(0l) {
      case (sum, i) if !invalid.contains(i) => sum + validChanges(data, invalid, i)
      case (sum, i) => sum
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum
//    println(doubles)
    println(res + doubles)
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int): Long = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = isValid(data, swapIndex) && invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    if (data(0) == data(1))
      println(0)
    else
      println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}.toSet
    if (invalid.size > 6)
      println(0)
    else {
      println(data.indices.foldLeft(0l) {
        case (sum, i) => sum + validChanges(data, invalid, i)
      })
    }
  }

}

import scala.io.Source

object Solution extends App {

  def swap(arr: Array[Long], i: Int, j: Int) {
    val tmp = arr(i)
    arr(i) = arr(j)
    arr(j) = tmp
  }

  def isValid(data: Array[Long], i: Int) =
    if (i % 2 == 0)
      ((i == data.length - 1) || data(i) < data(i + 1)) && (i == 0 || data(i) < data(i - 1))
    else
      ((i == data.length - 1) || data(i) > data(i + 1)) && data(i) > data(i - 1)

  def validChanges(data: Array[Long], invalidIndices: Iterable[Int], swapIndex: Int) = {
    invalidIndices.count{ j =>
      swap(data, swapIndex, j)
      val res = invalidIndices.forall(k => isValid(data, k))
      swap(data, swapIndex, j)
      swapIndex != j && res
    }
  }

  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toLong)
  if (n == 2)
    println(1)
  else {
    val invalid = data.indices.filterNot{i => isValid(data, i)}

    val res = data.indices.foldLeft(0l) {
      case (sum, i) => sum + validChanges(data, invalid, i)
    }
//    println(invalid)
//    println(res)

    val doubles = invalid.map(i => validChanges(data, invalid, i)).sum / 2
//    println(doubles)
    println(res - doubles)
  }

}

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

object C extends App {

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

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

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwap(i: Int, j: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j)
    ts(i) = ti
    ts(j) = tj
    can
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j) && isValid(u) && isValid(v)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwap(a, i)) res += 1
      for (i <- ts.indices) if (i != a && canSwap(b, i)) res += 1
    case Seq(a, b, c) =>
      if (canSwap(a, c)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(a, d, b, c)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, c, a, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, d, a, c)) res += 1 //{println("a"); res += 1}
    case _ =>
  }

  println(res)
}

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

object C extends App {

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

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

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int, z: Int, x: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = i != j && isValid(i) && isValid(j) && isValid(u) && isValid(v) && isValid(z) && isValid(x)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b, b, b)) res += 1
      for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a, a, a)) res += 1
    case Seq(a, b, c) =>
      if (canSwapWithCheck(a, c, b, b, b, b)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c, a, a)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d, a, a)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(a, d, b, c, a, a)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, c, a, d, a, a)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, d, a, c, a, a)) res += 1 //{println("a"); res += 1}
    case Seq(a, b, c, d, e) =>
      if (canSwapWithCheck(b, d, a, c, e, a)) res += 1
    case Seq(a, b, c, d, e, f) =>
      if (canSwapWithCheck(b, e, a, c, d, f)) res += 1
    case _ =>
  }

  println(res)
}

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

object C extends App {

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

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

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwap(i: Int, j: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwap(a, i)) res += 1
      for (i <- ts.indices) if (i != a && canSwap(b, i)) res += 1
    case Seq(a, b, c) =>
      if (canSwap(a, c)) res += 1
      for (i <- ts.indices) if (canSwap(b, i)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwap(a, c)) res += 1 //{println("a"); res += 1}
      if (canSwap(a, d)) res += 1 //{println("a"); res += 1}
      if (canSwap(b, c)) res += 1 //{println("a"); res += 1}
      if (canSwap(b, d)) res += 1 //{println("a"); res += 1}
    case _ =>
  }

  println(res)
}

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

object C extends App {

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

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

  val errs = ArrayBuffer.empty[Int]

  def isValid(i: Int) = {
    val t = ts(i)
    if (i % 2 == 0) {
      !((i > 0 && t >= ts(i - 1)) || (i < n - 1 && t >= ts(i + 1)))
    } else {
      !((i > 0 && t <= ts(i - 1)) || (i < n - 1 && t <= ts(i + 1)))
    }
  }

  def canSwap(i: Int, j: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j)
    ts(i) = ti
    ts(j) = tj
    can
  }

  def canSwapWithCheck(i: Int, j: Int, u: Int, v: Int) = {
    val ti = ts(i)
    val tj = ts(j)
    ts(i) = tj
    ts(j) = ti
    val can = isValid(i) && isValid(j) && isValid(u) && isValid(v)
    ts(i) = ti
    ts(j) = tj
    can
  }

  for (i <- ts.indices) {
    if (!isValid(i)) errs += i
  }

  var res = 0L

  //println(errs)

  errs match {
    case Seq(a, b) =>
      for (i <- ts.indices) if (canSwapWithCheck(a, i, b, b)) res += 1
      for (i <- ts.indices) if (i != a && canSwapWithCheck(b, i, a, a)) res += 1
    case Seq(a, b, c) =>
      if (canSwapWithCheck(a, c, b, b)) res += 1
      for (i <- ts.indices) if (canSwapWithCheck(b, i, a, c)) {
        //println(i)
        res += 1
      }
    case Seq(a, b, c, d) =>
      if (canSwapWithCheck(a, c, b, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(a, d, b, c)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, c, a, d)) res += 1 //{println("a"); res += 1}
      if (canSwapWithCheck(b, d, a, c)) res += 1 //{println("a"); res += 1}
    case _ =>
  }

  println(res)
}


Ivar the Boneless is a great leader. He is trying to capture Kattegat from Lagertha. The war has begun and wave after wave Ivar's warriors are falling in battle.Ivar has $$$n$$$ warriors, he places them on a straight line in front of the main gate, in a way that the $$$i$$$-th warrior stands right after $$$(i-1)$$$-th warrior. The first warrior leads the attack.Each attacker can take up to $$$a_i$$$ arrows before he falls to the ground, where $$$a_i$$$ is the $$$i$$$-th warrior's strength.Lagertha orders her warriors to shoot $$$k_i$$$ arrows during the $$$i$$$-th minute, the arrows one by one hit the first still standing warrior. After all Ivar's warriors fall and all the currently flying arrows fly by, Thor smashes his hammer and all Ivar's warriors get their previous strengths back and stand up to fight again. In other words, if all warriors die in minute $$$t$$$, they will all be standing to fight at the end of minute $$$t$$$.The battle will last for $$$q$$$ minutes, after each minute you should tell Ivar what is the number of his standing warriors.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \leq 200\,000$$$) — the number of warriors and the number of minutes in the battle. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) that represent the warriors' strengths. The third line contains $$$q$$$ integers $$$k_1, k_2, \ldots, k_q$$$ ($$$1 \leq k_i \leq 10^{14}$$$), the $$$i$$$-th of them represents Lagertha's order at the $$$i$$$-th minute: $$$k_i$$$ arrows will attack the warriors.

Output $$$q$$$ lines, the $$$i$$$-th of them is the number of standing warriors after the $$$i$$$-th minute.

NoteIn the first example:   after the 1-st minute, the 1-st and 2-nd warriors die.  after the 2-nd minute all warriors die (and all arrows left over are wasted), then they will be revived thus answer is 5 — all warriors are alive.  after the 3-rd minute, the 1-st warrior dies.  after the 4-th minute, the 2-nd warrior takes a hit and his strength decreases by 1.  after the 5-th minute, the 2-nd warrior dies.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader
    val n, q = r.read[Int]
    val as = r.read[Array[Long]](n).scanLeft(0L){ case (acc, a) => a + acc }
    val ks = r.read[Array[Long]](q)

    ks.foldLeft((0, 0L)) {
      case ((i, d), k) => {
        val kd = k + d
        if (as(n) <= kd) {
          println(n)
          (0, 0)
        } else {
          val j = lb(as(_) >= kd, i, n)
          if (as(j+1) == kd) {
            println(n-j-1)
            (j+1, kd)
          } else {
            println(n-j)
            (j, kd)
          }
        }
      }
    }
  }

  def lb(test: (Int => Boolean), from: Int, to: Int) = {
    import annotation.tailrec
    @tailrec
    def go(l: Int, r: Int): Int =
      if (l <= r) {
        val m = (r + l) / 2
        if (test(m)) go(l, m - 1) else go(m + 1, r)
      } else r

    go(from, to)
  }
}

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

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

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

  val tokenizer = new Tokenizer(br)
}

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

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

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

    import scala.collection.generic.CanBuildFrom

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

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

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

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

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

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


You are given two huge binary integer numbers $$$a$$$ and $$$b$$$ of lengths $$$n$$$ and $$$m$$$ respectively. You will repeat the following process: if $$$b > 0$$$, then add to the answer the value $$$a~ \&~ b$$$ and divide $$$b$$$ by $$$2$$$ rounding down (i.e. remove the last digit of $$$b$$$), and repeat the process again, otherwise stop the process.The value $$$a~ \&~ b$$$ means bitwise AND of $$$a$$$ and $$$b$$$. Your task is to calculate the answer modulo $$$998244353$$$.Note that you should add the value $$$a~ \&~ b$$$ to the answer in decimal notation, not in binary. So your task is to calculate the answer in decimal notation. For example, if $$$a = 1010_2~ (10_{10})$$$ and $$$b = 1000_2~ (8_{10})$$$, then the value $$$a~ \&~ b$$$ will be equal to $$$8$$$, not to $$$1000$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the length of $$$b$$$ correspondingly. The second line of the input contains one huge integer $$$a$$$. It is guaranteed that this number consists of exactly $$$n$$$ zeroes and ones and the first digit is always $$$1$$$. The third line of the input contains one huge integer $$$b$$$. It is guaranteed that this number consists of exactly $$$m$$$ zeroes and ones and the first digit is always $$$1$$$.

Print the answer to this problem in decimal notation modulo $$$998244353$$$.

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 = 998244353
  val out = new PrintWriter(System.out)

  val pow2 = Array.ofDim[Long](2e5.toInt + 1)
  pow2(0) = 1
  rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2 % MOD)

  def solve(): Unit = {
    val N, M = ni()
    val A = ns(N)
    val B = ns(M)

    val cum = Array.ofDim[Int](M + 1)
    rep(M) { i =>
      cum(i + 1) = cum(i) + (if (B(i) == '1') 1 else 0)
    }
    var ans = 0L
    val diff = M - N
    rep(N) { i =>
      val k = N - 1 - i
      if (A(i) == '1') {
        val cnt = if (i + 1 + diff >= 0) cum(i + 1 + diff) else 0
        ans = (ans + pow2(k) * cnt) % MOD
      }
    }

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


Toad Zitz has an array of integers, each integer is between $$$0$$$ and $$$m-1$$$ inclusive. The integers are $$$a_1, a_2, \ldots, a_n$$$.In one operation Zitz can choose an integer $$$k$$$ and $$$k$$$ indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$1 \leq i_1 < i_2 < \ldots < i_k \leq n$$$. He should then change $$$a_{i_j}$$$ to $$$((a_{i_j}+1) \bmod m)$$$ for each chosen integer $$$i_j$$$. The integer $$$m$$$ is fixed for all operations and indices.Here $$$x \bmod y$$$ denotes the remainder of the division of $$$x$$$ by $$$y$$$.Zitz wants to make his array non-decreasing with the minimum number of such operations. Find this minimum number of operations.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 300\,000$$$) — the number of integers in the array and the parameter $$$m$$$. The next line contains $$$n$$$ space-separated integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_i < m$$$) — the given array.

Output one integer: the minimum number of described operations Zitz needs to make his array non-decreasing. If no operations required, print $$$0$$$. It is easy to see that with enough operations Zitz can always make his array non-decreasing.

NoteIn the first example, the array is already non-decreasing, so the answer is $$$0$$$.In the second example, you can choose $$$k=2$$$, $$$i_1 = 2$$$, $$$i_2 = 5$$$, the array becomes $$$[0,0,1,3,3]$$$. It is non-decreasing, so the answer is $$$1$$$.

object A extends App {

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

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

  def can(lim: Long): Boolean = {
    var prev = 0L
    var ok = true
    for (a <- as) {
      val max = if (a + lim >= m && (a + lim) % m >= prev) prev
      else if (a < prev && a + lim >= prev) prev
      else a
      if (max < prev) ok = false
      prev = max
    }
    ok
  }

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

  val res = binSearch(0, m)

  println(res)
}


You are given the array $$$a$$$ consisting of $$$n$$$ elements and the integer $$$k \le n$$$.You want to obtain at least $$$k$$$ equal elements in the array $$$a$$$. In one move, you can make one of the following two operations:  Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of $$$a$$$ is $$$mn$$$ then you choose such index $$$i$$$ that $$$a_i = mn$$$ and set $$$a_i := a_i + 1$$$);  take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of $$$a$$$ is $$$mx$$$ then you choose such index $$$i$$$ that $$$a_i = mx$$$ and set $$$a_i := a_i - 1$$$). Your task is to calculate the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and the required number of equal elements. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum number of moves required to obtain at least $$$k$$$ equal elements in the array.

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0)
  val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumL = count * (a - 1L) - sum
      countL = count
    }
    sumsL(a) = sumL
    countsL(a) = countL
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumR = sum - count * (a + 1L)
      countR = count
    }
    sumsR(a) = sumR
    countsR(a) = countR
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0L)
  val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sum = 0L
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumsL(a) = count * (a - 1L) - sum
      countsL(a) = count
    }
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  sum = 0L
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumsR(a) = sum - count * (a + 1L)
      countsR(a) = count
    }
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long]
  val countsL, countsR = mutable.Map.empty[Int, Int]
  val counts = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumL = count * (a - 1L) - sum
      countL = count
    }
    sumsL(a) = sumL
    countsL(a) = countL
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumR = sum - count * (a + 1L)
      countR = count
    }
    sumsR(a) = sumR
    countsR(a) = countR
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted

  val sumsL, sumsR = mutable.Map.empty[Int, Long].withDefaultValue(0)
  val counts, countsL, countsR = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (a != prev) {
      sumL = count * (a - 1) - sum
      countL = count
    }
    sumsL(a) = sumL
    countsL(a) = countL
    sum += a
    count += 1
    counts(a) += 1
    prev = a
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  for (i <- n - 1 to 0 by -1) {
    val a = as(i)
    if (a != prev) {
      sumR = sum - count * (a + 1)
      countR = count
    }
    sumsR(a) = sumR
    countsR(a) = countR
    sum += a
    count += 1
    prev = a
  }

  var min = Long.MaxValue
  for (a <- as) {
    val need = k - counts(a)
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val leftCost0 = sumsL(a) + Math.min(need, countsL(a))
      val rightCost0 = sumsR(a) + Math.min(need, countsR(a))
      if (countsL(a) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(a) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(a) + countsR(a) >= need) {
        val costLR = sumsL(a) + sumsR(a) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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

import scala.collection.mutable

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

  val n, k = nextInt
  val as = nextInts(n).sorted
  //val ds = as.distinct

  val sumsL, sumsR = Array.ofDim[Long](n)
  val countsL, countsR, lefts, rights = Array.ofDim[Int](n)
  val counts = mutable.Map.empty[Int, Int].withDefaultValue(0)

  var prev = -1
  var sumL = 0L
  var sum = 0L
  var countL = 0
  var count = 0
  var left = -1
  for (i <- 0 until n) {
    if (as(i) != prev) {
      sumL = count * as(i) - sum
      countL = count
      left = i - 1
    }
    lefts(i) = left
    sumsL(i) = sumL
    countsL(i) = countL
    sum += as(i)
    count += 1
    counts(as(i)) += 1
    prev = as(i)
  }

  prev = -1
  var sumR = 0L
  sum = 0L
  var countR = 0
  count = 0
  var right = n
  for (i <- n - 1 to 0 by -1) {
    if (as(i) != prev) {
      sumR = sum - count * as(i)
      countR = count
      right = i + 1
    }
    rights(i) = right
    sumsR(i) = sumR
    countsR(i) = countR
    sum += as(i)
    count += 1
    prev = as(i)
  }

  var min = Long.MaxValue
//println(as.mkString(" "))
//  println(countsR.mkString(" "))
//  println(sumsR.mkString(" "))
//  println(counts)
  for (i <- 0 until n) {
    val need = k - counts(as(i))
    var cost = 0L
    if (need > 0) {
      cost = Long.MaxValue
      val l = lefts(i)
      val r = rights(i)
      val leftCost0 = if (l >= 0) sumsL(l) + Math.min(need, countsL(i)) else Long.MaxValue
      val rightCost0 = if (r < n) sumsR(r) + Math.min(need, countsR(i)) else Long.MaxValue
      if (countsL(i) >= need && leftCost0 < cost) cost = leftCost0
      if (countsR(i) >= need && rightCost0 < cost) cost = rightCost0
      if (cost == Long.MaxValue && countsL(i) + countsR(i) >= need && l >= 0 && r < n) {
        val costLR = sumsL(l) + sumsR(r) + need
        if (costLR < cost) cost = costLR
      }
    }
    if (cost < min) min = cost
  }

  out.println(min)

  out.flush()

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


You are given two arrays of integers a and b. For each element of the second array bj you should find the number of elements in array a that are less than or equal to the value bj.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the sizes of arrays a and b. The second line contains n integers — the elements of array a ( - 109 ≤ ai ≤ 109). The third line contains m integers — the elements of array b ( - 109 ≤ bj ≤ 109).

Print m integers, separated by spaces: the j-th of which is equal to the number of such elements in array a that are less than or equal to the value bj.

import scala.collection.mutable

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()

  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).sorted
  val b = in.next().split(' ').map(_.toInt)
  val map = mutable.Map.empty[Int, Long]
  var sum = 0l
  var startIndex = 0
  b.sorted.foreach { i =>
    while (startIndex < a.length && a(startIndex) <= i) {
      startIndex += 1
      sum += 1
    }
    map += (i -> sum)
  }
  println(b.map(map).mkString(" "))
}

object B600 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m)
    var res = 0

    for(i <- 0 until m) {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low + 1)/2

        if(a(mid) > b(i))
          high = mid - 1
        else
          low = mid
      }
      if(a(low) <= b(i))
        out.print(s"${low+1} ")
      else
        out.print("0 ")
    }

    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import java.util.Date

object task2 {
  def main(args: Array[String]) {
        val len = readLine().split(" ").map(_.toInt)

        val a = readLine().split(" ").map(_.toLong).sorted
        val b = readLine().split(" ").map(_.toLong)

        val res = b.map { bj =>
          val bb = findMoreThenEl(a, bj)
          if(bb != -1) bb else len(0)
        }.mkString(" ")
    println(res)
  }

  def findMoreThenEl(list: Array[Long], el: Long): Int = {
    def inner(from: Int, to: Int): Int = {
      val len = to - from
      val newCenter = from + (len / 2)
      if (len <= 1 && list(from) <= el && list(to) <= el) {
        -1
      }
      else if (len <= 1 && list(from) > el) {
        from
      } else if (len <= 1 && list(to) > el) {
        to
      }
      else if (list(newCenter) <= el) {
        inner(newCenter, to)
      }
      else {
        inner(from, newCenter)
      }
    }

    inner(0, list.length - 1)
  }
}

import java.util.Date

object task2 {
  def main(args: Array[String]) {
        val len = readLine().split(" ").map(_.toInt)

        val a = readLine().split(" ").map(_.toLong).sorted
        val b = readLine().split(" ").map(_.toLong)

        val res = b.map { bj =>

          val bb = if(a(0)>bj) 0
          else if(a(len(0)-1)<=bj) len(0)
          else  findMoreThenEl(a, bj)
          if(bb != -1) bb else len(0)
        }.mkString(" ")
    println(res)
  }

  def findMoreThenEl(list: Array[Long], el: Long): Int = {
    def inner(from: Int, to: Int): Int = {
      val len = to - from
      val newCenter = from + (len / 2)
      if (len <= 1 && list(from) <= el && list(to) <= el) {
        -1
      }
      else if (len <= 1 && list(from) > el) {
        from
      } else if (len <= 1 && list(to) > el) {
        to
      }
      else if (list(newCenter) <= el) {
        inner(newCenter, to)
      }
      else {
        inner(from, newCenter)
      }
    }

    inner(0, list.length - 1)
  }
}

object B600 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, m) = readInts(2)
    val a = readInts(n).sorted
    val b = readInts(m)
    var res = 0

    for(i <- 0 until m) {
      var low = 0
      var high = n - 1

      while(low < high) {
        val mid = low + (high - low + 1)/2

        if(a(mid) > b(i))
          high = mid - 1
        else
          low = mid
      }

      out.print(s"${low+1} ")
    }

    out.close()
  }

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

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

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

object task2 {
  def main (args: Array[String]){
    val len = readLine().split(" ")
    val a = readLine().split(" ")
    val b = readLine().split(" ")

    val res = b.map{bj =>a.count(ai=>ai<=bj)}.mkString(" ")

    println(res)
  }
}


Stephen Queen wants to write a story. He is a very unusual writer, he uses only letters 'a', 'b', 'c', 'd' and 'e'!To compose a story, Stephen wrote out $$$n$$$ words consisting of the first $$$5$$$ lowercase letters of the Latin alphabet. He wants to select the maximum number of words to make an interesting story.Let a story be a sequence of words that are not necessarily different. A story is called interesting if there exists a letter which occurs among all words of the story more times than all other letters together.For example, the story consisting of three words "bac", "aaada", "e" is interesting (the letter 'a' occurs $$$5$$$ times, all other letters occur $$$4$$$ times in total). But the story consisting of two words "aba", "abcde" is not (no such letter that it occurs more than all other letters in total).You are given a sequence of $$$n$$$ words consisting of letters 'a', 'b', 'c', 'd' and 'e'. Your task is to choose the maximum number of them to make an interesting story. If there's no way to make a non-empty story, output $$$0$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of the words in the sequence. Then $$$n$$$ lines follow, each of them contains a word — a non-empty string consisting of lowercase letters of the Latin alphabet. The words in the sequence may be non-distinct (i. e. duplicates are allowed). Only the letters 'a', 'b', 'c', 'd' and 'e' may occur in the words. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$; the sum of the lengths of all words over all test cases doesn't exceed $$$4 \cdot 10^5$$$.

For each test case, output the maximum number of words that compose an interesting story. Print 0 if there's no way to make a non-empty interesting story.

6
3
bac
aaada
e
3
aba
abcde
aba
2
baba
baba
4
ab
ab
c
bc
5
cbdca
d
a
d
e
3
b
c
ca

NoteIn the first test case of the example, all $$$3$$$ words can be used to make an interesting story. The interesting story is "bac aaada e".In the second test case of the example, the $$$1$$$-st and the $$$3$$$-rd words can be used to make an interesting story. The interesting story is "aba aba". Stephen can't use all three words at the same time.In the third test case of the example, Stephen can't make a non-empty interesting story. So the answer is $$$0$$$.In the fourth test case of the example, Stephen can use the $$$3$$$-rd and the $$$4$$$-th words to make an interesting story. The interesting story is "c bc".

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

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

    def main(args: Array[String]): Unit = {
        val t = readInt()
        val dp = Map[Char, ArrayBuffer[Int]]()
        val chars = Array('a', 'b', 'c', 'd', 'e')
        val ans = Map[Char, Int]()
        chars.foreach(x => dp(x) = new ArrayBuffer[Int]())
        var str = ""
        for (tt <- 1 to t) {
            chars.foreach(x => dp(x).clear())
            val n = readInt()
            for (i <- 1 to n) {
                str = readString()
                chars.foreach(x => dp(x).append(2*str.count(_ == x)-str.length))
            }
            chars.foreach(x => dp(x) = dp(x).sortWith(_>_))
            chars.foreach(x => {
                var cnt = 0
                var po = 0
                while (po < n && cnt + dp(x)(po) > 0){
                    cnt += dp(x)(po)
                    po += 1
                }
                ans(x) = po
            })
            writer.println(ans.values.max)
            writer.flush()
        }
    }
}


This is the hard version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.You are given a string $$$s$$$, consisting of lowercase English letters. Find the longest string, $$$t$$$, which satisfies the following conditions:   The length of $$$t$$$ does not exceed the length of $$$s$$$.  $$$t$$$ is a palindrome.  There exists two strings $$$a$$$ and $$$b$$$ (possibly empty), such that $$$t = a + b$$$ ( "$$$+$$$" represents concatenation), and $$$a$$$ is prefix of $$$s$$$ while $$$b$$$ is suffix of $$$s$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$), the number of test cases. The next $$$t$$$ lines each describe a test case. Each test case is a non-empty string $$$s$$$, consisting of lowercase English letters. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$10^6$$$.

For each test case, print the longest string which satisfies the conditions described above. If there exists multiple possible solutions, print any of them.

5
a
abcdfdcecba
abbaxyzyx
codeforces
acbba

NoteIn the first test, the string $$$s = $$$"a" satisfies all conditions.In the second test, the string "abcdfdcba" satisfies all conditions, because:  Its length is $$$9$$$, which does not exceed the length of the string $$$s$$$, which equals $$$11$$$.  It is a palindrome.  "abcdfdcba" $$$=$$$ "abcdfdc" $$$+$$$ "ba", and "abcdfdc" is a prefix of $$$s$$$ while "ba" is a suffix of $$$s$$$. It can be proven that there does not exist a longer string which satisfies the conditions.In the fourth test, the string "c" is correct, because "c" $$$=$$$ "c" $$$+$$$ "" and $$$a$$$ or $$$b$$$ can be empty. The other possible solution for this test is "s".

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }

  val M = 1000000009L
  val B = 37L
  val maxN = 1000001
  val POW = ((0 to maxN).scanLeft(1L){case (h,_) => (h*B)%M}).toArray
  val hashForward: Array[Long] = Array.fill(maxN)(0L)
  val hashBackward: Array[Long] = Array.fill(maxN)(0L)
  var N = 0
  def calcHash(a: Int,b: Int,hash: Array[Long]): Long = {
    //println(s"HASHING: $a : $b")
    ((hash(b)-(hash(a)*POW(b-a))%M)+M)%M
  }

  def isPal(left: Int,right: Int): Boolean = {
    val L = (left+right)
    val L_2 = L/2
    //println(s"left: $left : right: $right  :: L_2: $L_2")
    val hLeft = if(left>=right) {
        f(L_2,0,L_2)
    }else {
        f(left,N-right,L_2)
    }

    val hRight = if(left>=right) {
      g(right,N-left,L_2)
    }else{
      g(L_2,0,L_2)
    }

    hLeft == hRight
  }

  def f(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashForward))
  def g(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashBackward))

  def fg(i_incl: Int, j_incl: Int, length: Int, ch: (Int,Int) => Long): Long = {
    //println(s"fg $i_incl $j_incl length: $length")
    val leftHash = ch(0,i_incl)
    val d = length-i_incl
    val centerHash = ch(j_incl,j_incl+d)
    //println(s"$leftHash*POW($d) + $centerHash")
    ((leftHash*POW(d))%M + centerHash)%M
  }

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val numCases = in.nextInt()
    (1 to numCases).foreach{ _ =>
      val s = in.next()
      val sr = s.reverse
      N = s.length
      hashForward(0) = 0L
      s.zipWithIndex.foreach{
        case (ch,i) =>
          val v = ch.toInt-'a'.toInt+1
          hashForward(i+1)  = (hashForward(i) *B+v)%M
      }

      hashBackward(0) = 0L
      sr.zipWithIndex.foreach{
        case (ch,i) =>
          val v = ch.toInt-'a'.toInt+1
          hashBackward(i+1) = (hashBackward(i)*B+v)%M
      }

/*
      println(isPal(0,1))
      println(isPal(1,0))
      println(isPal(0,0))
      println(isPal(1,1))
      println(isPal(2,2))
      println(isPal(3,3))
      println(isPal(4,4))
      println(isPal(5,4))
      println(isPal(4,5))
*/

      var maxH = -1
      var isEqual = true
      (0 until N).foreach{ i =>
        if(s(i) == s(N-i-1) && isEqual){
          maxH = i
        }else{
          isEqual = false
        }
      }

      val L = if(maxH== -1) 0 else (Math.min(N/2,maxH+1))

      assert(isPal(L,L))

      val r0 = (0 to (N-2*L)).reverse.find{d =>isPal(L+d,L)}.get

      val r1 = (0 to (N-2*L)).reverse.find{d =>isPal(L,L+d)}.get

      //println(s"$L: $r0 - $r1")
      //println(hashForward.take(11).mkString(" - "))
      //println(hashBackward.take(11).mkString(" - "))
      val ans = if(r0>=r1){
        //println(isPal(L+r0,L))
        s.substring(0,L+r0)+s.substring(N-L)
      }else{
        //println(isPal(L,L+r1))
        s.substring(0,L)+s.substring(N-(L+r1))
      }
      out.println(ans)

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

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  val M = 16769023L
  val B = 37L
  val maxN = 1000001
  val POW = ((0 to maxN).scanLeft(1L){case (h,_) => (h*B)%M}).toArray
  val hashForward: Array[Long] = Array.fill(maxN)(0L)
  val hashBackward: Array[Long] = Array.fill(maxN)(0L)
  var N = 0
  def calcHash(a: Int,b: Int,hash: Array[Long]): Long = {
    //println(s"HASHING: $a : $b")
    ((hash(b)-(hash(a)*POW(b-a))%M)+M)%M
  }

  def isPal(left: Int,right: Int): Boolean = {
    val L = (left+right)
    val L_2 = L/2
    //println(s"left: $left : right: $right  :: L_2: $L_2")
    val hLeft = if(left>=right) {
        f(L_2,0,L_2)
    }else {
        f(left,N-right,L_2)
    }

    val hRight = if(left>=right) {
      g(right,N-left,L_2)
    }else{
      g(L_2,0,L_2)
    }

    hLeft == hRight
  }

  def f(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashForward))
  def g(i_incl: Int, j_incl: Int, length: Int): Long = fg(i_incl,j_incl,length,(a,b) => calcHash(a,b,hashBackward))

  def fg(i_incl: Int, j_incl: Int, length: Int, ch: (Int,Int) => Long): Long = {
    //println(s"fg $i_incl $j_incl length: $length")
    val leftHash = ch(0,i_incl)
    val d = length-i_incl
    val centerHash = ch(j_incl,j_incl+d)
    //println(s"$leftHash*POW($d) + $centerHash")
    ((leftHash*POW(d))%M + centerHash)%M
  }

  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val numCases = in.nextInt()
    (1 to numCases).foreach{ _ =>
      val s = in.next()
      val sr = s.reverse
      N = s.length
      hashForward(0) = 0L
      s.zipWithIndex.foreach{
        case (ch,i) =>
          val v = ch.toInt-'a'.toInt+1
          hashForward(i+1)  = (hashForward(i) *B+v)%M
      }

      hashBackward(0) = 0L
      sr.zipWithIndex.foreach{
        case (ch,i) =>
          val v = ch.toInt-'a'.toInt+1
          hashBackward(i+1) = (hashBackward(i)*B+v)%M
      }

/*
      println(isPal(0,1))
      println(isPal(1,0))
      println(isPal(0,0))
      println(isPal(1,1))
      println(isPal(2,2))
      println(isPal(3,3))
      println(isPal(4,4))
      println(isPal(5,4))
      println(isPal(4,5))
*/

      var maxH = -1
      var isEqual = true
      (0 until N).foreach{ i =>
        if(s(i) == s(N-i-1) && isEqual){
          maxH = i
        }else{
          isEqual = false
        }
      }

      val L = if(maxH== -1) 0 else (Math.min(N/2,maxH+1))

      assert(isPal(L,L))

      val r0 = (0 to (N-2*L)).reverse.find{d =>isPal(L+d,L)}.get

      val r1 = (0 to (N-2*L)).reverse.find{d =>isPal(L,L+d)}.get

      //println(s"$L: $r0 - $r1")
      //println(hashForward.take(11).mkString(" - "))
      //println(hashBackward.take(11).mkString(" - "))
      val ans = if(r0>=r1){
        //println(isPal(L+r0,L))
        s.substring(0,L+r0)+s.substring(N-L)
      }else{
        //println(isPal(L,L+r1))
        s.substring(0,L)+s.substring(N-(L+r1))
      }
      out.println(ans)

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


Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s at time 0.The elevator takes exactly 1 second to move down exactly 1 floor and negligible time to pick up passengers. Genos is given a list detailing when and on which floor passengers arrive. Please determine how long in seconds it will take Genos to bring all passengers to floor 0.

The first line of input contains two integers n and s (1 ≤ n ≤ 100, 1 ≤ s ≤ 1000) — the number of passengers and the number of the top floor respectively. The next n lines each contain two space-separated integers fi and ti (1 ≤ fi ≤ s, 1 ≤ ti ≤ 1000) — the floor and the time of arrival in seconds for the passenger number i.

Print a single integer — the minimum amount of time in seconds needed to bring all the passengers to floor 0.

NoteIn the first sample, it takes at least 11 seconds to bring all passengers to floor 0. Here is how this could be done:1. Move to floor 5: takes 2 seconds.2. Pick up passenger 3.3. Move to floor 3: takes 2 seconds.4. Wait for passenger 2 to arrive: takes 4 seconds.5. Pick up passenger 2.6. Go to floor 2: takes 1 second.7. Pick up passenger 1.8. Go to floor 0: takes 2 seconds.This gives a total of 2 + 2 + 4 + 1 + 2 = 11 seconds.

import scala.io.StdIn

/**
  * Created by hsleep on 2016. 1. 8..
  */
object ASolution extends App {
  val Array(numOfPassenger, numOfFloor) = StdIn.readLine().split(' ').map(_.toInt)
  val waitForPassenger = (0 until numOfPassenger).map { _ => StdIn.readLine().split(' ').map(_.toInt).sum }.max

  val output = math.max(numOfFloor, waitForPassenger)
  println(output)
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, s) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).foldLeft(s) {
    case (acc, _) =>
      val Array(f, t) = in.next().split(' ').map(_.toInt)
      Math.max(acc, t + f)
  }
  println(res)
}

import java.util.Scanner

object CF1 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.nextInt()
    val f = new Array[Int](n)
    val t = new Array[Int](n)
    var i = 0;
    while (i < n) {
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
      i += 1;
    }
    var maxF = f(0)
    var maxT = t(0)
    var max = t(0) - (s - f(0))
    i = 1
    while (i < n) {
      val tmp = t(i) - (s - f(i))
      if (tmp > max) {
        maxF = f(i)
        maxT = t(i)
        max = tmp
      }
      i += 1
    }
    if (max >= 0) System.out.print(maxF + maxT) else System.out.print(s)
    System.out.flush();
  }
}

object A608 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, s) = readInts(2)
    val in = Array.fill(n)(readInts(2)).map(arr => (arr(0), arr(1))).sorted.reverse
    var t = 0
    var curr = s
    for(i <- 0 until n) {
      if(in(i)._1 < curr) {
        t += (curr - in(i)._1)
        curr = in(i)._1
      }
      if(in(i)._2 > t) {
        t = in(i)._2
      }
    }
    t += curr
    println(t)
  }

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

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

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

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

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

}

import java.util.Scanner
import scala.math.max

object Main {
  def main(args: Array[String]) {
    val scanner = new Scanner(System.in)
    def next = scanner.next.toInt
    def nextPairs(n: Int) = 0.until(n).map(_ => (next, next)) // floor, time

    val n = next

    println(measureTrip(n, next, nextPairs(n)))
  }

  def measureTrip(peopleCount: Int, topFloor: Int, people: IndexedSeq[(Int, Int)]) = {
    val maxDelay = people.foldLeft(0)( (a: Int, p: (Int, Int)) => max(a, max(0, p._1 - (topFloor - p._2))) )
    topFloor + maxDelay
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.nextInt()

    var f = new Array[Int](n)
    var t = new Array[Int](n)
    for(i <- 0 until n){
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
    }

    //
    var tul = new Array[(Int, Int)](n + 1)
    tul(n) = (0, 0)

    for(i <- 0 until n)
      tul(i) = (f(i), t(i))

    tul = tul.sorted.reverse
    tul(n) = (10000, 100000)

    var ans = -1
    var man = 0
    for(i <- (0 to s).reverse){
      ans += 1
      if(man < n)
        if(tul(man)._1 == i){
          while(tul(man)._1 == i){
            ans = Math.max(ans, tul(man)._2)
            man += 1
          }
        }
    }

    println(ans)
  }
}

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

object A_336 {

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

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

    //---------------------------- parameters reading --------------------------
    val line1 = readLine
    val n = line1.int
    val s = line1.int

    var max = s

    for (i <- 0 until n) {
      val line = readLine
      val sum = line.int + line.int
      if (max < sum) {
        max = sum
      }
    }
    //---------------------------- parameters reading end ----------------------

    println(max)

  }

  def readLine() = new Line
  class Line {
    val tok = new StringTokenizer(br.readLine(), " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
  }

  var debugV = false
  var is = System.in
  val br = setupInputOutput();
  def db(x: => String) = if (debugV) println(x) // nullary function
  def setupInputOutput(): BufferedReader = {
    val devEnv = this.getClass.getCanonicalName.contains(".")
    if (!devEnv) {
      is = System.in
      debugV = false
    }
    val bis = new BufferedInputStream(is);
    new BufferedReader(new InputStreamReader(bis));
  }

}

//============================================================================================
object Test {

val sa1 = """

"""

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, s) = in.next().split(' ').map(_.toInt)
  val res = (1 to n).foldLeft(0) {
    case (acc, _) =>
      val Array(f, t) = in.next().split(' ').map(_.toInt)
      Math.max(acc, t + f)
  }
  println(res)
}

import java.util.Scanner

object CF1 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.nextInt()
    val f = new Array[Int](n)
    val t = new Array[Int](n)
    var i = 0;
    while (i < n) {
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
      i += 1;
    }
    var maxF = f(0)
    var maxT = t(0)
    var max = t(0) - (s - f(0));
    i = 1;
    while (i < n) {
      val tmp = t(i) - (s - f(i))
      if (tmp > max) {
        maxF = f(i);
        maxT = t(i);
        max = tmp;
      }
      i += 1;
    }
    System.out.print(maxF + maxT);
    System.out.flush();
  }
}

import java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val s = sc.nextInt()

    var f = new Array[Int](n)
    var t = new Array[Int](n)
    for(i <- 0 until n){
      f(i) = sc.nextInt()
      t(i) = sc.nextInt()
    }

    //
    var tul = new Array[(Int, Int)](n)
    for(i <- 0 until n)
      tul(i) = (f(i), t(i))

    tul = tul.sorted.reverse

    var ans = -1
    var man = 0
    for(i <- (0 to s).reverse){
      ans += 1
      if(man < n)
        if(tul(man)._1 == i){
          ans = Math.max(ans, tul(man)._2)
          man += 1
        }
    }

    println(ans)
  }
}