You are given two integers $$$x$$$ and $$$y$$$. You can perform two types of operations:   Pay $$$a$$$ dollars and increase or decrease any of these integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are four possible outcomes after this operation:   $$$x = 0$$$, $$$y = 6$$$;  $$$x = 0$$$, $$$y = 8$$$;  $$$x = -1$$$, $$$y = 7$$$;  $$$x = 1$$$, $$$y = 7$$$.   Pay $$$b$$$ dollars and increase or decrease both integers by $$$1$$$. For example, if $$$x = 0$$$ and $$$y = 7$$$ there are two possible outcomes after this operation:   $$$x = -1$$$, $$$y = 6$$$;  $$$x = 1$$$, $$$y = 8$$$.  Your goal is to make both given integers equal zero simultaneously, i.e. $$$x = y = 0$$$. There are no other requirements. In particular, it is possible to move from $$$x=1$$$, $$$y=0$$$ to $$$x=y=0$$$.Calculate the minimum amount of dollars you have to spend on it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. The first line of each test case contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^9$$$). The second line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^9$$$).

For each test case print one integer — the minimum amount of dollars you have to spend.

NoteIn the first test case you can perform the following sequence of operations: first, second, first. This way you spend $$$391 + 555 + 391 = 1337$$$ dollars.In the second test case both integers are equal to zero initially, so you dont' have to spend money.

import scala.io.StdIn.readLine

object A {
  def solution(x: Int, y: Int, a: Long, b: Long): Long =
    if (y < x)
      solution(y, x, a, b)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

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

  for (_ <- 1 to nextInt) {
    val x, y, a, b = nextLong
    val res1 = a * Math.abs(x - y) + b * Math.min(x, y)
    val res2 = a * (x + y)

    out.println(res1 min res2)
  }

  out.flush()

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

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ans = 1L * a * math.abs(x - y) + math.min(2L * a, 1L * b) * math.min(x, y)

    println(ans)
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toLong)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val ans = a * math.abs(x - y) + math.min(a + a, b) * math.min(x, y)

    println(ans)
  }
}

import scala.io.StdIn.readLine
import math._

object A {
  def solution(x: Int, y: Int, a: Int, b: Int): Int =
    if (abs(y) < abs(x))
      solution(y, x, a, b)
    else if (x < 0 && y < 0)
      solution(-x, -y, a, b)
    else if (x < 0 && y > 0)
      a * (y - x)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

import scala.io.StdIn.readLine
import math._

object A {
  def solution(x: Int, y: Int, a: Int, b: Int): Int =
    if (abs(y) < abs(x))
      solution(y, x, a, b)
    else if (x < 0 && y < 0)
      solution(-y, -x, a, b)
    else if (x < 0 && y > 0)
      a * (y - x)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

import scala.io.StdIn.readLine

object A {
  def solution(x: Int, y: Int, a: Int, b: Int): Int =
    if (y < x)
      solution(y, x, a, b)
    else
      if (a * 2 < b)
        a * (x + y)
      else
        a * (y - x) + b * x

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val Seq(x, y) = readLine.split(" ").toSeq.map(_.toInt)
      val Seq(a, b) = readLine.split(" ").toSeq.map(_.toInt)
      println(solution(x, y, a, b))
    }
  }
}

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

  for (_ <- 1 to nextInt) {
    val x, y, a, b = nextLong
    val res = a * Math.abs(x - y) + b * Math.min(x, y)

    out.println(res)
  }

  out.flush()

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

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toLong)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val ans = a * math.abs(x - y) + math.min(a, b) * math.min(x, y)

    println(ans)
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val Array(a, b) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ans = 1L * a * math.abs(x - y) + math.min(2L * a * x, 1L * b * x)

    println(ans)
  }
}


You have a string $$$s$$$ — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:  'W' — move one cell up;  'S' — move one cell down;  'A' — move one cell left;  'D' — move one cell right. Let $$$Grid(s)$$$ be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands $$$s$$$. For example, if $$$s = \text{DSAWWAW}$$$ then $$$Grid(s)$$$ is the $$$4 \times 3$$$ grid:  you can place the robot in the cell $$$(3, 2)$$$;  the robot performs the command 'D' and moves to $$$(3, 3)$$$;  the robot performs the command 'S' and moves to $$$(4, 3)$$$;  the robot performs the command 'A' and moves to $$$(4, 2)$$$;  the robot performs the command 'W' and moves to $$$(3, 2)$$$;  the robot performs the command 'W' and moves to $$$(2, 2)$$$;  the robot performs the command 'A' and moves to $$$(2, 1)$$$;  the robot performs the command 'W' and moves to $$$(1, 1)$$$.   You have $$$4$$$ extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence $$$s$$$ to minimize the area of $$$Grid(s)$$$.What is the minimum area of $$$Grid(s)$$$ you can achieve?

The first line contains one integer $$$T$$$ ($$$1 \le T \le 1000$$$) — the number of queries. Next $$$T$$$ lines contain queries: one per line. This line contains single string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$, $$$s_i \in \{\text{W}, \text{A}, \text{S}, \text{D}\}$$$) — the sequence of commands. It's guaranteed that the total length of $$$s$$$ over all queries doesn't exceed $$$2 \cdot 10^5$$$.

Print $$$T$$$ integers: one per query. For each query print the minimum area of $$$Grid(s)$$$ you can achieve.

