Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1, ..., ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1, ..., ak (1 ≤ ai ≤ p) — the marks that Vova got for the tests he has already written.

If Vova cannot achieve the desired result, print "-1". Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

NoteThe median of sequence a1, ..., an where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4 2", "2 4", "5 1", "1 5", "4 1", "1 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1".

object main{
  object Solver extends InputReader{
    def solve(){
      val n = getInt()
      val k = getInt()
      val p = getInt()
      val x = getInt()
      val y = getInt()

      val a = new Array[Int](n)
      for(i <- 0 to k - 1)
        a(i) = getInt()

      var s = a.sum
      for(i <- k to n - 1){
        val can = x - s
        val rest = n - 1 - i

        a(i) = Math.min(can - rest, y)
        s += a(i)
      }

      val b = a.sorted

      if(b(0) > 0 && b(n / 2) >= y){
        for(i <- k to n - 1)
          print(a(i) + " ")
        println()
      }else{
        println(-1)
      }
    }
  }

  // TEMPLATE ------------------------

  def main(args: Array[String]){
    Solver.solve()
  }

  trait InputReader{
    import java.io._
    import java.util._
    protected val stream = System.in
    private val reader = new BufferedReader(new InputStreamReader(stream))
    private var tokenizer = new StringTokenizer(reader.readLine())

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

    def getInt(): Int = getStr().toInt
    def getLong(): Long = getStr().toLong
    def getDouble(): Double = getStr().toDouble
  }
}

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

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

import Ordering.Implicits._

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

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

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

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

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

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val first = math.min(n - k, n / 2 - tested.count(_ < y))
    if (first < 0 || sumk + first + (n - k - first) * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until n - k - first) {
        printf("%d ", y)
      }
    }
  }

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

object B540 extends App {
  import java.util.Scanner
  def apply(problem: String): String = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /***************************************************************************/
  type Input = (Int, Int, Int, Int, Int, List[Int])

  type Output = Option[List[Int]]

  def solve(input: Input): Output = {
    val (n, k, p, x, y, s) = input
    val numOfYs = ((n+1)/2 - s.count(_ >= y)) max 0 min (n-k)
    val numOf1s = n - k - numOfYs
    val solution = List.fill(numOfYs)(y) ::: List.fill(numOf1s)(1)
    val result = s ::: solution
    if (result.sum <= x && result.count(_ >= y) >= (n+1)/2) Some(solution) else None
  }

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, k, p, x, y, List.fill(k)(nextInt))
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, k, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, k, p, x, y, scores) = problem

    def isMedianSatisfied(s: List[Int]) = (s ::: scores).count(_ >= y) >= (n + 1)/2

    @scala.annotation.tailrec
    def score(newScores: List[Int]): List[Int] = if (newScores.length == n - k) {
      newScores
    } else if (isMedianSatisfied(newScores)) {
      score(1 :: newScores)
    } else {
      score(y :: newScores)
    }

    val solution = score(Nil)
    if (isMedianSatisfied(solution) && (solution ::: scores).sum <= x) Some(solution) else None
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

import Array._

object main extends App with fastIO {

  var Array(n, k, p, x, y) = readLine split(" ") map(_.toInt)
  var a = Array.fill(k)(nextInt)

  var r = a.count(_ >= y)

  var b = Vector[Int]()
  for (i <- r until (n >> 1) + 1) b = b :+ y
  for (i <- a.length + b.length until n) b = b :+ 1

  if (b.length <= n - k && a.sum + b.sum <= x)
    println(b.mkString(" ")) else
    println(-1)

  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken
    in.sval
  }

  def nextInt: Int = {
    in.nextToken
    in.nval.toInt
  }

  def nextLong:Long ={
    in.nextToken
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken
    in.nval.toDouble
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush = out.flush
}

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

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

import Ordering.Implicits._

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

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

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

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

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

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val (first, second) = (n / 2 - tested.count(_ < y), (n + 1) / 2 - tested.count(_ >= y))
    if (first < 0 || second < 0 || sumk + first + second * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until second) {
        printf("%d ", y)
      }
    }
  }

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

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

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

import Ordering.Implicits._

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

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

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

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

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

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val first = math.min(n - k, n / 2 - tested.count(_ < y))
    println (first)
    if (first < 0 || sumk + first + (n - k - first) * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until n - k - first) {
        printf("%d ", y)
      }
    }
  }

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

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

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

import Ordering.Implicits._

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

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

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

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

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

  def solve(): Unit = {
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    val tested = (for (i <- Range(0, k)) yield nextInt).toArray
    val sumk = tested.sum
    val (first, second) = (n / 2 - tested.count(_ < y), (n + 1) / 2 - tested.count(_ >= y))
    if (sumk + first + second * y > x) {
      println(-1)
    } else {
      for (i <- 0 until first) {
        printf("%d ", 1)
      }
      for (i <- 0 until second) {
        printf("%d ", y)
      }
    }
  }

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

object B540 extends App {
  import java.util.Scanner
  def apply(problem: String): String = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /***************************************************************************/
  type Input = (Int, Int, Int, Int, Int, List[Int])

  type Output = Option[List[Int]]