NoteIn the first query you have to get string $$$\text{DSAWW}\underline{D}\text{AW}$$$.In second and third queries you can not decrease the area of $$$Grid(s)$$$.

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[Int]]): 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[Int] = {
    val cum = Array.ofDim[Int](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 = {
    REP(ni()) { _ =>
      val S = ns()
      val X, Y = Array.ofDim[Int](S.length)
      REP(S.length) { i =>
        S(i) match {
          case 'A' => X(i) -= 1
          case 'D' => X(i) += 1
          case 'S' => Y(i) -= 1
          case 'W' => Y(i) += 1
        }
      }

      val cumX = cumSum(X)
      val cumY = cumSum(Y)

      debug(cumX)
      debug(cumY)

      val x = cumX.max - cumX.min + 1
      val y = cumY.max - cumY.min + 1

      debug(s"x:$x y:$y")

      var ans = 1e18.toLong
      val minT = new SegmentTree(cumX.length, 0)(min)
      val maxT = new SegmentTree(cumX.length, 0)(max)
      def traverse(A: Array[Int], z: Long, isMinus: Boolean) = {
        REP(A.length) { i =>
          minT.update(i, A(i))
          maxT.update(i, A(i))
          var ms = minT.query(0, A.length)
          var mx = maxT.query(0, A.length)
          if (isMinus) ms = min(ms, A(i) - 1)
          if (!isMinus) mx = max(mx, A(i) + 1)
          val xx = (mx - ms + 1).toLong
          ans = min(ans, xx * z)
        }
      }

      def setXTree(d: Int): Unit = {
        REP(cumX.length) { i =>
          minT.update(i, cumX(i) + d)
          maxT.update(i, cumX(i) + d)
        }
      }
      setXTree(-1)
      traverse(cumX, y, isMinus = true)

      setXTree(1)
      traverse(cumX, y, isMinus = false)

      def setYTree(d: Int): Unit = {
        REP(cumY.length) { i =>
          minT.update(i, cumY(i) + d)
          maxT.update(i, cumY(i) + d)
        }
      }
      setYTree(-1)
      traverse(cumY, x, isMinus = true)

      setYTree(1)
      traverse(cumY, x, isMinus = false)

      out.println(ans)
    }
  }

  class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      assert(i < n)
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }
}

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[Int]]): 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[Int] = {
    val cum = Array.ofDim[Int](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 = {
    REP(ni()) { _ =>
      val S = ns()
      val X, Y = Array.ofDim[Int](S.length)
      REP(S.length) { i =>
        S(i) match {
          case 'A' => X(i) -= 1
          case 'D' => X(i) += 1
          case 'S' => Y(i) -= 1
          case 'W' => Y(i) += 1
        }
      }

      val cumX = cumSum(X)
      val cumY = cumSum(Y)

      debug(cumX)
      debug(cumY)

      val x = cumX.max - cumX.min + 1
      val y = cumY.max - cumY.min + 1

      debug(s"x:$x y:$y")

      var ans = 1e18.toLong
      val minT = new SegmentTree(cumX.length, 0)(min)
      val maxT = new SegmentTree(cumX.length, 0)(max)
      def traverse(A: Array[Int], isMinus: Boolean) = {
        REP(A.length) { i =>
          minT.update(i, A(i))
          maxT.update(i, A(i))
          var ms = minT.query(0, A.length)
          var mx = maxT.query(0, A.length)
          if (isMinus) ms = min(ms, A(i) - 1)
          if (!isMinus) mx = max(mx, A(i) + 1)
          val xx = (mx - ms + 1).toLong
          debug(s"xx:$xx y:$y")
          ans = min(ans, xx * y)
        }
      }

      def setXTree(d: Int): Unit = {
        REP(cumX.length) { i =>
          minT.update(i, cumX(i) + d)
          maxT.update(i, cumX(i) + d)
        }
      }
      setXTree(-1)
      traverse(cumX, isMinus = true)

      setXTree(1)
      traverse(cumX, isMinus = false)

      def setYTree(d: Int): Unit = {
        REP(cumY.length) { i =>
          minT.update(i, cumY(i) + d)
          maxT.update(i, cumY(i) + d)
        }
      }
      setYTree(-1)
      traverse(cumY, isMinus = true)

      setYTree(1)
      traverse(cumY, isMinus = false)

      out.println(ans)
    }
  }

  class SegmentTree(n: Int, zero: Int)(f: (Int, Int) => Int) {
    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val dat: Array[Int] = if (zero != 0){
      Array.fill(2 * N)(zero)
    } else {
      Array.ofDim(2 * N)
    }

    def update(i: Int, a: Int): Unit = {
      assert(i < n)
      var ix = i + N
      dat(ix) = a
      while(ix > 1) {
        dat(ix >> 1) = f(dat(ix), dat(ix ^ 1))
        ix >>= 1
      }
    }

    /**
      * [a, b)
      */
    def query(a: Int, b: Int): Int = {
      assert(a < n && b <= n)

      var res: Int = zero
      var left = a + N
      var right = b - 1 + N

      while(left <= right) {
        if ((left & 1) == 1) res = f(res, dat(left))
        if ((right & 1) == 0) res = f(res, dat(right))
        left = (left + 1) >> 1 // 右の子供なら右の親に移動
        right = (right - 1) >> 1 // 左の子供なら左の親に移動
      }

      res
    }
  }
}


Jafar has n cans of cola. Each can is described by two integers: remaining volume of cola ai and can's capacity bi (ai  ≤  bi).Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!

The first line of the input contains one integer n (2 ≤ n ≤ 100 000) — number of cola cans. The second line contains n space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — volume of remaining cola in cans. The third line contains n space-separated integers that b1, b2, ..., bn (ai ≤ bi ≤ 109) — capacities of the cans.

Print "YES" (without quotes) if it is possible to pour all remaining cola in 2 cans. Otherwise print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteIn the first sample, there are already 2 cans, so the answer is "YES".

import scala.io.StdIn._

object ProblemA extends App {
  val n = readInt()
  val A: Seq[Int] = readLine().split(' ').map(_ toInt)
  val B: Seq[Int] = readLine().split(' ').map(_ toInt)
  var maxbs = Seq(-1, -1)
  for (b <- B) {
    maxbs = Seq(maxbs(0).max(b), maxbs(1)).sorted
  }
  println(if (maxbs.sum >= A.map(BigInt(_)).sum) "YES" else "NO")
}

object A extends App {
  val n = scala.io.StdIn.readLine().toLong
  val A = scala.io.StdIn.readLine().split(" ").foldLeft(0L)(_ + _.toLong)
  val b = scala.io.StdIn.readLine().split(" ").map(_.toLong).sortWith(_ > _)

  if (b(0) + b(1) >= A) println("YES")
  else println("NO")
}

import scala.io.StdIn._

object ProblemA extends App {
  val n = readInt()
  val A: Seq[Int] = readLine().split(' ').map(_ toInt)
  val B: Seq[Int] = readLine().split(' ').map(_ toInt)
  var maxbs = Seq(-1, -1)
  for (b <- B) {
    maxbs = Seq(maxbs(0), maxbs(1).max(b)).sorted(Ordering[Int].reverse)
  }
  println(if (maxbs.sum >= A.sum) "YES" else "NO")
}

import scala.io.StdIn._

object ProblemA extends App {
  val n = readInt()
  val A: Seq[Int] = readLine().split(' ').map(_ toInt)
  val B: Seq[Int] = readLine().split(' ').map(_ toInt)
  var maxbs = Seq(-1, -1)
  for (b <- B) {
    maxbs = Seq(maxbs(0).max(b), maxbs(1)).sorted
  }
  println(if (maxbs.map(BigInt(_)).sum >= A.sum) "YES" else "NO")
}

object A extends App {
  val n = scala.io.StdIn.readLine().toInt
  val A = scala.io.StdIn.readLine().split(" ").foldLeft(0)(_ + _.toInt)
  val b = scala.io.StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _)

  if (b(0) + b(1) >= A && b(0) < A) println("YES")
  else println("NO")
}