  def solve(input: Input): Output = {
    val (n, k, p, x, y, s) = input
    val numOfYs = ((n+1)/2 - s.count(y <=)) max 0
    val numOf1s = n - k - numOfYs
    val best = List.fill(numOfYs)(y) ::: List.fill(numOf1s)(1)
    if ((s ::: best).sum <= x) Some(best) else None
  }

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, k, p, x, y, List.fill(k)(nextInt))
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < left || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets%2 == 0 || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < (x - total) || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 => when(1 <= target && target <= p)(List(target))
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _} filter {strategy => buckets < left || median(strategy ::: scores) >= y}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      solve(x - total, left)
    }
  }

  def median(l: List[Int]) = {
    require(l.length % 2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

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

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}

object B540 extends App {
  import java.util.Scanner

  type Input = (Int, Int, Int, Int, List[Int])
  type Output = Option[List[Int]]

  def read(scanner: Scanner): Input = {
    import scanner._
    val (n, k, p, x, y) = (nextInt, nextInt, nextInt, nextInt, nextInt)
    (n, p, x, y, List.fill(k)(nextInt))
  }

  def solve(problem: Input): Output = {
    val (n, p, x, y, scores) = problem
    val (k, total) = (scores.length, scores.sum)
    val left = n - k
    if (total + left > x) {
      None
    } else {
      def solve(target: Int, buckets: Int): Option[List[Int]] = buckets match {
        case _ if target < 1 => None
        case 1 if 1 <= target && target <= p => Some(List(target))
        case 1 => None
        case _ =>
          def score(s: Int) = solve(target - s, buckets - 1) map {s :: _}
          (p to 1 by -1) collectFirst Function.unlift(score)
      }
      val strategy = solve(x - total, left)
      strategy filter {s => median(s ::: scores) >= y}
    }
  }

  def median(l: List[Int]) = {
    require(l.length %2 == 1)
    l.sorted.apply(l.length/2 + 1)
  }

  def format(result: Output): String = result map {_ mkString " "} getOrElse "-1"

  def apply(input: String): String = apply(new Scanner(input))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
}


A robber has attempted to rob a bank but failed to complete his task. However, he had managed to open all the safes.Oleg the bank client loves money (who doesn't), and decides to take advantage of this failed robbery and steal some money from the safes. There are many safes arranged in a line, where the i-th safe from the left is called safe i. There are n banknotes left in all the safes in total. The i-th banknote is in safe xi. Oleg is now at safe a. There are two security guards, one of which guards the safe b such that b < a, i.e. the first guard is to the left of Oleg. The other guard guards the safe c so that c > a, i.e. he is to the right of Oleg.The two guards are very lazy, so they do not move. In every second, Oleg can either take all the banknotes from the current safe or move to any of the neighboring safes. However, he cannot visit any safe that is guarded by security guards at any time, becaues he might be charged for stealing. Determine the maximum amount of banknotes Oleg can gather.

The first line of input contains three space-separated integers, a, b and c (1 ≤ b < a < c ≤ 109), denoting the positions of Oleg, the first security guard and the second security guard, respectively. The next line of input contains a single integer n (1 ≤ n ≤ 105), denoting the number of banknotes. The next line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109), denoting that the i-th banknote is located in the xi-th safe. Note that xi are not guaranteed to be distinct.

Output a single integer: the maximum number of banknotes Oleg can take.

NoteIn the first example Oleg can take the banknotes in positions 4, 5, 6 (note that there are 2 banknotes at position 5). Oleg can't take the banknotes in safes 7 and 8 because he can't run into the second security guard. Similarly, Oleg cannot take the banknotes at positions 3 and 2 because he can't run into the first security guard. Thus, he can take a maximum of 4 banknotes.For the second sample, Oleg can't take any banknotes without bumping into any of the security guards.

import java.util.StringTokenizer

object B extends App {
  val INF = 1 << 30

  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong

  read()
  val a = int()
  val b = int()
  val c = int()

  def filter(x: Int) = (x > b) && (x < c)

  read()
  val n = int()

  read()
  val ans = (1 to n).map(_ => int()).count(filter)
  println(ans)

}


Welcome to Rockport City!It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet $$$a$$$ dollars and Ronnie has bet $$$b$$$ dollars. But the fans seem to be disappointed. The excitement of the fans is given by $$$gcd(a,b)$$$, where $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. To make the race more exciting, you can perform two types of operations:  Increase both $$$a$$$ and $$$b$$$ by $$$1$$$.  Decrease both $$$a$$$ and $$$b$$$ by $$$1$$$. This operation can only be performed if both $$$a$$$ and $$$b$$$ are greater than $$$0$$$. In one move, you can perform any one of these operations. You can perform arbitrary (possibly zero) number of moves. Determine the maximum excitement the fans can get and the minimum number of moves required to achieve it.Note that $$$gcd(x,0)=x$$$ for any $$$x \ge 0$$$.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^3$$$) — the number of test cases. The first and the only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$0\leq a, b\leq 10^{18}$$$).

For each test case, print a single line containing two integers.  If the fans can get infinite excitement, print 0 0. Otherwise, the first integer must be the maximum excitement the fans can get, and the second integer must be the minimum number of moves required to achieve that excitement.

NoteFor the first test case, you can apply the first operation $$$1$$$ time to get $$$a=9$$$ and $$$b=6$$$. It can be shown that $$$3$$$ is the maximum excitement possible.For the second test case, no matter how many operations you apply, the fans will always have an excitement equal to $$$1$$$. Since the initial excitement is also $$$1$$$, you don't need to apply any operation.For the third case, the fans can get infinite excitement by applying the first operation an infinite amount of times.For the fourth test case, you can apply the second operation $$$3$$$ times to get $$$a=0$$$ and $$$b=6$$$. Since, $$$gcd(0,6)=6$$$, the fans will get an excitement of $$$6$$$.

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toLong).sorted

    val e = b - a
    val m =
      if (e == 0) 0
      else if (a % e == b % e) (a % e) min (e - a % e)
      else a

    println(s"$e $m")
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toLong).sorted

    val e = b - a
    val m =
      if (e == 0) 0
      else if (a % e == b % e) (a % e) min (e - a % e) min a
      else a

    println(s"$e $m")
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toLong).sorted

    val e = b - a
    val m =
      if (e == 0) 0
      else if (a % e == b % e) {
        if (a % e == 0) 0 else (e - a % e) min a
      } else a

    println(s"$e $m")
  }
}


At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1], a[2], ..., a[n]. Then he should perform a sequence of m operations. An operation can be one of the following:  Print operation l, r. Picks should write down the value of .  Modulo operation l, r, x. Picks should perform assignment a[i] = a[i] mod x for each i (l ≤ i ≤ r).  Set operation k, x. Picks should set the value of a[k] to x (in other words perform an assignment a[k] = x). Can you help Picks to perform the whole sequence of operations?

The first line of input contains two integer: n, m (1 ≤ n, m ≤ 105). The second line contains n integers, separated by space: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109) — initial value of array elements. Each of the next m lines begins with a number type .    If type = 1, there will be two integers more in the line: l, r (1 ≤ l ≤ r ≤ n), which correspond the operation 1.  If type = 2, there will be three integers more in the line: l, r, x (1 ≤ l ≤ r ≤ n; 1 ≤ x ≤ 109), which correspond the operation 2.  If type = 3, there will be two integers more in the line: k, x (1 ≤ k ≤ n; 1 ≤ x ≤ 109), which correspond the operation 3.

For each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer.

NoteConsider the first testcase:  At first, a = {1, 2, 3, 4, 5}.  After operation 1, a = {1, 2, 3, 0, 1}.  After operation 2, a = {1, 2, 5, 0, 1}.  At operation 3, 2 + 5 + 0 + 1 = 8.  After operation 4, a = {1, 2, 2, 0, 1}.  At operation 5, 1 + 2 + 2 = 5.

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()

    val a = na(n)

    val t = new SegmentTree(n, a)
    t.build(1, 0, n-1)
    REP(m) { _ =>
      ni() match {
        case 1 =>
          out.println(t.get(1, 0, n-1, ni() - 1, ni() - 1))
        case 2 =>
          t.updateRange(1, 0, n-1, ni() - 1, ni() -1, ni())
//          t.print()
        case 3 =>
          t.updatePoint(1, 0, n-1, ni() - 1, ni())
//          t.print()
      }
    }
  }

  private class SegmentTree(n: Int, a: Array[Int])  {
    private val sum = Array.ofDim[Long](4 * n)
    private val max = Array.ofDim[Int](4 * n)

    def merge(v: Int): Unit = {
      sum(v) = sum(v << 1) + sum(v << 1 | 1)
      max(v) = Math.max(max(v << 1), max(v << 1 | 1))
    }

    def print(): Unit = {
      out.println(a.mkString(","))
    }

    def print_1(): Unit = {
      out.println(max.mkString(","))
    }

    def build(v: Int, tl: Int, tr: Int): Unit = {
      if(tl == tr) {
        sum(v) = a(tl)
        max(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        build(v << 1, tl, tm)
        build(v << 1 | 1, tm + 1, tr)
        merge(v)
      }
    }

    def updateRange(v: Int, tl: Int, tr: Int, l: Int, r: Int, x: Int): Unit = {
      if(l > r) {}
      else if(l == tl && r == tr && max(v) < x) {}
      else if(tl == tr) {
        a(tl) = a(tl) % x
        sum(v) = a(tl)
        max(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        updateRange(v << 1, tl, tm, l, Math.min(r, tm), x)
        updateRange(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r, x)
        merge(v)
      }
    }

    def updatePoint(v: Int, tl: Int, tr: Int, pos: Int, x: Int): Unit = {
      if(tl == tr) {
        a(tl) = x
        sum(v) = a(tl)
        max(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        if(pos <= tm) {
          updatePoint(v << 1, tl, tm, pos, x)
        } else {
          updatePoint(v << 1 | 1, tm + 1, tr, pos, x)
        }
        merge(v)
      }
    }

    def get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Long = {
      if(l > r) 0L
      else if(l == tl && r == tr) sum(v)
      else {
        val tm = tl + (tr - tl) / 2
        get(v << 1, tl, tm, l, Math.min(r, tm)) +
        get(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r)
      }
    }
  }
}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()
    val m = ni()

    val a = na(n)

    val t = new SegmentTree(n, a)
    t.build(1, 0, n-1)
    REP(m) { _ =>
      ni() match {
        case 1 =>
          out.println(t.get(1, 0, n-1, ni() - 1, ni() - 1))
        case 2 =>
          t.updateRange(1, 0, n-1, ni() - 1, ni() -1, ni())
//          t.print()
        case 3 =>
          t.updatePoint(1, 0, n-1, ni() - 1, ni())
//          t.print()
      }
    }
  }

  private class SegmentTree(n: Int, a: Array[Int])  {
    private val sum = Array.ofDim[Int](4 * n)
    private val max = Array.ofDim[Int](4 * n)

    def merge(v: Int): Unit = {
      sum(v) = sum(v << 1) + sum(v << 1 | 1)
      max(v) = Math.max(max(v << 1), max(v << 1 | 1))
    }

    def print(): Unit = {
      out.println(a.mkString(","))
    }

    def print_1(): Unit = {
      out.println(max.mkString(","))
    }

    def build(v: Int, tl: Int, tr: Int): Unit = {
      if(tl == tr) {
        sum(v) = a(tl)
        max(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        build(v << 1, tl, tm)
        build(v << 1 | 1, tm + 1, tr)
        merge(v)
      }
    }

    def updateRange(v: Int, tl: Int, tr: Int, l: Int, r: Int, x: Int): Unit = {
      if(l > r) {}
      else if(l == tl && r == tr && max(v) < x) {}
      else if(tl == tr) {
        a(tl) = a(tl) % x
        sum(v) = a(tl)
        max(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        updateRange(v << 1, tl, tm, l, Math.min(r, tm), x)
        updateRange(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r, x)
        merge(v)
      }
    }

    def updatePoint(v: Int, tl: Int, tr: Int, pos: Int, x: Int): Unit = {
      if(tl == tr) {
        a(tl) = x
        sum(v) = a(tl)
        max(v) = a(tl)
      } else {
        val tm = tl + (tr - tl) / 2
        if(pos <= tm) {
          updatePoint(v << 1, tl, tm, pos, x)
        } else {
          updatePoint(v << 1 | 1, tm + 1, tr, pos, x)
        }
        merge(v)
      }
    }

    def get(v: Int, tl: Int, tr: Int, l: Int, r: Int): Long = {
      if(l > r) 0L
      else if(l == tl && r == tr) sum(v).toLong
      else {
        val tm = tl + (tr - tl) / 2
        get(v << 1, tl, tm, l, Math.min(r, tm)) +
        get(v << 1 | 1, tm + 1, tr, Math.max(tm + 1, l), r)
      }
    }
  }
}


One day Prof. Slim decided to leave the kingdom of the GUC to join the kingdom of the GIU. He was given an easy online assessment to solve before joining the GIU. Citizens of the GUC were happy sad to see the prof leaving, so they decided to hack into the system and change the online assessment into a harder one so that he stays at the GUC. After a long argument, they decided to change it into the following problem.Given an array of $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$, where $$$a_{i} \neq 0$$$, check if you can make this array sorted by using the following operation any number of times (possibly zero). An array is sorted if its elements are arranged in a non-decreasing order.  select two indices $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$) such that $$$a_i$$$ and $$$a_j$$$ have different signs. In other words, one must be positive and one must be negative.  swap the signs of $$$a_{i}$$$ and $$$a_{j}$$$. For example if you select $$$a_i=3$$$ and $$$a_j=-2$$$, then they will change to $$$a_i=-3$$$ and $$$a_j=2$$$. Prof. Slim saw that the problem is still too easy and isn't worth his time, so he decided to give it to you to solve.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of the array $$$a$$$. The next line contain $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_{i} \le 10^9$$$, $$$a_{i} \neq 0$$$) separated by spaces describing elements of the array $$$a$$$.  It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, print "YES" if the array can be sorted in the non-decreasing order, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the first test case, there is no way to make the array sorted using the operation any number of times.In the second test case, the array is already sorted.In the third test case, we can swap the sign of the $$$1$$$-st element with the sign of the $$$5$$$-th element, and the sign of the $$$3$$$-rd element with the sign of the $$$6$$$-th element, this way the array will be sorted.In the fourth test case, there is no way to make the array sorted using the operation any number of times.

object Task1 extends App {

  import scala.io.StdIn

  def readLine: String = StdIn.readLine()

  def readNum: Int = StdIn.readLine().toInt

  def isSorted(array: Array[Int]): Boolean = {
    var sorted = true
    var pos = 0

    while (sorted && pos < array.length - 1) {
      if (array(pos) > array(pos + 1)) {
        sorted = false
      }
      pos += 1
    }

    sorted
  }

  val testCases = readNum

  for (_ <- 0 until testCases) {
    readLine
    val inputNumbers = readLine.split(" ").map(_.toInt)

    var leftPos = 0
    var rightPos = inputNumbers.length - 1

    while (leftPos != rightPos) {
      while (leftPos != rightPos && inputNumbers(leftPos) < 0) {
        leftPos += 1
      }

      while (leftPos != rightPos && inputNumbers(rightPos) > 0) {
        rightPos -= 1
      }

      inputNumbers(leftPos) = -inputNumbers(leftPos)
      inputNumbers(rightPos) = -inputNumbers(rightPos)
    }

    if (isSorted(inputNumbers)) {
      println("YES")
    } else {
      println("NO")
    }

  }

}


The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring.String x(i, j) contains string "bear", if there is such index k (i ≤ k ≤ j - 3), that sk = b, sk + 1 = e, sk + 2 = a, sk + 3 = r.Help the bear cope with the given problem.

The first line contains a non-empty string s (1 ≤ |s| ≤ 5000). It is guaranteed that the string only consists of lowercase English letters.

Print a single number — the answer to the problem.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val str = in.next()
  val l = str.length
  println((0 until str.length).foldLeft(0L) {
    case(count, i) =>
      val index = str.indexOf("bear", i)
      count + (if (index == -1) 0 else l - index - 3)
  })
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Long = {
    val S = sc.nextLine
    val L = S.length

    @tailrec
    def loop(acc: Long, i: Int): Long = {
      val j = S.indexOf("bear", i)
      if (j < 0) acc
      else loop(acc + (j - i + 1) * (L - j - 3), j + 1)
    }

    loop(0, 0)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Long = {
    val S = sc.nextLine
    val L = S.length

    @tailrec
    def loop(acc: Long, i: Int): Long = {
      val j = S.indexOf("bear", i)
      if (j < 0) acc
      else loop(acc + (j + 1) * (L - j - 3), j + 1)
    }

    loop(0, 0)
  }

  out.println(solve)
  out.close
}


You are given a sorted array $$$a_1, a_2, \dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\sum\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 1 \le a_i \le 10^9$$$, $$$a_i \ge a_{i-1}$$$).

Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$.