object A extends App {
  val n = scala.io.StdIn.readLine().toInt
  val A = scala.io.StdIn.readLine().split(" ").foldLeft(0)(_ + _.toInt)
  val b = scala.io.StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _)

  if (b(0) + b(1) >= A) println("YES")
  else println("NO")
}


In the Catowice city next weekend the cat contest will be held. However, the jury members and the contestants haven't been selected yet. There are $$$n$$$ residents and $$$n$$$ cats in the Catowice, and each resident has exactly one cat living in his house. The residents and cats are numbered with integers from $$$1$$$ to $$$n$$$, where the $$$i$$$-th cat is living in the house of $$$i$$$-th resident.Each Catowice resident is in friendship with several cats, including the one living in his house. In order to conduct a contest, at least one jury member is needed and at least one cat contestant is needed. Of course, every jury member should know none of the contestants. For the contest to be successful, it's also needed that the number of jury members plus the number of contestants is equal to $$$n$$$.Please help Catowice residents to select the jury and the contestants for the upcoming competition, or determine that it's impossible to do.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100\,000$$$), the number of test cases. Then description of $$$t$$$ test cases follow, where each description is as follows: The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le m \le 10^6$$$), the number of Catowice residents and the number of friendship pairs between residents and cats. Each of the next $$$m$$$ lines contains integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that $$$a_i$$$-th resident is acquaintances with $$$b_i$$$-th cat. It's guaranteed that each pair of some resident and some cat is listed at most once. It's guaranteed, that for every $$$i$$$ there exists a pair between $$$i$$$-th resident and $$$i$$$-th cat. Different test cases are separated with an empty line. It's guaranteed, that the sum of $$$n$$$ over all test cases is at most $$$10^6$$$ and that the sum of $$$m$$$ over all test cases is at most $$$10^6$$$.

For every test case print:   "No", if it's impossible to select the jury and contestants.  Otherwise print "Yes".In the second line print two integers $$$j$$$ and $$$p$$$ ($$$1 \le j$$$, $$$1 \le p$$$, $$$j + p = n$$$) — the number of jury members and the number of contest participants.In the third line print $$$j$$$ distinct integers from $$$1$$$ to $$$n$$$, the indices of the residents forming a jury.In the fourth line print $$$p$$$ distinct integers from $$$1$$$ to $$$n$$$, the indices of the cats, which will participate in the contest.In case there are several correct answers, print any of them.

NoteIn the first test case, we can select the first and the third resident as a jury. Both of them are not acquaintances with a second cat, so we can select it as a contestant.In the second test case, we can select the second resident as a jury. He is not an acquaintances with a first and a third cat, so they can be selected as contestants.In the third test case, the only resident is acquaintances with the only cat, so they can't be in the contest together. So it's not possible to make a contest with at least one jury and at least one cat.In the fourth test case, each resident is acquaintances with every cat, so it's again not possible to make a contest with at least one jury and at least one cat.

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[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

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

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

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

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

object Workspace {
  import Main._

  class GraphDfs(g: Array[Array[Int]]) {
    private[this] val n = g.length
    private[this] val stack = Array.ofDim[Int](n)
    private[this] var s = 0
    private[this] val ix = Array.ofDim[Int](n)
    private[this] val used = Array.ofDim[Boolean](n)

    def apply(rt: Int = 0, enter: Int => Unit, exit: Int => Unit): Unit = {
      stack(s) = rt
      used(rt) = true
      s += 1

      while(s > 0) {
        val v = stack(s-1)
        val es = g(v)

        if (ix(v) == 0) {
          // dfsの開始部分
          enter(v)
        }

        if (ix(v) == es.length) {
          // dfsの終了部分
          exit(v)
          s -= 1
        }
        else {
          val u = es(ix(v))
          if (!used(u) && (s == 1 || u != stack(s-2))) {
            stack(s) = u
            used(u) = true
            s += 1
          }
          ix(v) += 1
        }
      }
    }

    def getUsed: Array[Boolean] = used
  }

  def stronglyConnectedComponents(g1: Array[Array[Int]], g2: Array[Array[Int]]): (Int, Array[Int]) = {
    val n = g1.length
    val vs = Array.ofDim[Int](n)
    var p = 0
    val dfs1 = new GraphDfs(g1)

    REP(n) { v =>
      if (!dfs1.getUsed(v)) {
        dfs1(v, _ => Unit, v => {
          vs(p) = v
          p += 1
        })
      }
    }
    val comp = Array.ofDim[Int](n)
    var k = 0
    val dfs2 = new GraphDfs(g2)
    REP_r(n) { i =>
      val v = vs(i)
      if (!dfs2.getUsed(v)) {
        dfs2(v, _ => Unit, v => {
          comp(v) = k
        })
        k += 1
      }
    }
    (k, comp)
  }

  def packDGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP_r(m) { i => // 順序維持する
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
    }
    t
  }
}

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n, m = ni()
      val A, B = Array.ofDim[Int](m - n)
      var p = 0
      REP(m) { _ =>
        val a, b = ni() - 1
        if (a != b) {
          A(p) = a
          B(p) = b
          p += 1
        }
      }
      val g = packDGraph(n, A, B)
      val g1 = packDGraph(n, B, A)
      val (k, comp) = stronglyConnectedComponents(g, g1)
      debug(comp)
      if (k == 1) out.println("No")
      else {
        val j = comp.count(_ == k - 1)
        out.println("Yes")
        out.println(s"$j ${n - j}")
        val juries, participants = ArrayBuffer[Int]()
        REP(n) { i =>
          if (comp(i) == k - 1) juries += i + 1
          else participants += i + 1
        }
        out.println(juries.mkString(" "))
        out.println(participants.mkString(" "))
      }
    }
  }
}


You are given an array $$$a_1, a_2, \dots , a_n$$$. Array is good if for each pair of indexes $$$i < j$$$ the condition $$$j - a_j \ne i - a_i$$$ holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if $$$a = [1, 1, 3, 5]$$$, then shuffled arrays $$$[1, 3, 5, 1]$$$, $$$[3, 5, 1, 1]$$$ and $$$[5, 3, 1, 1]$$$ are good, but shuffled arrays $$$[3, 1, 5, 1]$$$, $$$[1, 1, 3, 5]$$$ and $$$[1, 1, 5, 3]$$$ aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 100$$$).

For each test case print the shuffled version of the array $$$a$$$ which is good.

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

  override def solve(io: IO) = io.repeat {

    def isOkay(arr: Seq[Int]) = arr.zipWithIndex.map{case (i, a) => i - a }.distinct.length == arr.length

    val array = io.read[Seq[Int]]
    val ans = if (isOkay(array)) array else {
      val sorted = array.sorted
      if (isOkay(sorted)) sorted else sorted.reverse.ensuring(isOkay _)
    }
    io.writeAll(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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


After learning a lot about space exploration, a little girl named Ana wants to change the subject.Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so she came up with a more interesting one and she needs your help to solve it:You are given an array of strings which consist of only small letters of the alphabet. Your task is to find how many palindrome pairs are there in the array. A palindrome pair is a pair of strings such that the following condition holds: at least one permutation of the concatenation of the two strings is a palindrome. In other words, if you have two strings, let's say "aab" and "abcac", and you concatenate them into "aababcac", we have to check if there exists a permutation of this new string such that it is a palindrome (in this case there exists the permutation "aabccbaa"). Two pairs are considered different if the strings are located on different indices. The pair of strings with indices $$$(i,j)$$$ is considered the same as the pair $$$(j,i)$$$.

The first line contains a positive integer $$$N$$$ ($$$1 \le N \le 100\,000$$$), representing the length of the input array. Eacg of the next $$$N$$$ lines contains a string (consisting of lowercase English letters from 'a' to 'z') — an element of the input array.  The total number of characters in the input array will be less than $$$1\,000\,000$$$.

Output one number, representing how many palindrome pairs there are in the array.

NoteThe first example:  aa $$$+$$$ bb $$$\to$$$ abba. The second example:  aab $$$+$$$ abcac $$$=$$$ aababcac $$$\to$$$ aabccbaa aab $$$+$$$ aa $$$=$$$ aabaa abcac $$$+$$$ aa $$$=$$$ abcacaa $$$\to$$$ aacbcaa dffe $$$+$$$ ed $$$=$$$ dffeed $$$\to$$$ fdeedf dffe $$$+$$$ aade $$$=$$$ dffeaade $$$\to$$$ adfaafde ed $$$+$$$ aade $$$=$$$ edaade $$$\to$$$ aeddea

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    var ans = 0L
    val set = mutable.Map[Int, Int]() withDefaultValue 0
    rep(N) { _ =>
      var bit = 0
      val s = ns()
      rep(s.length) { i =>
        val j = s(i) - 'a'
        val k = 1 << j
        bit ^= k
      }

      ans += set(bit) // 全部偶数

      // １つだけ奇数
      rep(26) { i =>
        ans += set(bit ^ 1 << i)
      }

      set(bit) = set(bit) + 1
    }

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


Alice and Bob are playing yet another card game. This time the rules are the following. There are $$$n$$$ cards lying in a row in front of them. The $$$i$$$-th card has value $$$a_i$$$. First, Alice chooses a non-empty consecutive segment of cards $$$[l; r]$$$ ($$$l \le r$$$). After that Bob removes a single card $$$j$$$ from that segment $$$(l \le j \le r)$$$. The score of the game is the total value of the remaining cards on the segment $$$(a_l + a_{l + 1} + \dots + a_{j - 1} + a_{j + 1} + \dots + a_{r - 1} + a_r)$$$. In particular, if Alice chooses a segment with just one element, then the score after Bob removes the only card is $$$0$$$.Alice wants to make the score as big as possible. Bob takes such a card that the score is as small as possible.What segment should Alice choose so that the score is maximum possible? Output the maximum score.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of cards. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-30 \le a_i \le 30$$$) — the values on the cards.

Print a single integer — the final score of the game.

NoteIn the first example Alice chooses a segment $$$[1;5]$$$ — the entire row of cards. Bob removes card $$$3$$$ with the value $$$10$$$ from the segment. Thus, the final score is $$$5 + (-2) + (-1) + 4 = 6$$$.In the second example Alice chooses a segment $$$[1;4]$$$, so that Bob removes either card $$$1$$$ or $$$3$$$ with the value $$$5$$$, making the answer $$$5 + 2 + 3 = 10$$$.In the third example Alice can choose any of the segments of length $$$1$$$: $$$[1;1]$$$, $$$[2;2]$$$ or $$$[3;3]$$$. Bob removes the only card, so the score is $$$0$$$. If Alice chooses some other segment then the answer will be less than $$$0$$$.

//package codeforces.contests._1359

object _4 {

  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()

    val seq = 0 +: io.StdIn.readLine.split(" ").map(_.toInt) // 1 based
    val prefix = seq.scanLeft(0)(_ + _).tail

    @scala.annotation.tailrec
    def calculateLeftView(idx: Int = 1,
                          decreasingStack: List[(Int, Int)] = Nil, // stack for indices and there max sub array sum ending at them
                          resultList: List[Int] = Nil): List[Int] = {
      if (idx > n) resultList
      else {
        val (toConsider, rest) = decreasingStack.partition { case (i, _) => seq(i) <= seq(idx) }

        val resultSum = toConsider.foldLeft(seq(idx)) { case (acc, (i, maxSum)) =>
          val rangeSum = prefix(idx) - prefix(i) // without i
          acc max ((maxSum + rangeSum) max (seq(i) + rangeSum))
        }

        calculateLeftView(idx + 1, (idx, resultSum) :: rest, resultSum :: resultList)
      }
    }

    @scala.annotation.tailrec
    def calculateRightView(idx: Int = n,
                           decreasingStack: List[(Int, Int)] = Nil, // stack for indices and there max sub array sum ending at them
                           resultList: List[Int] = Nil): List[Int] = {
      if (idx == 0) resultList
      else {
        val (toConsider, rest) = decreasingStack.partition { case (i, _) => seq(i) <= seq(idx) }

        val resultSum = toConsider.foldLeft(seq(idx)) { case (acc, (i, maxSum)) =>
          val rangeSum = prefix(i - 1) - prefix(idx - 1)
          acc max ((maxSum + rangeSum) max (seq(i) + rangeSum))
        }

        calculateRightView(idx - 1, (idx, resultSum) :: rest, resultSum :: resultList)
      }
    }

    val leftView = calculateLeftView().reverse
    val rightView = calculateRightView()
    println {
      leftView.zip(rightView).zipWithIndex.foldLeft(0) { case (acc, ((lSum, rSum), i)) => acc max (lSum + rSum - 2 * seq(i + 1)) }
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val _ = StdIn.readLine().toInt
    val arr = StdIn.readLine.trim.split(" ").map(_.toInt)
    def maxSubArrayEx(nums: Array[Int], max: Int): Int = {
      var res: Long = 0
      var cur: Long = 0
      for (i <- nums.indices ) {
        if (nums(i) > max) cur = 0
        else {
          cur = math.max(cur + nums(i),0)
          res = math.max(res, cur-max)
        }
      }
      res.toInt
    }
    println((1 to 30).map(maxSubArrayEx(arr, _)).max)
  }
}

object D extends App {
  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans = (0 to 30).foldLeft(0) {
    case (ans, m) =>
      ans max (an
        .foldLeft((0, 0)) {
          case ((subSum, partSum), a) =>
            if (a > m) (subSum, 0)
            else (subSum max (partSum + a), 0 max (partSum + a))
        }
        ._1 - m)
  }

  println(ans)
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    val arr = StdIn.readLine.trim.split(" ").map(_.toInt)
    def maxSubArrayEx(nums: Array[Int]): Int = {
      var res: Long = 0
      var cur: Long = nums(0)
      var emax: Long = nums(0)
      for (i <- 1 until nums.length) {
        if (cur + nums(i) < nums(i)) {
          cur = nums(i)
          emax = nums(i)
        } else {
          cur = cur + nums(i)
          emax = emax max nums(i)
        }
        res = res max (cur - emax)
      }
      res.toInt
    }
    println(maxSubArrayEx(arr))
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine().toInt
    val arr = StdIn.readLine.trim.split(" ").map(_.toInt)
    def maxSubArrayEx(nums: Array[Int]): Int = {
      var res: Long = 0
      var cur: Long = nums(0)
      var emax: Long = nums(0)
      for (i <- 1 until nums.length) {
        if (cur + nums(i) < nums(i)) {
          cur = nums(i)
          emax = nums(i)
        } else {
          cur = cur + nums(i)
          emax = emax max nums(i)
        }
        res = res max (cur - emax)
      }
      res.toInt
    }
    maxSubArrayEx(arr)
  }
}