//package codeforces.contest1197

object ArraySplitting {

  def main(args: Array[String]): Unit = {
    val Array(n, k) = io.StdIn.readLine().split(" ").map(_.toInt)
    println(
      if (n == 1) {
        io.StdIn.readInt()
        0
      }
      else {
        io.StdIn
          .readLine()
          .split(" ")
          .map(_.toInt)
          .sliding(2)
          .map(arr => arr(1) - arr(0))
          .toArray
          .sorted
          .slice(0, n - k)
          .sum
      }
    )
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, K = ni()
    val A = na(N)
    val D = Array.ofDim[Int](N - 1)
    REP(N - 1) { i =>
      D(i) = A(i + 1) - A(i)
    }
    sort(D)
    debug(D)
    val ans = sumL(D.take(max(0, N - K)))
    out.println(ans)
  }

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    java.util.Arrays.sort(a)
    a
  }
}


There is a pyramid which consists of $$$n$$$ floors. The floors are numbered from top to bottom in increasing order. In the pyramid, the $$$i$$$-th floor consists of $$$i$$$ rooms.Denote the $$$j$$$-th room on the $$$i$$$-th floor as $$$(i,j)$$$. For all positive integers $$$i$$$ and $$$j$$$ such that $$$1 \le j \le i < n$$$, there are $$$2$$$ one-way staircases which lead from $$$(i,j)$$$ to $$$(i+1,j)$$$ and from $$$(i,j)$$$ to $$$(i+1,j+1)$$$ respectively.In each room you can either put a torch or leave it empty. Define the brightness of a room $$$(i, j)$$$ to be the number of rooms with a torch from which you can reach the room $$$(i, j)$$$ through a non-negative number of staircases.For example, when $$$n=5$$$ and torches are placed in the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,2)$$$, $$$(4,1)$$$, $$$(4,3)$$$, and $$$(5,3)$$$, the pyramid can be illustrated as follows:  In the above picture, rooms with torches are colored in yellow, and empty rooms are white. The blue numbers in the bottom-right corner indicate the brightness of the rooms.The room $$$(4,2)$$$ (the room with a star) has brightness $$$3$$$. In the picture below, the rooms from where you can reach $$$(4,2)$$$ have red border. The brightness is $$$3$$$ since there are three torches among these rooms.  The pyramid is called nice if and only if for all floors, all rooms in the floor have the same brightness.Define the brilliance of a nice pyramid to be the sum of brightness over the rooms $$$(1,1)$$$, $$$(2,1)$$$, $$$(3,1)$$$, ..., $$$(n,1)$$$.Find an arrangement of torches in the pyramid, such that the resulting pyramid is nice and its brilliance is maximized.We can show that an answer always exists. If there are multiple answers, output any one of them.

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The only line of each test case contains a single positive integer $$$n$$$ ($$$1 \le n \le 500$$$) — the number of floors in the pyramid. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$500$$$.

For each test case, output $$$n$$$ lines, the arrangement of torches in the pyramid. The $$$i$$$-th line should contain $$$i$$$ integers, each separated with a space. The $$$j$$$-th integer on the $$$i$$$-th line should be $$$1$$$ if room $$$(i,j)$$$ has a torch, and $$$0$$$ otherwise. We can show that an answer always exists. If there are multiple answers, output any one of them.

NoteIn the third test case, torches are placed in $$$(1,1)$$$, $$$(2,1)$$$, $$$(2,2)$$$, $$$(3,1)$$$, and $$$(3,3)$$$.  The pyramid is nice as rooms on each floor have the same brightness. For example, all rooms on the third floor have brightness $$$3$$$.The brilliance of the pyramid is $$$1+2+3 = 6$$$. It can be shown that no arrangements with $$$n=3$$$ will have a greater brilliance.

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 10:36
 * @note
 * 1734B. Bright, Nice, Brilliant | 难度：800
 */
object Solution1734B {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    val sb = new StringBuilder
    for (_ <- 0 until t) {
      val n = StdIn.readInt()
      sb.clear()
      sb.append("1")
      println(sb)
      if(n > 1) {
        sb.append(" 1")
        println(sb)
      }
      for (i <- 2 until n) {
        sb.delete(sb.length - 2, sb.length)
        sb.append(" 0 1")
        println(sb)
      }
    }
  }
}

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 10:36
 * @note
 * 1734B. Bright, Nice, Brilliant | 难度：800
 */
object Solution1734B {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    val sb = new StringBuilder
    for (_ <- 0 until t) {
      val n = StdIn.readInt()
      sb.clear()
      sb.append("1")
      println(sb)
      if(n > 1) {
        sb.append(" 1")
        println(sb)
      }
      for (i <- 1 until n) {
        sb.delete(sb.length - 2, sb.length)
        sb.append(" 0 1")
        println(sb)
      }
    }
  }
}

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 10:36
 * @note
 * 1734B. Bright, Nice, Brilliant | 难度：800
 */
object Solution1734B {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 0 until t) {
      val n = StdIn.readInt()
      for (j <- 0 until n) {
        if (j == 0 || j == n - 1) print("1") else print("0")
      }
      println()
    }
  }
}


Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.