object D extends App {
  val n  = scala.io.StdIn.readInt()
  val an = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val ans = (0 to 30).map { m =>
    an.foldLeft((an.head, 0)) {
        case ((subSum, partSum), a) =>
          if (a > m) (subSum, 0)
          else (subSum max (partSum + a), 0 max (partSum + a))
      }
      ._1 - m
  }.max

  println(ans)

}


This is an interactive problem.Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet.Let's define $$$x$$$ as the distance to Mars. Unfortunately, Natasha does not know $$$x$$$. But it is known that $$$1 \le x \le m$$$, where Natasha knows the number $$$m$$$. Besides, $$$x$$$ and $$$m$$$ are positive integers.Natasha can ask the rocket questions. Every question is an integer $$$y$$$ ($$$1 \le y \le m$$$). The correct answer to the question is $$$-1$$$, if $$$x<y$$$, $$$0$$$, if $$$x=y$$$, and $$$1$$$, if $$$x>y$$$. But the rocket is broken — it does not always answer correctly. Precisely: let the correct answer to the current question be equal to $$$t$$$, then, if the rocket answers this question correctly, then it will answer $$$t$$$, otherwise it will answer $$$-t$$$.In addition, the rocket has a sequence $$$p$$$ of length $$$n$$$. Each element of the sequence is either $$$0$$$ or $$$1$$$. The rocket processes this sequence in the cyclic order, that is $$$1$$$-st element, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$\ldots$$$, $$$(n-1)$$$-th, $$$n$$$-th, $$$\ldots$$$. If the current element is $$$1$$$, the rocket answers correctly, if $$$0$$$ — lies. Natasha doesn't know the sequence $$$p$$$, but she knows its length — $$$n$$$.You can ask the rocket no more than $$$60$$$ questions.Help Natasha find the distance to Mars. Assume, that the distance to Mars does not change while Natasha is asking questions.Your solution will not be accepted, if it does not receive an answer $$$0$$$ from the rocket (even if the distance to Mars is uniquely determined by the already received rocket's answers).

The first line contains two integers $$$m$$$ and $$$n$$$ ($$$1 \le m \le 10^9$$$, $$$1 \le n \le 30$$$) — the maximum distance to Mars and the number of elements in the sequence $$$p$$$.

NoteIn the example, hacking would look like this:5 2 31 0This means that the current distance to Mars is equal to $$$3$$$, Natasha knows that it does not exceed $$$5$$$, and the rocket answers in order: correctly, incorrectly, correctly, incorrectly ...Really:on the first query ($$$1$$$) the correct answer is $$$1$$$, the rocket answered correctly: $$$1$$$;on the second query ($$$2$$$) the correct answer is $$$1$$$, the rocket answered incorrectly: $$$-1$$$;on the third query ($$$4$$$) the correct answer is $$$-1$$$, the rocket answered correctly: $$$-1$$$;on the fourth query ($$$5$$$) the correct answer is $$$-1$$$, the rocket answered incorrectly: $$$1$$$;on the fifth query ($$$3$$$) the correct and incorrect answer is $$$0$$$.

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

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

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

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

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

    case class Answer(x: Int)

    def query(y: Int): Either[Answer, Int] = {
//      debug(s"query $y")
      out.println(y)
      out.flush()
      val res = ni()
      if (res == 0) Left(Answer(y))
      else Right(res)
    }

    def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {
      if (i == N) Right(p)
      else {
        // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。
        // -1がくるかどうかでpを判定する
        query(i + 1).right flatMap { res =>
          p(i) = res
          makeP(i + 1, p)
        }
      }
    }

    def search(p: Array[Int]): Either[Answer, _] = {
      def step(i: Int, l: Int, r: Int): Either[Answer, _] = {
//        debug(s"step($i, $l, $r)")
        if (r - l == 1) {
//          debug(s"found $r")
          query(r)
        } else {
          val mid = (l + r) / 2 + 1
          query(mid).right flatMap { res =>
            if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y
            else step(i + 1, l, mid - 1) // -1 => x < y =>
          }
        }
      }

      step(0, N, M)
    }

    // 結果を出力しなくていい。0が帰った時点で終わり
    for {
      p <- makeP(0, Array.ofDim[Int](N)).right
      _ <- search(p).right
    } ()
  }

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

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

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

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