If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).

NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below:   In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$.

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

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

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

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

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

    val p = gcd(N * M, K)
    if (K / p > 2) {
      out.println("NO")
      return ()
    }

    val pn = gcd(N, p)
    val pm = p / pn
    val n0 = N / pn
    val m0 = M / pm

    val (x, y) = if (K / p == 2) {
      (n0, m0)
    } else {
      if (2 * n0 <= N) (2 * n0, m0) else (n0, 2 * m0)
    }

    out.println("YES")
    out.println("0 0")
    out.println(s"$x 0")
    out.println(s"0 $y")
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a
    else gcd(b, a % b)
  }

  def gcd(as: Array[Long]): Long = {
    var res = as(0)
    rep(as.length - 1, 1) { i =>
      res = gcd(res, as(i))
    }
    res
  }

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


The only difference between easy and hard versions is the constraints.Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of $$$n$$$ consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the $$$i$$$-th picture has beauty $$$a_i$$$.Vova wants to repost exactly $$$x$$$ pictures in such a way that:   each segment of the news feed of at least $$$k$$$ consecutive pictures has at least one picture reposted by Vova;  the sum of beauty values of reposted pictures is maximum possible. For example, if $$$k=1$$$ then Vova has to repost all the pictures in the news feed. If $$$k=2$$$ then Vova can skip some pictures, but between every pair of consecutive pictures Vova has to repost at least one of them.Your task is to calculate the maximum possible sum of values of reposted pictures if Vova follows conditions described above, or say that there is no way to satisfy all conditions.

The first line of the input contains three integers $$$n, k$$$ and $$$x$$$ ($$$1 \le k, x \le n \le 200$$$) — the number of pictures in the news feed, the minimum length of segment with at least one repost in it and the number of pictures Vova is ready to repost. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the beauty of the $$$i$$$-th picture.

Print -1 if there is no way to repost some pictures to satisfy all the conditions in the problem statement. Otherwise print one integer — the maximum sum of values of reposted pictures if Vova follows conditions described in the problem statement.

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, K, X = ni()
    val A = na(N)

    val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
    dp(0).add(0, 0)
    rep(N, 1) { i =>
      val a = A(i - 1)
      rep_r(X) { x =>
        if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
      }
    }

    val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
    out.println(ans)
  }

  // todo test
  /**
    * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
    * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
    */
  class SlideMax(k: Int) {
    case class Entry(i: Int, v: Long)

    val queue = new java.util.ArrayDeque[Entry]()

    def nonEmpty(i: Int): Boolean = {
      maintenance(i)
      !queue.isEmpty
    }

    def max(i: Int): Long = {
      maintenance(i)
      queue.peek().v
    }

    def add(i: Int, x: Long): Unit = {
      maintenance(i)

      // 条件逆さまにすると最小になる
      while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()
      queue.addLast(Entry(i, x))
    }

    def maintenance(i: Int): Unit = {
      while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

object F extends App {
	val n = InputReader.nextInt
	val k = InputReader.nextInt
	val x = InputReader.nextInt
	var arr = Array.fill(n + 1)(0)

	for(i <- 1 to n) arr(i) = InputReader.nextInt

	val prv = Array.fill(n + 1)(-1L)
	val cur = Array.fill(n + 1)(-1L)

	prv(0) = 0L

	for (j <- 1 to x) {
		val q: Deque[Int] = new LinkedList[Int]()

		for (i <- 0 to n) {
			while (!q.isEmpty && i - q.getFirst > k)
				q.pollFirst

			cur(i) = if (q.isEmpty || prv(q.getFirst) == -1) -1 else prv(q.getFirst) + arr(i)

			while (!q.isEmpty && prv(i) >= prv(q.getLast))
				q.pollLast

			q.addLast(i)
		}

		for (i <- 0 to n) {
			prv(i) = cur(i)
			cur(i) = -1L
		}
	}

	println(prv.takeRight(k).max)
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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, K, X = ni()
    val A = na(N)

    val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
    dp(0).add(0, 0)
    rep(N, 1) { i =>
      val a = A(i - 1)
      rep_r(X) { x =>
        if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
      }

      ""
    }

    val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
    out.println(ans)
  }

  // todo test
  /**
    * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
    * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
    */
  class SlideMax(k: Int) {
    case class Entry(i: Int, v: Long)

    val queue = new java.util.ArrayDeque[Entry]()

    def nonEmpty(i: Int): Boolean = {
      maintenance(i)
      !queue.isEmpty
    }

    def max(i: Int): Long = {
      maintenance(i)
      queue.peek().v
    }

    def add(i: Int, x: Long): Unit = {
      maintenance(i)

      // 条件逆さまにすると最小になる
      while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()
      queue.addLast(Entry(i, x))
    }

    def maintenance(i: Int): Unit = {
      while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()
    }
  }

  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[Int](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 N, K, X = ni()
    val A = na(N)

    val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
    dp(0).add(0, 0)
    rep(N, 1) { i =>
      val a = A(i - 1)
      rep_r(X) { x =>
        if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
      }
    }

    val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
    out.println(ans)
  }

  // todo test
  /**
    * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
    * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
    */
  class SlideMax(k: Int) {
    case class Entry(i: Int, v: Long)

    val queue = new java.util.ArrayDeque[Entry]()

    def nonEmpty(i: Int): Boolean = {
      maintenance(i)
      !queue.isEmpty
    }

    def max(i: Int): Long = {
      maintenance(i)
      queue.peek().v
    }

    def add(i: Int, x: Long): Unit = {
      maintenance(i)

      // 条件逆さまにすると最小になる
      while(!queue.isEmpty && queue.peekLast().v <= x) queue.removeLast()
      queue.addLast(Entry(i, x))
    }

    def maintenance(i: Int): Unit = {
      while (!queue.isEmpty && k < i - queue.peek().i + 1) queue.removeFirst()
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

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

object F extends App {
	val n = InputReader.nextInt
	val k = InputReader.nextInt
	val x = InputReader.nextInt
	var arr = Array.fill(n + 1)(0)

	for(i <- 1 to n) arr(i) = InputReader.nextInt

	val prv = Array.fill(n + 1)(-1L)
	val cur = Array.fill(n + 1)(-1L)

	prv(0) = 0L

	for (j <- 1 to x) {
		val q: Deque[Int] = new ArrayDeque[Int]()

		for (i <- 0 to n) {
			while (!q.isEmpty && i - q.getFirst > k)
				q.pollFirst

			cur(i) = if (q.isEmpty || prv(q.getFirst) == -1) -1 else prv(q.getFirst) + arr(i)

			while (!q.isEmpty && prv(i) >= prv(q.getLast))
				q.pollLast

			q.addLast(i)
		}

		for (i <- 0 to n) {
			prv(i) = cur(i)
			cur(i) = -1L
		}
	}

	println(prv.takeRight(k).max)
}

object InputReader {
	val rd = new BufferedReader(new InputStreamReader(System.in), 32768);
	var tk = new StringTokenizer("")

	def read() = {
		while (!tk.hasMoreTokens)
			tk = new StringTokenizer(readLine)

		tk.nextToken
	}

	def readLine() = rd.readLine
	def nextInt() = read.toInt
	def nextLong() = read.toLong
	def nextDouble() = read.toDouble
}

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, K, X = ni()
    val A = na(N)

    val dp = Array.fill[SlideMax](X + 1)(new SlideMax(K))
    dp(0).add(0, 0)
    rep(N, 1) { i =>
      val a = A(i - 1)
      rep_r(X) { x =>
        if (dp(x).nonEmpty(i - 1)) dp(x + 1).add(i, dp(x).max(i - 1) + a)
      }
    }

    val ans = if (dp(X).nonEmpty(N)) dp(X).max(N) else -1
    out.println(ans)
  }

  // todo test
  /**
    * DPなんかでKの個数を維持しつつ区間の最大を探す時に使う
    * DP上で１個前の状態からとるなどするときはmax(i-1)のようにその時のインデックスをちゃんと渡さないといけないのに注意
    */
  class SlideMax(k: Int) {
    case class Entry(i: Int, v: Long)

    val queue = new java.util.ArrayDeque[Entry]()

    def nonEmpty(i: Int): Boolean = {
      maintenance(i)
      !queue.isEmpty
    }

    def max(i: Int): Long = {
      maintenance(i)
      queue.peek().v
    }

    def add(i: Int, x: Long): Unit = {
      maintenance(i)

      // 条件逆さまにすると最小になる
      while(!queue.isEmpty && queue.peekLast().v < x) queue.removeLast()
      queue.addLast(Entry(i, x))
    }

    def maintenance(i: Int): Unit = {
      if (!queue.isEmpty && k < i - queue.peek().i + 1) queue.poll()
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


You are given a string $$$a$$$, consisting of $$$n$$$ characters, $$$n$$$ is even. For each $$$i$$$ from $$$1$$$ to $$$n$$$ $$$a_i$$$ is one of 'A', 'B' or 'C'.A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)"), and ")(", "(" and ")" are not.You want to find a string $$$b$$$ that consists of $$$n$$$ characters such that:   $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$. In other words, you want to replace all occurrences of 'A' with the same type of bracket, then all occurrences of 'B' with the same type of bracket and all occurrences of 'C' with the same type of bracket.Your task is to determine if such a string $$$b$$$ exists.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The only line of each testcase contains a string $$$a$$$. $$$a$$$ consists only of uppercase letters 'A', 'B' and 'C'. Let $$$n$$$ be the length of $$$a$$$. It is guaranteed that $$$n$$$ is even and $$$2 \le n \le 50$$$.

For each testcase print "YES" if there exists such a string $$$b$$$ that:    $$$b$$$ is a regular bracket sequence;  if for some $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) $$$a_i=a_j$$$, then $$$b_i=b_j$$$.  Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).

NoteIn the first testcase one of the possible strings $$$b$$$ is "(())()".In the second testcase one of the possible strings $$$b$$$ is "()()".

import scala.annotation.tailrec
import scala.io.Source

object abcString extends App{
  val strings = for (str <- Source.stdin.getLines().drop(1)) yield str

  def yesNo(str: List[Char]): Boolean = {
    lazy val firstCount = str.count(_ == str.head)
    lazy val lastCount = str.count(_ == str.last)

    @tailrec
    def bracesMatch(openBraces: Int, first: Char, last: Char, remaining: List[Char]): Boolean = {
      if (openBraces >= 0)
        remaining match {
          case Nil => if (openBraces == 0) true else false
          case c :: cs => {
            val newOpenBraces = {
              if (c == first) openBraces + 1
              else if (c == last) openBraces - 1
              else if (firstCount > lastCount) openBraces - 1
              else openBraces + 1
            }
            bracesMatch(newOpenBraces, first, last, cs)
          }
        }
      else false
    }
    bracesMatch(0, str.head, str.last, str)
  }

  for (str <- strings) {
    val res =
      if (yesNo(str.toCharArray.toList)) "YES"
      else "NO"
    println(s"$res")
  }
}

import scala.annotation.tailrec
import scala.io.Source

object abcString extends App{
  val strings = for (str <- Source.stdin.getLines().drop(1)) yield str

  def yesNo(str: List[Char]): Boolean = {
    @tailrec
    def bracesMatch(openBraces: Int, first: Char, last: Char, remaining: List[Char]): Boolean = {
      if (openBraces >= 0)
        remaining match {
          case Nil => if (openBraces == 0) true else false
          case c :: cs =>
            if (c == first) bracesMatch(openBraces + 1, first, last, cs)
            else if (c == last) bracesMatch(openBraces - 1, first, last, cs)
            else if (str.count(_ == first) > str.count(_ == last)) bracesMatch(openBraces - 1, first, last, cs)
            else bracesMatch(openBraces + 1, first, last, cs)
        }
      else false
    }
    bracesMatch(0, str.head, str.last, str)
  }

  for (str <- strings) {
    val res =
      if (yesNo(str.toCharArray.toList)) "YES"
      else "NO"
    println(s"$res")
  }
}


Vasya has been playing Plane of Tanks with his friends the whole year. Now it is time to divide the participants into several categories depending on their results. A player is given a non-negative integer number of points in each round of the Plane of Tanks. Vasya wrote results for each round of the last year. He has n records in total.In order to determine a player's category consider the best result obtained by the player and the best results of other players. The player belongs to category:   "noob" — if more than 50% of players have better results;  "random" — if his result is not worse than the result that 50% of players have, but more than 20% of players have better results;  "average" — if his result is not worse than the result that 80% of players have, but more than 10% of players have better results;  "hardcore" — if his result is not worse than the result that 90% of players have, but more than 1% of players have better results;  "pro" — if his result is not worse than the result that 99% of players have.  When the percentage is calculated the player himself is taken into account. That means that if two players played the game and the first one gained 100 points and the second one 1000 points, then the first player's result is not worse than the result that 50% of players have, and the second one is not worse than the result that 100% of players have.Vasya gave you the last year Plane of Tanks results. Help Vasya determine each player's category.

The first line contains the only integer number n (1 ≤ n ≤ 1000) — a number of records with the players' results. Each of the next n lines contains a player's name and the amount of points, obtained by the player for the round, separated with a space. The name contains not less than 1 and no more than 10 characters. The name consists of lowercase Latin letters only. It is guaranteed that any two different players have different names. The amount of points, obtained by the player for the round, is a non-negative integer number and does not exceed 1000.

Print on the first line the number m — the number of players, who participated in one round at least. Each one of the next m lines should contain a player name and a category he belongs to, separated with space. Category can be one of the following: "noob", "random", "average", "hardcore" or "pro" (without quotes). The name of each player should be printed only once. Player names with respective categories can be printed in an arbitrary order.

5
vasya 100
vasya 200
artem 100
kolya 200
igor 250

4
artem noob
igor pro
kolya random
vasya random

NoteIn the first example the best result, obtained by artem is not worse than the result that 25% of players have (his own result), so he belongs to category "noob". vasya and kolya have best results not worse than the results that 75% players have (both of them and artem), so they belong to category "random". igor has best result not worse than the result that 100% of players have (all other players and himself), so he belongs to category "pro".In the second example both players have the same amount of points, so they have results not worse than 100% players have, so they belong to category "pro".

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

object CF105B {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val userToMaxScoreBuilder = mutable.Map.empty[String, Int]
    for (i <- 0 until n) {
      val user = sc.next()
      val score = sc.nextInt()
      userToMaxScoreBuilder(user) = max(score, userToMaxScoreBuilder.getOrElse(user, 0))
    }
    val userToMaxScore = userToMaxScoreBuilder.toMap
    val numberOfUsers = userToMaxScore.keys.size
    println(numberOfUsers)
    for (user <- userToMaxScore.keys) {
      val maxScore = userToMaxScore(user)
      val countAbove = userToMaxScore.values.count(_ > maxScore)
      if (countAbove <= numberOfUsers * 1 / 100) {
        println(user + " " + "pro")
      } else if (countAbove <= numberOfUsers * 10 / 100) {
        println(user + " " + "hardcore")
      } else if (countAbove <= numberOfUsers * 20 / 100) {
        println(user + " " + "average")
      } else if (countAbove <= numberOfUsers * 50 / 100) {
        println(user + " " + "random")
      } else {
        println(user + " " + "noob")
      }
    }
  }
}

/**
 * Created by IntelliJ IDEA.
 * User: ymatsux
 * Date: 12/05/06
 * Time: 2:16
 * To change this template use File | Settings | File Templates.
 */

import java.util.Scanner
import scala.collection.mutable

object CF105B {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val userToMaxScoreBuilder = mutable.Map.empty[String, Int]
    for (i <- 0 until n) {
      val user = sc.next()
      val score = sc.nextInt()
      userToMaxScoreBuilder(user) = math.max(score, userToMaxScoreBuilder.getOrElse(user, 0))
    }
    val userToMaxScore = userToMaxScoreBuilder.toMap
    val numberOfUsers = userToMaxScore.keys.size
    println(numberOfUsers)

    val scores = userToMaxScore.values.toArray
    for (user <- userToMaxScore.keys) {
      val maxScore = userToMaxScore(user)
      val countAbove = scores.count(_ > maxScore)
      if (countAbove <= numberOfUsers * 1 / 100) {
        println(user + " " + "pro")
      } else if (countAbove <= numberOfUsers * 10 / 100) {
        println(user + " " + "hardcore")
      } else if (countAbove <= numberOfUsers * 20 / 100) {
        println(user + " " + "average")
      } else if (countAbove <= numberOfUsers * 50 / 100) {
        println(user + " " + "random")
      } else {
        println(user + " " + "noob")
      }
    }
  }
}

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