object CF499D extends App {

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

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

  val m = in.nextInt
  val n = in.nextInt

  var count = -1
  def ask(question: Int): Int = {
    count += 1
    out.println(question)
    out.flush

    val answer = in.nextInt
    if (answer == 0 || answer == -2) {
      out.close
      System.exit(0)
    }
    answer
  }

  // log(10^9)/log(2) = 29.9
  // so we can waste up to 30 questions to determine the lie sequence and still have 30 left to find the answer
  // Ask n times "1", all answers should be 1 (meaning distance > 1)
  val lieSequence = new Array[Int](n).map(_ => ask(1)).map(_ != 1)

  var min = 1
  var max = m

  while (true) {
    // Binary search
    val question = (min + max)/2
    val answer = (ask(question) == 1) ^ lieSequence(count%n) // real answer
    if (answer) {
      // more
      min = question + 1
    } else {
      // less
      max = question - 1
    }
  }
}

object CF499D extends App {

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

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

  val m = in.nextInt
  val n = in.nextInt

  var count = -1
  def ask(question: Int): Int = {
    count += 1
    out.println(question)
    out.flush

    val answer = in.nextInt
    if (answer == 0 || answer == -2) {
      out.close
      System.exit(0)
    }
    answer
  }

  // log(10^9)/log(2) = 29.9
  // so we can waste 30 questions to determine the lie sequence and still have 30 left to find the answer
  // All answers should be 1
  val lieSequence = new Array[Int](30).map(_ => ask(1)).map(_ != 1).take(n)

  var min = 1
  var max = m

  while (true) {
    // Binary search
    val question = (min + max)/2
    val answer = (ask(question) == 1) ^ lieSequence(count%n) // real answer
    if (answer) {
      // more
      min = question + 1
    } else {
      // less
      max = question - 1
    }
  }
}

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

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

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

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

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

    case class Answer(x: Int)

    def query(y: Int): Either[Answer, Int] = {
//      debug(s"query $y")
      out.println(y)
      out.flush()
      val res = ni()
      if (res == 0) Left(Answer(y))
      else Right(res)
    }

    def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {
      if (i == N) Right(p)
      else {
        // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。
        // -1がくるかどうかでpを判定する
        query(i + 1).right flatMap { res =>
          p(i) = res
          makeP(i + 1, p)
        }
      }
    }

    def search(p: Array[Int]): Either[Answer, _] = {
      def step(i: Int, l: Int, r: Int): Either[Answer, _] = {
//        debug(s"step($i, $l, $r)")
        if (r - l == 1) {
//          debug(s"found $r")
          query(r)
        } else {
          val mid = (l + r) / 2
          query(mid).right flatMap { res =>
            if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y
            else step(i + 1, l, mid) // -1 => x < y =>
          }
        }
      }

      step(0, N, M)
    }

    // 結果を出力しなくていい。0が帰った時点で終わり
    for {
      p <- makeP(0, Array.ofDim[Int](N)).right
      _ <- search(p).right
    } ()
  }

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

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

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

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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

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

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

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

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

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

    case class Answer(x: Int)

    def query(y: Int): Either[Answer, Int] = {
//      debug(s"query $y")
      out.println(y)
      out.flush()
      val res = ni()
      if (res == 0) Left(Answer(y))
      else Right(res)
    }

    def makeP(i: Int, p: Array[Int]): Either[Answer, Array[Int]] = {
      if (i == N) Right(p)
      else {
        // x >= i + 1 なので、0でなければ x > y => 1 が返るはず。
        // -1がくるかどうかでpを判定する
        query(i + 1).right flatMap { res =>
          p(i) = res
          makeP(i + 1, p)
        }
      }
    }

    def search(p: Array[Int]): Either[Answer, _] = {
      def step(i: Int, l: Int, r: Int): Either[Answer, _] = {
//        debug(s"step($i, $l, $r)")
        if (r - l == 1) {
//          debug(s"found $r")
          query(r)
        } else {
          val mid = (l + r) / 2
          query(mid).right flatMap { res =>
            if (res * p(i % N) == 1) step(i + 1, mid, r) // 1 => x > y
            else step(i + 1, l, mid - 1) // -1 => x < y =>
          }
        }
      }

      step(0, N, M)
    }

    // 結果を出力しなくていい。0が帰った時点で終わり
    for {
      p <- makeP(0, Array.ofDim[Int](N)).right
      _ <- search(p).right
    } ()
  }

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

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

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

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

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

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

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

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

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

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


You are given two integers $$$n$$$ and $$$k$$$.You should create an array of $$$n$$$ positive integers $$$a_1, a_2, \dots, a_n$$$ such that the sum $$$(a_1 + a_2 + \dots + a_n)$$$ is divisible by $$$k$$$ and maximum element in $$$a$$$ is minimum possible.What is the minimum possible maximum element in $$$a$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).

For each test case, print one integer — the minimum possible maximum element in array $$$a$$$ such that the sum $$$(a_1 + \dots + a_n)$$$ is divisible by $$$k$$$.

NoteIn the first test case $$$n = 1$$$, so the array consists of one element $$$a_1$$$ and if we make $$$a_1 = 5$$$ it will be divisible by $$$k = 5$$$ and the minimum possible.In the second test case, we can create array $$$a = [1, 2, 1, 2]$$$. The sum is divisible by $$$k = 3$$$ and the maximum is equal to $$$2$$$.In the third test case, we can create array $$$a = [1, 1, 1, 1, 1, 1, 1, 1]$$$. The sum is divisible by $$$k = 8$$$ and the maximum is equal to $$$1$$$.

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n){
        if(n % k == 0){
          println(1)
        } else {
          k *= n / k + 1
          println(k / n + 1)
        }
      } else {
        if(k % n == 0) println(k / n)
        else println(k / n + 1)
      }
      T -= 1
    }
  }
}

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

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      val x: Long = Math.max(n, k)
      var res: Long = Math.max(1, x / n)
      if (n * res % k > 0) res += 1

      out.println(res)
    }

    out.flush()
  }

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

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

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      val x = Math.max(n, k)
      var res = Math.max(1, x / n)
      if (n * res % k > 0) res += 1

      out.println(res)
    }

    out.flush()
  }

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