object CF105B {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    val userToMaxScoreBuilder = mutable.Map.empty[String, Int]
    for (i <- 0 until n) {
      val user = sc.next()
      val score = sc.nextInt()
      userToMaxScoreBuilder(user) = max(score, userToMaxScoreBuilder.getOrElse(user, 0))
    }
    val userToMaxScore = userToMaxScoreBuilder.toMap
    val numberOfUsers = userToMaxScore.keys.size
    println(numberOfUsers)

    val scores = userToMaxScore.values
    for (user <- userToMaxScore.keys) {
      val maxScore = userToMaxScore(user)
      val countAbove = scores.count(_ > maxScore)
      if (countAbove <= numberOfUsers * 1 / 100) {
        println(user + " " + "pro")
      } else if (countAbove <= numberOfUsers * 10 / 100) {
        println(user + " " + "hardcore")
      } else if (countAbove <= numberOfUsers * 20 / 100) {
        println(user + " " + "average")
      } else if (countAbove <= numberOfUsers * 50 / 100) {
        println(user + " " + "random")
      } else {
        println(user + " " + "noob")
      }
    }
  }
}


Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change.You have to find the minimum number of digits in which these two numbers can differ.

The first line contains integer k (1 ≤ k ≤ 109). The second line contains integer n (1 ≤ n < 10100000). There are no leading zeros in n. It's guaranteed that this situation is possible.

Print the minimum number of digits in which the initial number and n can differ.

NoteIn the first example, the initial number could be 12.In the second example the sum of the digits of n is not less than k. The initial number could be equal to n.

object B extends App {

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

  val Array(k) = readInts(1)
  val n = readLine.map(_ - '0').sorted

  var sum = n.sum

  var i = 0
  while (i < n.length && sum < k) {
    sum += 9 - n(i)
    i += 1
  }

  println(i)
}

import scala.io.StdIn

object Main extends App {

  val k = StdIn.readLine().toInt
  val n = StdIn.readLine().sortWith(_ < _)

  val sum = n.foldLeft(0)((z: Int,c: Char) => {
    z + c - 48
  })

  var diff = k - sum
  var count = 0
  while(diff > 0 && count < n.length) {
    diff = diff - (9 - (n.charAt(count) - 48))
    count = count + 1
  }
  println(count)

}

object BTheNumberOnTheBoard extends App {
  val k: Int = scala.io.StdIn.readLine.toInt
  val n: String = scala.io.StdIn.readLine

  var cnt = Array.fill(10){0}
  var cur = n.foldLeft(0) { (cur, c) =>
    val digit = c - '0'
    cnt(digit) = cnt(digit) + 1
    cur + digit
  }

  var ans = 0
  for {
    i <- 0 until 10; j <- 0 until cnt(i)
    if cur < k
  } {
    ans = ans + 1
    cur = cur + 9 - i
  }

  print(ans)
}

import scala.io.StdIn

object Main extends App {

  val k = StdIn.readLine().toInt
  val n = StdIn.readLine().sortWith(_ < _)

  val sum = n.foldLeft(0)((z: Int,c: Char) => {
    z + c - 48
  })

  var diff = k - sum
  var count = 0

  while(diff > 0 && count < n.length) {
    diff = diff - (n.charAt(count) - 48)
    count = count + 1
  }
  println(count)

}


Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him; find out if he will manage to compose the needed text.

The first line contains a newspaper heading s1. The second line contains the letter text s2. s1 и s2 are non-empty lines consisting of spaces, uppercase and lowercase Latin letters, whose lengths do not exceed 200 symbols. The uppercase and lowercase letters should be differentiated. Vasya does not cut spaces out of the heading.

If Vasya can write the given anonymous letter, print YES, otherwise print NO