//package codeforces.CF1476

import scala.io.StdIn._

object SolutionA extends App {
  (1 to readInt()).foreach {
    _ =>
      val strings = readLine().split(" ")
      val n = strings.head.toLong
      val k = strings.last.toLong
      if (n <= k) {
        println(k / n + (k % n != 0).compare(false))
      } else {
        val realK = (n / k + (n % k != 0).compare(false)) * k
        println(realK / n + (realK % n != 0).compare(false))
      }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n){
        if(n % k == 0){
          println(1)
        } else {
          k *= n / k + 1
        }
      } else {
        if(k % n == 0) println(k / n)
        else println(k / n + 1)
      }
      if(k < n){
        val temp = n / k
        k *= temp + 1
      }

      T -= 1
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n){
        val temp = n / k
        k *= temp + 1
      }
      if(k % n == 0) println(k / n)
      else println(k / n + 1)
      T -= 1
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    var T = stdin.readInt()
    while(T > 0) {
      val str = stdin.readLine().split(" ")
      var n = str(0).toInt
      var k = str(1).toInt
      if(k < n) k *= 2
      if(k % n == 0) println(k / n)
      else println(k / n + 1)
      T -= 1
    }
  }
}

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

    for (_ <- 1 to nextInt) {
      val n, k = nextInt
      var res = Math.max(1, k / n)
      if (k % n > 0) res += 1

      out.println(res)
    }

    out.flush()
  }

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


This problem is actually a subproblem of problem G from the same contest.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$).You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad). It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.Your task is to find out the maximum possible size of the single gift you can prepare using the candies you have.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Each query is represented by two lines. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of candies. The second line of each query contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy in the box. It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.

For each query print one integer — the maximum possible size of the single gift you can compose using candies you got in this query with the restriction described in the problem statement.

NoteIn the first query, you can prepare a gift with two candies of type $$$8$$$ and one candy of type $$$5$$$, totalling to $$$3$$$ candies.Note that this is not the only possible solution — taking two candies of type $$$4$$$ and one candy of type $$$6$$$ is also valid.

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

  override def apply(io: IO): io.type = {
    val queries = io.read[Seq[Seq[Int]]]
    val ans = queries map {candies =>
      val sizes = candies
        .groupBy(identity)
        .values
        .map(_.size)
        .toList
        .sorted(desc[Int])
      sum(sizes, upper = Int.MaxValue, acc = 0)
    }

    io.writeLines(ans)
  }

  @tailrec
  def sum(as: List[Int], upper: Int, acc: Long): Long = {
    as match {
      case Nil => acc
      case a1 :: _ if a1 <= 0 => acc
      case a1 :: at if a1 >= upper => sum((upper - 1) :: at, upper, acc)
      case a1 :: at => sum(at, a1, acc + a1)
    }
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)
}
/****************************[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
      }
    }
  }
}


You are given a following process. There is a platform with $$$n$$$ columns. $$$1 \times 1$$$ squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column. When all of the $$$n$$$ columns have at least one square in them, the bottom row is being removed. You will receive $$$1$$$ point for this, and all the squares left will fall down one row. You task is to calculate the amount of points you will receive.

The first line of input contain 2 integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the length of the platform and the number of the squares. The next line contain $$$m$$$ integer numbers $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le n$$$) — column in which $$$i$$$-th square will appear.

Print one integer — the amount of points you will receive.

NoteIn the sample case the answer will be equal to $$$2$$$ because after the appearing of $$$6$$$-th square will be removed one row (counts of the squares on the platform will look like $$$[2~ 3~ 1]$$$, and after removing one row will be $$$[1~ 2~ 0]$$$).After the appearing of $$$9$$$-th square counts will be $$$[2~ 3~ 1]$$$, and after removing one row it will look like $$$[1~ 2~ 0]$$$.So the answer will be equal to $$$2$$$.

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, m = r.read[Int]
    import Utils._
    val xs = r.read[List[Int]](m).sorted.group(_ == _)

    if (xs.length < n) {
      println(0)
    } else {
      println(xs.map(_.length).min)
    }
  }
}

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).map(new StringTokenizer(_)).buffered
}

object Utils {
  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

object Solution {

    def main(args: Array[String]) {
        val inp = readLine.split(" ").map(_.toInt)
        val arr = Array.ofDim[Int](inp(0))
        readLine.split(" ").foreach(f => arr(f.toInt - 1) += 1)
        print(arr.min)
    }
}

object Tetrix extends App {
  val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
  val n = firstinput(0)
  val m = firstinput(1)
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList

  val emptyFreqMap = (1 to n).map( x => (x, 0)).toMap
  val distinctSquaresValues = emptyFreqMap.keys.size
  val freqMap = squares.groupBy( x => x).mapValues( _.length )
  val finalMap = emptyFreqMap ++ freqMap
  val minFq = finalMap.minBy( _._2 )._2

  val points =
    if(distinctSquaresValues < n) 0
    else minFq

  println(points)
}

object Tetrix extends App {
  val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
    // Seq(1, 1000)
    // Seq(3, 9)
    // Console.in.readLine().split(" ").map( _.toInt).toList
  val n = firstinput(0) // cantidad de valores distintos
  val m = firstinput(1)
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList
    // (1 to 1000).map(x => 1).toList
    // List(1, 1, 2, 2, 2, 3, 1, 2, 3)
    // Console.in.readLine().split(" ").map( _.toInt).toList

  val emptyFreqMap = (1 to n).map( x => (x, 0)).toMap
  val distinctSquaresValues = emptyFreqMap.keys.size
  val freqMap = squares.groupBy( x => x).mapValues( _.length )
  val finalMap = emptyFreqMap ++ freqMap
  val maxFq = finalMap.maxBy( _._2 )._2
  val minFq = finalMap.minBy( _._2 )._2

  val resutl =
    if(distinctSquaresValues < n) {
      0
    } else if (distinctSquaresValues == 1) {
      maxFq
    } else {
      minFq
    }

  println(resutl)
}

object A {
  def main(args: Array[String]) {
    val t = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    val n = t(0);
    val m = t(1);
    //println(n, m);
    val s = scala.io.StdIn.readLine();
    var cs = s.split(" ").map( _.toInt );
    //println(cs.size)
    var a = Array.ofDim[Int](n);
    //println(a.size)
    for(c <- cs){
        //println(c - 1)
        //println(cs(i) - 1)
        a(c - 1) += 1;
    }
    var ans = m + m;
    for(i <- 0 until n){
        ans = math.min(ans, a(i))
    }
    println(ans)
  }
}

object problemA {
    import java.io.{BufferedReader, FileInputStream, InputStreamReader}
    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable
    import scala.util.control.Breaks._

    val source = System.in
    //new FileInputStream("D://in.txt")
    implicit val reader = new BufferedReader(new InputStreamReader(source))

    def read()(implicit reader: BufferedReader): String = reader.readLine().split(" ")(0)
    def readArray()(implicit reader: BufferedReader): Array[String] = reader.readLine().split(" ")
    def readString()(implicit reader: BufferedReader): String = reader.readLine()

    def main(args: Array[String]): Unit = {
        val Array(n, m) = readArray.map(_.toInt)
        val f = new Array[Int](n)

        val k = readArray().map(_.toInt)

        for (i <- k) {
            f(i - 1) += 1
        }

        println(f.min)

    }
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, m = r.read[Int]
    val xs = r.read[List[Int]](m)

    import Utils._
    println(xs.sorted.group(_ == _).map(_.length).min)
  }
}

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).map(new StringTokenizer(_)).buffered
}

object Utils {
  import scala.math._

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

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

    if (xs.length < n) {
      println(0)
    } else {
      import Utils._

      println(xs.sorted.group(_ == _).map(_.length).min)
    }
  }
}

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).map(new StringTokenizer(_)).buffered
}

object Utils {
  import scala.math._

  implicit def listToExtendedList[A](xs: List[A]): ExtendedList[A] = new ExtendedList(xs)

  class ExtendedList[A](xs: List[A]) {
    def group(g: (A, A) => Boolean) =
      xs.foldRight(List[List[A]]()) {
        case (x, ys :: zs) => if (g(x, ys.head)) (x :: ys) :: zs else List(x) :: ys :: zs
        case (x, _) => List(List(x))
      }
  }
}

import scala.annotation.tailrec

object Tetrix extends App {
  val _: String = Console.in.readLine()
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList
  @tailrec
  def minFreq(a: List[Int], min: Int, max: Int, freq: Map[Int, Int]): (Int, Int) = a match {
    case Nil => (min, max)
    case x :: xs =>
      val currValue : Int = freq.getOrElse(x, 0)
      val newValue = currValue + 1
      val newFreq: Map[Int, Int] = freq + (x -> newValue)
      if(max <= newValue) {
        minFreq(xs, max, newValue, newFreq)
      } else if(min >= newValue){
        minFreq(xs, newValue, max, newFreq)
      } else {
        minFreq(xs, min, max, newFreq)
      }
  }

  val (min, max) = minFreq(squares, 0, 0, Map.empty[Int, Int])
  println { min }
}

object Tetrix extends App {
  val _ = Console.in.readLine()

  val squares = Console.in.readLine().split(" ").map(_.toInt)
  val x = squares.groupBy(x => x).mapValues(_.length).values.min

  println { x }
}

object Tetrix extends App {
    val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
    val n = firstinput(0)
    val m = firstinput(1)
    val squares = Console.in.readLine().split(" ").map( _.toInt).toList

    def increaseFreq(e: Int, freqMap: Map[Int, Int]): Map[Int, Int] = {
        val currValue = freqMap.getOrElse(e, 0)
        freqMap + (e -> (currValue + 1))
    }

    def pointsOf(Fq: Int, minFq: Int , maxFq: Int): (Int, Int) = {
        if(Fq >= maxFq) (maxFq, Fq)
        else (Fq, maxFq)
    }

    def minFreq(a: List[Int], freqMap: Map[Int, Int], minFq: Int , maxFq: Int): (Int, Map[Int, Int]) = a match {
      case Nil => (minFq, freqMap)
      case x :: xs =>
        val newMap = increaseFreq(x, freqMap)
        val (points, newMax) = pointsOf(newMap(x), minFq, maxFq)
        minFreq(xs, newMap, points, newMax)
    }

    val tablero = Map.empty[Int, Int]
    val initialPoints = 0
    val (min, freq) = minFreq(squares, tablero, minFq = initialPoints, maxFq = 0)

    val result =
      if(1 < freq.keys.size && freq.keys.size < n) 0
      else if (1 == freq.keys.size) min + 1
      else min

    println(result)
}

object Tetrix extends App {
    val firstinput = Console.in.readLine().split(" ").map( _.toInt).toList
    val n = firstinput(0)
    val m = firstinput(1)
    val squares = Console.in.readLine().split(" ").map( _.toInt).toList

    def increaseFreq(e: Int, freqMap: Map[Int, Int]): Map[Int, Int] = {
        val currValue = freqMap.getOrElse(e, 0)
        freqMap + (e -> (currValue + 1))
    }

    def pointsOf(Fq: Int, minFq: Int , maxFq: Int): (Int, Int) = {
        if(Fq >= maxFq) (maxFq, Fq)
        else (Fq, maxFq)
    }

    def minFreq(a: List[Int], freqMap: Map[Int, Int], minFq: Int , maxFq: Int): (Int, Map[Int, Int]) = a match {
      case Nil => (minFq, freqMap)
      case x :: xs =>
        val newMap = increaseFreq(x, freqMap)
        val (points, newMax) = pointsOf(newMap(x), minFq, maxFq)
        minFreq(xs, newMap, points, newMax)
    }

    val tablero = Map.empty[Int, Int]
    val initialPoints = 0
    val (min, freq) = minFreq(squares, tablero, minFq = initialPoints, maxFq = 0)

    val result =
      if(freq.keys.size < n) 0
      else min

    println(result)
}

import scala.annotation.tailrec

object Tetrix extends App {
  val _: String = Console.in.readLine()
  val squares = Console.in.readLine().split(" ").map( _.toInt).toList
  @tailrec
  def minFreq(a: List[Int], min: Int, max: Int, freq: Map[Int, Int]): (Int, Int) = a match {
    case Nil => (min, max)
    case x :: xs =>
      val currValue : Int = freq.getOrElse(x, 0)
      val newValue = currValue + 1
      val newFreq: Map[Int, Int] = freq + (x -> newValue)
      if(max <= newValue) {
        minFreq(xs, max, newValue, newFreq)
      } else if(min <= newValue){
        minFreq(xs, min, max, newFreq)
      } else {
        minFreq(xs, newValue, max, newFreq)
      }
  }

  val (min, max) = minFreq(squares, 0, 0, Map.empty[Int, Int])
  println { min }
}