Instead of dogging Your footsteps it disappears but you dont notice anything
where is your dog

Instead of dogging Your footsteps it disappears but you dont notice anything
Your dog is upstears

Instead of dogging your footsteps it disappears but you dont notice anything
Your dog is upstears

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val text = in.next.filter(_ != ' ').groupBy(identity).map(i => i._1 -> i._2.length)
  val message = in.next.filter(_ != ' ').groupBy(identity).map(i => i._1 -> i._2.length)
  if (message.keys.forall(i => text.getOrElse(i, 0) >= message(i)))
    println("YES")
  else
    println("NO")

}

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var s1 = readLine;
    var s2 = readLine;
    for (i <- 0 until s2.length) {
      if (s2(i) != ' ' && s1.contains(s2(i))) {
        s1 = s1.replaceFirst(s2(i).toString, "");
      } else if (s2(i) != ' ') {
        println("NO");
        return;
      }
    }
    println("YES");
  }
}

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var s1 = readLine;
    var s2 = readLine;
    for (i <- 0 until s2.length) {
      if (s2(i) != ' ' && s1.contains(s2(i))) {
        s1.replace(s2(i).toString, "");
      } else if (s2(i) != ' ') {
        println("NO");
        return;
      }
    }
    println("YES");
  }
}

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var s1 = readLine;
    var s2 = readLine;
    for (i <- 0 until s2.length) {
      if (s2(i) != ' ' && s1.contains(s2(i))) {
        s1 = s1.replace(s2(i).toString, "");
      } else if (s2(i) != ' ') {
        println("NO");
        return;
      }
    }
    println("YES");
  }
}


This is a simplified version of the problem B2. Perhaps you should read the problem B2 before you start solving B1.Paul and Mary have a favorite string $$$s$$$ which consists of lowercase letters of the Latin alphabet. They want to paint it using pieces of chalk of two colors: red and green. Let's call a coloring of a string wonderful if the following conditions are met:  each letter of the string is either painted in exactly one color (red or green) or isn't painted;  each two letters which are painted in the same color are different;  the number of letters painted in red is equal to the number of letters painted in green;  the number of painted letters of this coloring is maximum among all colorings of the string which meet the first three conditions. E. g. consider a string $$$s$$$ equal to "kzaaa". One of the wonderful colorings of the string is shown in the figure.    The example of a wonderful coloring of the string "kzaaa". Paul and Mary want to learn by themselves how to find a wonderful coloring of the string. But they are very young, so they need a hint. Help them find $$$k$$$ — the number of red (or green, these numbers are equal) letters in a wonderful coloring.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one non-empty string $$$s$$$ which consists of lowercase letters of the Latin alphabet. The number of characters in the string doesn't exceed $$$50$$$.

For each test case, output a separate line containing one non-negative integer $$$k$$$ — the number of letters which will be painted in red in a wonderful coloring.

NoteThe first test case contains the string from the statement. One of the wonderful colorings is shown in the figure. There's no wonderful coloring containing $$$3$$$ or more red letters because the total number of painted symbols will exceed the string's length.The string from the second test case can be painted as follows. Let's paint the first occurrence of each of the letters "c", "o", "e" in red and the second ones in green. Let's paint the letters "d", "f" in red and "r", "s" in green. So every letter will be painted in red or green, hence the answer better than $$$5$$$ doesn't exist.The third test case contains the string of distinct letters, so you can paint any set of characters in red, as long as the size of this set doesn't exceed half of the size of the string and is the maximum possible.The fourth test case contains a single letter which cannot be painted in red because there will be no letter able to be painted in green.The fifth test case contains a string of identical letters, so there's no way to paint more than one letter in red.

import scala.io.StdIn

object Main {
  implicit class Rep(n: Int) {
    def times[A](f: => A) { 1 to n foreach (_ => f) }
  }
  def main(args: Array[String]) = {
    StdIn.readInt.times {
      def f(string: String) = {
        val (gt2, rest) =
          (string.groupBy(identity) mapValues (_.length)).partition(kv =>
            kv._2 >= 2
          )
        println(gt2.size + (rest.size / 2))
      }
      f(StdIn.readLine)
    }
  }
}

object B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    val k = {
      val cs = Array.fill(26)(0)
      s.foreach(c => cs(c - 'a') += 1)

      val (c1, c2) = (cs.count(_ == 1), cs.count(_ > 1))

      c2 + c1 / 2
    }

    println(k)
  }
}


Eugene likes working with arrays. And today he needs your help in solving one challenging task.An array $$$c$$$ is a subarray of an array $$$b$$$ if $$$c$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.Let's call a nonempty array good if for every nonempty subarray of this array, sum of the elements of this subarray is nonzero. For example, array $$$[-1, 2, -3]$$$ is good, as all arrays $$$[-1]$$$, $$$[-1, 2]$$$, $$$[-1, 2, -3]$$$, $$$[2]$$$, $$$[2, -3]$$$, $$$[-3]$$$ have nonzero sums of elements. However, array $$$[-1, 2, -1, -3]$$$ isn't good, as his subarray $$$[-1, 2, -1]$$$ has sum of elements equal to $$$0$$$.Help Eugene to calculate the number of nonempty good subarrays of a given array $$$a$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 2 \times 10^5$$$)  — the length of array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$)  — the elements of $$$a$$$.

Output a single integer  — the number of good subarrays of $$$a$$$.

NoteIn the first sample, the following subarrays are good: $$$[1]$$$, $$$[1, 2]$$$, $$$[2]$$$, $$$[2, -3]$$$, $$$[-3]$$$. However, the subarray $$$[1, 2, -3]$$$ isn't good, as its subarray $$$[1, 2, -3]$$$ has sum of elements equal to $$$0$$$.In the second sample, three subarrays of size 1 are the only good subarrays. At the same time, the subarray $$$[41, -41, 41]$$$ isn't good, as its subarray $$$[41, -41]$$$ has sum of elements equal to $$$0$$$.

object C extends App {
  implicit class SetOps[A](val set: Set[A]) extends AnyVal {
    def fillWhile(xs: List[A]): (List[A], Set[A]) = xs match {
      case Nil => (Nil, set)
      case x :: rs =>
        if (set.contains(x)) (xs, set) else (set + x).fillWhile(rs)
    }
  }

  private def howGood(as: List[Int]): Long = {

    @scala.annotation.tailrec
    def go(ps: List[Long],
           qs: List[Long],
           s: Set[Long] = Set(0L),
           acc: Long = 0L): Long = ps match {
      case Nil => acc
      case x :: xs =>
        val (nqs, ns) = s.fillWhile(qs)
        go(xs, nqs, ns - x, acc + ns.size - 1)
    }

    val ps = as.scanLeft(0L)(_ + _)

    go(ps, ps.tail)
  }

  val n = scala.io.StdIn.readInt()
  val as = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

  println(howGood(as))
}