Monocarp and Polycarp are learning new programming techniques. Now they decided to try pair programming.It's known that they have worked together on the same file for $$$n + m$$$ minutes. Every minute exactly one of them made one change to the file. Before they started, there were already $$$k$$$ lines written in the file.Every minute exactly one of them does one of two actions: adds a new line to the end of the file or changes one of its lines.Monocarp worked in total for $$$n$$$ minutes and performed the sequence of actions $$$[a_1, a_2, \dots, a_n]$$$. If $$$a_i = 0$$$, then he adds a new line to the end of the file. If $$$a_i > 0$$$, then he changes the line with the number $$$a_i$$$. Monocarp performed actions strictly in this order: $$$a_1$$$, then $$$a_2$$$, ..., $$$a_n$$$.Polycarp worked in total for $$$m$$$ minutes and performed the sequence of actions $$$[b_1, b_2, \dots, b_m]$$$. If $$$b_j = 0$$$, then he adds a new line to the end of the file. If $$$b_j > 0$$$, then he changes the line with the number $$$b_j$$$. Polycarp performed actions strictly in this order: $$$b_1$$$, then $$$b_2$$$, ..., $$$b_m$$$.Restore their common sequence of actions of length $$$n + m$$$ such that all actions would be correct — there should be no changes to lines that do not yet exist. Keep in mind that in the common sequence Monocarp's actions should form the subsequence $$$[a_1, a_2, \dots, a_n]$$$ and Polycarp's — subsequence $$$[b_1, b_2, \dots, b_m]$$$. They can replace each other at the computer any number of times.Let's look at an example. Suppose $$$k = 3$$$. Monocarp first changed the line with the number $$$2$$$ and then added a new line (thus, $$$n = 2, \: a = [2, 0]$$$). Polycarp first added a new line and then changed the line with the number $$$5$$$ (thus, $$$m = 2, \: b = [0, 5]$$$).Since the initial length of the file was $$$3$$$, in order for Polycarp to change line number $$$5$$$ two new lines must be added beforehand. Examples of correct sequences of changes, in this case, would be $$$[0, 2, 0, 5]$$$ and $$$[2, 0, 0, 5]$$$. Changes $$$[0, 0, 5, 2]$$$ (wrong order of actions) and $$$[0, 5, 2, 0]$$$ (line $$$5$$$ cannot be edited yet) are not correct.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$). Then $$$t$$$ test cases follow. Before each test case, there is an empty line. Each test case contains three lines. The first line contains three integers $$$k$$$, $$$n$$$, $$$m$$$ ($$$0 \le k \le 100$$$, $$$1 \le n, m \le 100$$$) — the initial number of lines in file and lengths of Monocarp's and Polycarp's sequences of changes respectively. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 300$$$). The third line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$0 \le b_j \le 300$$$).

For each test case print any correct common sequence of Monocarp's and Polycarp's actions of length $$$n + m$$$ or -1 if such sequence doesn't exist.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    readLine()
    val Array(k, n, m) = readLine().split(" ").map(_.toInt)
    val an             = readLine().split(" ").map(_.toInt)
    val bm             = readLine().split(" ").map(_.toInt)

    @annotation.tailrec
    def go(i: Int, j: Int, l: Int, ops: List[Int]): Option[List[Int]] =
      if (i == n && j == m) Some(ops)
      else if (i != n && an(i) == 0) go(i + 1, j, l + 1, 0 :: ops)
      else if (j != m && bm(j) == 0) go(i, j + 1, l + 1, 0 :: ops)
      else if (i != n && an(i) <= l) go(i + 1, j, l, an(i) :: ops)
      else if (j != m && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)
      else None

    go(0, 0, k, List.empty[Int]) match {
      case Some(ops) => println(ops.reverse.mkString(" "))
      case _         => println(-1)
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    readLine()
    val Array(k, n, m) = readLine().split(" ").map(_.toInt)
    val an             = readLine().split(" ").map(_.toInt)
    val bm             = readLine().split(" ").map(_.toInt)

    @annotation.tailrec
    def go(i: Int, j: Int, l: Int, ops: List[Int]): Option[List[Int]] =
      if (i == n && j == m) Some(ops)
      else if (i != n && an(i) == 0) go(i + 1, j, l + 1, 0 :: ops)
      else if (j != m && bm(j) == 0) go(i, j + 1, l + 1, 0 :: ops)
      else if (i != n && j != m && an(i) <= bm(j) && an(i) <= l) go(i + 1, j, l, an(i) :: ops)
      else if (i != n && j != m && bm(j) <= an(i) && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)
      else if (i == n && bm(j) <= l) go(i, j + 1, l, bm(j) :: ops)
      else if (j == m && an(i) <= l) go(i + 1, j, l, an(i) :: ops)
      else None

    go(0, 0, k, List.empty[Int]) match {
      case Some(ops) => println(ops.reverse.mkString(" "))
      case _         => println(-1)
    }
  }
}


Mike and Ann are sitting in the classroom. The lesson is boring, so they decided to play an interesting game. Fortunately, all they need to play this game is a string $$$s$$$ and a number $$$k$$$ ($$$0 \le k < |s|$$$).At the beginning of the game, players are given a substring of $$$s$$$ with left border $$$l$$$ and right border $$$r$$$, both equal to $$$k$$$ (i.e. initially $$$l=r=k$$$). Then players start to make moves one by one, according to the following rules: A player chooses $$$l^{\prime}$$$ and $$$r^{\prime}$$$ so that $$$l^{\prime} \le l$$$, $$$r^{\prime} \ge r$$$ and $$$s[l^{\prime}, r^{\prime}]$$$ is lexicographically less than $$$s[l, r]$$$. Then the player changes $$$l$$$ and $$$r$$$ in this way: $$$l := l^{\prime}$$$, $$$r := r^{\prime}$$$. Ann moves first. The player, that can't make a move loses.Recall that a substring $$$s[l, r]$$$ ($$$l \le r$$$) of a string $$$s$$$ is a continuous segment of letters from s that starts at position $$$l$$$ and ends at position $$$r$$$. For example, "ehn" is a substring ($$$s[3, 5]$$$) of "aaaehnsvz" and "ahz" is not.Mike and Ann were playing so enthusiastically that they did not notice the teacher approached them. Surprisingly, the teacher didn't scold them, instead of that he said, that he can figure out the winner of the game before it starts, even if he knows only $$$s$$$ and $$$k$$$.Unfortunately, Mike and Ann are not so keen in the game theory, so they ask you to write a program, that takes $$$s$$$ and determines the winner for all possible $$$k$$$.

The first line of the input contains a single string $$$s$$$ ($$$1 \leq |s| \leq 5 \cdot 10^5$$$) consisting of lowercase English letters.

Print $$$|s|$$$ lines. In the line $$$i$$$ write the name of the winner (print Mike or Ann) in the game with string $$$s$$$ and $$$k = i$$$, if both play optimally

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

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

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

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

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

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

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

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    var i = from
    while(i <= to) { 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]): 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にしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    val s = ns()
    val exists = Array.ofDim[Boolean](26)
    REP(s.length) { i =>
      // s(i)よりアルファベット順に小さい文字がでてきたか
      var ok = false
      REP(s(i)-'a') { c =>
        ok ||= exists(c)
      }
      exists(s(i)-'a') = true
      if (ok) {
        out.println("Ann")
      } else {
        out.println("Mike")
      }
    }
  }
}


Maxim wants to buy some games at the local game shop. There are $$$n$$$ games in the shop, the $$$i$$$-th game costs $$$c_i$$$.Maxim has a wallet which can be represented as an array of integers. His wallet contains $$$m$$$ bills, the $$$j$$$-th bill has value $$$a_j$$$.Games in the shop are ordered from left to right, Maxim tries to buy every game in that order.When Maxim stands at the position $$$i$$$ in the shop, he takes the first bill from his wallet (if his wallet is empty then he proceeds to the next position immediately) and tries to buy the $$$i$$$-th game using this bill. After Maxim tried to buy the $$$n$$$-th game, he leaves the shop.Maxim buys the $$$i$$$-th game if and only if the value of the first bill (which he takes) from his wallet is greater or equal to the cost of the $$$i$$$-th game. If he successfully buys the $$$i$$$-th game, the first bill from his wallet disappears and the next bill becomes first. Otherwise Maxim leaves the first bill in his wallet (this bill still remains the first one) and proceeds to the next game.For example, for array $$$c = [2, 4, 5, 2, 4]$$$ and array $$$a = [5, 3, 4, 6]$$$ the following process takes place: Maxim buys the first game using the first bill (its value is $$$5$$$), the bill disappears, after that the second bill (with value $$$3$$$) becomes the first one in Maxim's wallet, then Maxim doesn't buy the second game because $$$c_2 > a_2$$$, the same with the third game, then he buys the fourth game using the bill of value $$$a_2$$$ (the third bill becomes the first one in Maxim's wallet) and buys the fifth game using the bill of value $$$a_3$$$.Your task is to get the number of games Maxim will buy.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 1000$$$) — the number of games and the number of bills in Maxim's wallet. The second line of the input contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le 1000$$$), where $$$c_i$$$ is the cost of the $$$i$$$-th game. The third line of the input contains $$$m$$$ integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_j \le 1000$$$), where $$$a_j$$$ is the value of the $$$j$$$-th bill from the Maxim's wallet.

Print a single integer — the number of games Maxim will buy.

NoteThe first example is described in the problem statement.In the second example Maxim cannot buy any game because the value of the first bill in his wallet is smaller than the cost of any game in the shop.In the third example the values of the bills in Maxim's wallet are large enough to buy any game he encounter until he runs out of bills in his wallet.

import scala.io._

object A3 {

  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().take(3).toArray.map(_.split(' ').map(_.toInt))
    var j =0
    var count = 0
    for (i <- lines(2).indices) {
      while (j<lines(1).length && lines(1)(j) > lines(2)(i)) j+=1
      if (j<lines(1).length) {count+=1; j+=1}
    }
    println(count)
  }
}

object CFEDU47A extends App {

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

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

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

  def solve = {
    val n = nextInt
    val m = nextInt
    val games = (new Array[Int](n)).map(_ => nextInt)
    val bills = (new Array[Int](m)).map(_ => nextInt)

    def buy (games: Array[Int], bills: Array[Int], bought: Int): (Array[Int], Array[Int], Int) = {
      if (games.isEmpty || bills.isEmpty)
        return (games, bills, bought)
      if (games.head <= bills.head)
        return buy(games.tail, bills.tail, bought + 1)
      else
        return buy(games.tail, bills, bought)
    }

    out.println(buy(games, bills, 0)._3)
  }

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


Suppose you have an integer $$$v$$$. In one operation, you can:   either set $$$v = (v + 1) \bmod 32768$$$  or set $$$v = (2 \cdot v) \bmod 32768$$$. You are given $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$. What is the minimum number of operations you need to make each $$$a_i$$$ equal to $$$0$$$?

The first line contains the single integer $$$n$$$ ($$$1 \le n \le 32768$$$) — the number of integers. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i < 32768$$$).

Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to the minimum number of operations required to make $$$a_i$$$ equal to $$$0$$$.

NoteLet's consider each $$$a_i$$$:   $$$a_1 = 19$$$. You can, firstly, increase it by one to get $$$20$$$ and then multiply it by two $$$13$$$ times. You'll get $$$0$$$ in $$$1 + 13 = 14$$$ steps.  $$$a_2 = 32764$$$. You can increase it by one $$$4$$$ times: $$$32764 \rightarrow 32765 \rightarrow 32766 \rightarrow 32767 \rightarrow 0$$$.  $$$a_3 = 10240$$$. You can multiply it by two $$$4$$$ times: $$$10240 \rightarrow 20480 \rightarrow 8192 \rightarrow 16384 \rightarrow 0$$$.  $$$a_4 = 49$$$. You can multiply it by two $$$15$$$ times.

import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // =====================================

  def powtwo(x: Int) = ((x - 1) & x) == 0

  def calc(i: Int, count: Int = 0): Int = {
    if (count == 15) 15
    else if (i % 2 == 1) count
    else calc(i / 2, count + 1)
  }

  import Math._
  def add(i: Int, d: Int, count: Int = 1): Int = {
    if (i == 32768) min(d, count)
    else if (count == 15) d
    else if (i % 2 == 0) {
      add(i + 1, min(d, count + 15 - calc(i)), count + 1)
    }
    else add(i + 1, d, count + 1)
  }

  // 2^15
  def op(i: Int): Int = {
    val pt = 15 - calc(i)
    add(i + 1, pt)
  }

  def solve(n: Int, a: Array[Int]) = {
    a.foreach(x => print(s"${op(x)} "))
  }

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

    val n = readLine.toInt;
    val a = rsi
    solve(n, a)
  }
}


Alice and Bob play a game. There is a paper strip which is divided into n + 1 cells numbered from left to right starting from 0. There is a chip placed in the n-th cell (the last one).Players take turns, Alice is first. Each player during his or her turn has to move the chip 1, 2 or k cells to the left (so, if the chip is currently in the cell i, the player can move it into cell i - 1, i - 2 or i - k). The chip should not leave the borders of the paper strip: it is impossible, for example, to move it k cells to the left if the current cell has number i < k. The player who can't make a move loses the game.Who wins if both participants play optimally?Alice and Bob would like to play several games, so you should determine the winner in each game.

The first line contains the single integer T (1 ≤ T ≤ 100) — the number of games. Next T lines contain one game per line. All games are independent. Each of the next T lines contains two integers n and k (0 ≤ n ≤ 109, 3 ≤ k ≤ 109) — the length of the strip and the constant denoting the third move, respectively.

For each game, print Alice if Alice wins this game and Bob otherwise.

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n, k = ni()
      val win = if (n == 0) {
        false
      } else if (k % 3 != 0) {
        n % 3 != 0
      } else {
        val r = n % (k + 1)
        r == k || r % 3 != 0
      }

      if (win) out.println("Alice")
      else out.println("Bob")
    }
  }
}


Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:  it is up to a passenger to choose a plane to fly on;  if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs x zlotys (units of Polish currency). The only ticket office of the airport already has a queue of n passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all n passengers buy tickets according to the conditions of this offer?The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to n-th person.

The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of passengers in the queue and the number of planes in the airport, correspondingly. The next line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 1000) — ai stands for the number of empty seats in the i-th plane before the ticket office starts selling tickets. The numbers in the lines are separated by a space. It is guaranteed that there are at least n empty seats in total.

Print two integers — the maximum and the minimum number of zlotys that the airport administration can earn, correspondingly.

NoteIn the first test sample the number of passengers is equal to the number of empty seats, so regardless of the way the planes are chosen, the administration will earn the same sum.In the second sample the sum is maximized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 2-nd plane, the 3-rd person — to the 3-rd plane, the 4-th person — to the 1-st plane. The sum is minimized if the 1-st person in the queue buys a ticket to the 1-st plane, the 2-nd person — to the 1-st plane, the 3-rd person — to the 2-nd plane, the 4-th person — to the 2-nd plane.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val queue = new scala.collection.mutable.PriorityQueue[Int]()
  queue.enqueue(data:_*)
  val max = (1 to n).map{ _ =>
    val res = queue.dequeue()
    queue.enqueue(res - 1)
    res
  }.sum
  val queueMin = new scala.collection.mutable.PriorityQueue[Int]()
  queueMin.enqueue(data.map(-_):_*)
  val min = (1 to n).map{ _ =>
    val res = queueMin.dequeue()
    if (res != -1)
      queueMin.enqueue(res + 1)
    res
  }.sum
  println(max + " " + -min)
}

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.collection.mutable.PriorityQueue
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Unit = {
    val N, M = sc.nextInt
    val Planes = List.fill(M)(sc.nextInt)

    @tailrec
    def loop(acc: Int, n : Int, planes: PriorityQueue[Int]): Int = {
      if (n == 0) acc
      else {
        val x = planes.dequeue
        val y = x - 1
        if (y > 0) {
          planes.enqueue(x - 1)
        }
        loop(acc + x, n - 1, planes)
      }
    }

    val pqMax = new PriorityQueue[Int]() ++ Planes
    val max = loop(0, N, pqMax)
    val pqMin = new PriorityQueue[Int]()(Ordering.Int.reverse) ++ Planes
    val min = loop(0, N, pqMin)

    out.println(max + " " + min)
 }

  solve
  out.close
}

import scala.collection.mutable

/**
 * @author pvasilyev
 * @since 25 Jun 2016
 */
object B218 extends App {

  def solve() = {
    val Array(n, m): Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val minPQ: mutable.PriorityQueue[Int] = mutable.PriorityQueue.empty(Ordering.fromLessThan[Int](_ > _))
    val maxPQ: mutable.PriorityQueue[Int] = mutable.PriorityQueue.empty(Ordering.fromLessThan[Int](_ < _))
    a.foreach(minPQ += _)
    a.foreach(maxPQ += _)

    var min = 0
    var max = 0

    for (i <- 0 until n) {
      val mi = minPQ.dequeue()
      min += mi
      if (mi - 1 > 0) {
        minPQ += (mi - 1)
      }

      val ma = maxPQ.dequeue()
      max += ma
      if (ma - 1 > 0) {
        maxPQ += (ma - 1)
      }
    }
    println(max + " " + min)
  }

  solve()

}

import collection.mutable._

object A extends App {
  val max = new PriorityQueue[Int]
  val min = new PriorityQueue[Int]()(new Ordering[Int] {
    def compare(x: Int, y: Int) = y.compare(x)
  })

  val Array(n, m) = readLine split ' ' map (_.toInt)
  val a = readLine split ' ' map (_.toInt)
  max.enqueue(a: _*)
  min.enqueue(a: _*)

  var ans0, ans1 = 0
  for (i <- 0 until n) {
    val x = max.dequeue
    ans0 += x
    if (x > 1) max.enqueue(x-1)
  }
  for (i <- 0 until n) {
    val x = min.dequeue
    ans1 += x
    if (x > 1) min.enqueue(x-1)
  }

  println("%d %d" format (ans0, ans1))
}

import scala.collection.mutable.PriorityQueue
object Main{
  def main(args: Array[String]): Unit = {
    val maxHeap = new PriorityQueue[Int]
    val minHeap = new PriorityQueue[Int]()(new Ordering[Int] {
      def compare(x: Int, y :Int) = y.compare(x)
    })
    var ans = 0
    val temp = readLine.split(' ') map (_.toInt)
    val (n, m) = (temp(0), temp(1))

    val emptySeats = readLine.split(' ') map (_.toInt)
    maxHeap.enqueue(emptySeats:_*)
    minHeap.enqueue(emptySeats:_*)

    for (i <- 0 until n) {
      var x = maxHeap.dequeue
      ans += x
      x -= 1
      if (x > 0) maxHeap.enqueue(x)
    }
    print(ans + " ")

    ans = 0
    for (i <- 0 until n) {
      var x = minHeap.dequeue
      ans += x
      x -= 1
      if (x > 0) minHeap.enqueue(x)
    }
    println(ans)
  }
}

import java.io._
import java.util.Locale
import scala.annotation.tailrec
import scala.collection.mutable

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)
  def readLine = reader.readLine

  val Array(n, _) = readInts
  val a = readInts
  val pq1 = mutable.PriorityQueue(a: _*)
  val pq2 = mutable.PriorityQueue(a: _*)(Ordering.Int.reverse)
  val pq = Array(pq1, pq2)
  def ans = pq.map { q =>
    (for(_ <- 1 to n) yield {
      val x = q.dequeue()
      if(x > 1)
        q.enqueue(x - 1)
      x
    }).sum
  }.mkString(" ")

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def min(n: Int, a: TraversableOnce[Int]) = {
    var ax = scala.collection.mutable.Seq[Int]() ++ a
    (1 to n).foldLeft(0) { (sum, _) =>
      val e = ax.head
      ax(0) -= 1
      if(ax(0) == 0) ax = ax.drop(1)
      sum + e
    }
  }

  def max(n: Int, a: TraversableOnce[Int]) = {
    var ax = scala.collection.mutable.Seq[Int]() ++ a
    (1 to n).foldLeft(0) { (sum, _) =>
      val e = ax.last
      ax(ax.size - 1) -= 1
      ax = ax.sorted
      sum + e
    }
  }

  def main(args: Array[String]) = {
    val nk = readLine() split(" ") map(_.toInt)
    val a = readLine() split(" ") map(_.toInt) sorted
    val mi = min(nk(0), a)
    val ma = max(nk(0), a)
    println(ma + " " + mi)
  }
}

import scala.collection.mutable.PriorityQueue
import java.util.Scanner
object Main {
  def main(args: Array[String]): Unit = {
    val queueDesc = new PriorityQueue[Int]()(Ordering[Int].reverse)
    val queueAsc = new PriorityQueue[Int]()
    val scanner = new Scanner(System.in)
    val n = scanner.nextInt()
    val m = scanner.nextInt()
    for (i <- 1 to m) {
      val a = scanner.nextInt()
      queueAsc.enqueue(a)
      queueDesc.enqueue(a)
    }
    var maximum = 0
    var minimum = 0
    for (i <- 1 to n) {
      val priceMax = queueAsc.dequeue()
      maximum += priceMax
      if (priceMax > 1)
        queueAsc.enqueue(priceMax - 1)
      val priceMin = queueDesc.dequeue()
      minimum += priceMin
      if (priceMin  > 1)
        queueDesc.enqueue(priceMin -  1)
    }
    println(maximum.toString() + " " + minimum.toString())
  }
}


Roma works in a company that sells TVs. Now he has to prepare a report for the last year.Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of several numbers in the sequence. He can also change the sign of a number one, two or more times.The operation of changing a number's sign is the operation of multiplying this number by -1.Help Roma perform the changes so as to make the total income of the company (the sum of numbers in the resulting sequence) maximum. Note that Roma should perform exactly k changes.

The first line contains two integers n and k (1 ≤ n, k ≤ 105), showing, how many numbers are in the sequence and how many swaps are to be made. The second line contains a non-decreasing sequence, consisting of n integers ai (|ai| ≤ 104). The numbers in the lines are separated by single spaces. Please note that the given sequence is sorted in non-decreasing order.

In the single line print the answer to the problem — the maximum total income that we can obtain after exactly k changes.

NoteIn the first sample we can get sequence [1, 1, 1], thus the total income equals 3.In the second test, the optimal strategy is to get sequence [-1, 1, 1], thus the total income equals 1.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt)
  val (sum, l) = data.foldLeft((0l, k)) {
    case ((s, 0), el) => (s + el, 0)
    case ((s, left), el) if el <= 0 => (s - el, left - 1)
    case ((s, left), el) => (s + el, left)
  }
  if (l % 2 == 0)
    println(sum)
  else
    println(sum - 2 * data.map(Math.abs).min)
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0)
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    val add = if (rest == 1) 2 * a.map(_.abs).min else 0
    println(poss.sum - negs.take(k).sum  + negs.drop(k).sum - add)
  }
}

object B{
  def main(args: Array[String]){

    val (n,k)={
      val sp= readLine.split(" ")
      (sp(0).toInt,sp(1).toInt)
    }
    var a= readLine.split(" ").toList.map(_.toInt)

    val negalen=a.prefixLength(_<=0)
    if(negalen>=k){
      //先頭k個
      val (a1,a2)=a.splitAt(k)
      println(-(a1.sum)+a2.sum)
    }else{
      a=a.map(Math.abs(_))
      if((k-negalen)%2==0){
        //all +
        println(a.sum)
      }else{
        //min -> -min
        println(a.sum - 2* a.min)
      }
    }
  }
}

object Roma extends App {
  def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var result = seq.map {e =>
  		if (e < 0 && remainingSwaps > 0) {
  			remainingSwaps -= 1
  			-e
  		} else e
  	}

  	result = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0) {
  			result
  		} else {
  			val sorted = result.sorted
  			 (-sorted.head) :: sorted.tail
  		}
  	} else {
  		result
  	}

  	result.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object CF262B extends App {

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

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i + 1
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      if (j == 0) {
        a(j) *= -1
      } else if (j == n || a(j - 1) < a(j)) {
        a(j - 1) *= -1
      } else {
        a(j) *= -1
      }
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object Roma {

  def main(args: Array[String]): Unit = {
    val Array(n: Int, k: Int) = readLine.split(' ').map(_.toInt)
    val aa: Seq[Int] = readLine.split(' ').map(_.toInt)

    val negCount = aa.count(_ < 0)
    val result = if (k > negCount) {
      if ((k - negCount) % 2 == 0) {
        aa.map(_.abs).sum
      }
      else {
        aa.map(_.abs).sum - 2*aa.map(_.abs).min
      }
    }
    else {
      val origSeq: Map[Int, Int] = aa.zipWithIndex.map(_.swap).toMap
      val negFlipped: Map[Int, Int] = aa.zipWithIndex
        .filter{ case (a: Int, i: Int) => a < 0 }
        .sortBy { case (a: Int, i: Int) => a }
        .take(k)
        .map { case (a: Int, i: Int) => (-1*a, i) }
        .map(_.swap)
        .toMap
      (origSeq ++ negFlipped).values.sum
    }

    println(result)
  }

}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0).reverse
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    val add = 2 * a.map(_.abs).min * rest
    println(poss.sum - negs.take(k).sum  + negs.drop(k).sum - add)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0)
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    println(poss.sum - negs.reverse.take(k).sum - (poss.min.min(-negs.max)) * rest)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    val negs = a.filter(_ < 0).reverse
    val poss = a.filter(_ >= 0)

    val rest = (k - negs.size).max(0) % 2
    val add = - 2 * a.map(_.abs).min * rest
    println(poss.sum - negs.take(k).sum  + negs.drop(k).sum - add)
  }
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = (seq.take(nSwaps).map(_ * -1) ::: seq.drop(nSwaps)).sum

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = (seq.take(nSwaps).map(math.abs) ::: seq.drop(nSwaps)).sum

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
  def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var response = seq.map { e =>
  		if (e < 0) {
  			remainingSwaps -= 1
  			e * -1
  		} else 	e
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
  def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var response = seq.map { e =>
  		if (e < 0) e * -1
  		else {
  			remainingSwaps = remainingSwaps - 1
  			e
  		}
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	println("Remaining swaps = " + remainingSwaps)

  	var response = seq.map { e =>
  		if (e < 0 && remainingSwaps > 0) {
  			println("It is negative: " + e)
  			remainingSwaps -= 1
  		println("Remaining swaps = " + remainingSwaps)
  			e * -1

  		} else 	e
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object Roma extends App {
def maximize(seq: List[Int], nSwaps: Int) = {
  	var remainingSwaps = nSwaps

  	var response = seq.map { e =>
  		if (e < 0 && remainingSwaps > 0) {
  			remainingSwaps -= 1
  			e * -1

  		} else 	e
  	}

  	response = if (remainingSwaps > 0) {
  		if (remainingSwaps % 2 == 0)
  			response
  		else
  			(- response.head) :: response.tail
  	} else {
  		response
  	}

  	response.sum
  }

  val lines = io.Source.stdin.getLines().toList
  val params = lines.head.split(" ")
  val swaps = params(1).toInt
  val seq = lines.last.split(" ").toList.map(_.toInt)

  println(maximize(lines.last.split(" ").toList.map(_.toInt), swaps))
}

object CF262B extends App {

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

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    if (math.abs(a(0)) > math.abs(a(n - 1))) {
      a = a.reverse
    }

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i
      }
      i += 1
    }

    if ((k - kk) % 2 != 0) {
      j = if (j != 0 && j + 1 < n) j + 1 else j
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

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

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    if (math.abs(a(0)) > math.abs(a(n - 1))) {
      a = a.reverse
    }

    var kk = 0
    var i = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
      }
      i += 1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

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

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      j = if (j != 0 && j + 1 < n) j + 1 else j
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

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

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    if (math.abs(a(0)) > math.abs(a(n - 1))) {
      a = a.reverse
    }

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      j = if (j != 0 && j + 1 < n) j + 1 else j
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

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

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i + 1
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      if (j == 0) {
        a(j) *= -1
      } else if (j == n || a(j - 1) < a(j)) {
        a(j - 1) *= 1
      } else {
        a(j) *= 1
      }
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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

object CF262B extends App {

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

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

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

  def solve = {
    var n = nextInt
    var k = nextInt

    var a = (for (i <- 0 until n) yield nextInt).toArray

    var kk = 0
    var i = 0
    var j = 0
    while (kk < k && i < n) {
      if (a(i) < 0) {
        a(i) *= -1
        kk += 1
        j = i + 1
      }
      i += 1
    }

    if (kk < k && (k - kk) % 2 != 0) {
      j = if (j == 0) j else if (j < n) j else j - 1
      a(j) *= -1
    }

    out.println(a.reduceLeft[Int](_+_))
  }

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


Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m.About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On each day Vasiliy can either pass the exam of that day (it takes the whole day) or prepare all day for some exam or have a rest. About each subject Vasiliy know a number ai — the number of days he should prepare to pass the exam number i. Vasiliy can switch subjects while preparing for exams, it is not necessary to prepare continuously during ai days for the exam number i. He can mix the order of preparation for exams in any way.Your task is to determine the minimum number of days in which Vasiliy can pass all exams, or determine that it is impossible. Each exam should be passed exactly one time.

The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of days in the exam period and the number of subjects.  The second line contains n integers d1, d2, ..., dn (0 ≤ di ≤ m), where di is the number of subject, the exam of which can be passed on the day number i. If di equals 0, it is not allowed to pass any exams on the day number i.  The third line contains m positive integers a1, a2, ..., am (1 ≤ ai ≤ 105), where ai is the number of days that are needed to prepare before passing the exam on the subject i.

Print one integer — the minimum number of days in which Vasiliy can pass all exams. If it is impossible, print -1.

NoteIn the first example Vasiliy can behave as follows. On the first and the second day he can prepare for the exam number 1 and pass it on the fifth day, prepare for the exam number 2 on the third day and pass it on the fourth day.In the second example Vasiliy should prepare for the exam number 3 during the first four days and pass it on the fifth day. Then on the sixth day he should prepare for the exam number 2 and then pass it on the seventh day. After that he needs to prepare for the exam number 1 on the eighth day and pass it on the ninth day. In the third example Vasiliy can't pass the only exam because he hasn't anough time to prepare for it.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val time = in.next().split(' ').map(_.toInt)

  def hasSolution(endIndex: Int): Boolean = {
    val cache = Array.ofDim[Boolean](m)
    var mr = 0
    val t = (endIndex to 0 by -1).foldLeft(0) {
      case (overuse, i) if line(i) == 0 || cache(line(i) - 1) => Math.max(overuse - 1, 0)
      case (overuse, i) =>
        cache(line(i) - 1) = true
        mr += 1
        overuse + time(line(i) - 1)
    }
    t <= 0 && m == mr
  }

  def binary(start: Int, end: Int): Option[Int] = {
    if (start >= end) {
      None
    }
    else if (end - start == 1)
      Some(end)
    else {
      val middle = start + Math.max(1, (end - start) / 2)
      if (hasSolution(middle))
        binary(start, middle)
      else
        binary(middle, end)
    }
  }

  if (!hasSolution(n - 1))
    println(-1)
  else {
    println(binary(0, n - 1).get + 1)
  }

}

import java.io._

import scala.io.Source
import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

  def processFromSource(src: Source): Unit = {
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  // Declare type aliases for readability (but not type-safety)...
  type SubjectId = Int;
  type PrepTime = Int;
  type DayIndex = Int;

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line1 = lines.next()
    val strings = line1.split(" ")
    val n = strings(0).toInt
    val m = strings(1).toInt

    val line2 = lines.next()
    val d = line2.split(" ")
      .map(_.toInt)
      .map(di => if (di == 0) None else Some(di - 1))  // zero-base the d's

    val line3 = lines.next()
    val a = line3.split(" ").map(pt => pt.toInt)

    val soln = solve(n, m, d, a)
    soln match {
      case Some(days) => bw.write((days + 1).toString)  // Make d's one-based again
      case _ => bw.write("-1")
    }
    bw.newLine()
  }

  def solve(numDays: Int, numSubjects: Int, examByDay: Array[Option[SubjectId]], prepTimes: Array[PrepTime])
    : Option[DayIndex] = {

    // Get a sorted array of exam days for each subject:
    val maxPrepTimeOfAnyExam = prepTimes.max
    val examDaysBySubject = Array.fill(numSubjects)(ListBuffer[DayIndex]())
    for (dayIndex <- 0 until numDays) {
      val subjectOpt = examByDay(dayIndex)
      if (subjectOpt.isDefined) {
        val subjectId = subjectOpt.get
        if (dayIndex >= maxPrepTimeOfAnyExam || prepTimes(subjectId) <= dayIndex) {
          examDaysBySubject(subjectId).append(dayIndex)
        }
      }
    }

    def findDayIndexOfLastExamForSubjectOnOrBefore(subjectId: SubjectId, dayIndex: DayIndex): Option[Int] = {
      val examDays = examDaysBySubject(subjectId)

      @tailrec
      def binarySearch(lowerIx: Int, upperIx: Int): Int = {
        if (lowerIx == upperIx) lowerIx else {
          val midIx = (lowerIx + upperIx + 1) / 2
          val midVal = examDays(midIx)
          if ((midIx == upperIx) || (midVal == dayIndex))
            midVal
          else if (midVal > dayIndex) binarySearch(lowerIx, midIx)
          else binarySearch(midIx, upperIx)
        }
      }

      if (examDays.isEmpty) None else {
        val lowerVal = examDays(0)
        if (lowerVal > dayIndex) None else {
          val upperIndex = examDays.length - 1
          val upperVal = examDays(upperIndex)
          if (upperVal <= dayIndex) Some(upperVal)
          else Some(binarySearch(0, upperIndex))
        }
      }
    }

    def isSolution(dayIndex: DayIndex): Boolean = {
      val subjectExamDays = (0 until numSubjects).map { subjectId =>
        subjectId -> findDayIndexOfLastExamForSubjectOnOrBefore(subjectId, dayIndex)
      }
      if (!subjectExamDays.forall(_._2.isDefined)) false else {
        val sortedSubjectExamDays = subjectExamDays.map(pair => (pair._1, pair._2.get)).sortBy(_._2)

        def loop(sortIndex: Int, prevDayIndex: Int): Boolean = {
          val sed = sortedSubjectExamDays(sortIndex)
          val nextDayIndex = prevDayIndex + prepTimes(sed._1) + 1
          if (nextDayIndex > sed._2) false else {
            val nextSortIndex = sortIndex + 1
            if (nextSortIndex == numSubjects) true else loop(nextSortIndex, nextDayIndex)
          }
        }

        loop(0, -1)
      }
    }

    // Do a binary search to find the best solution
    @tailrec
    def search(lowerBound: DayIndex, upperBound: DayIndex): DayIndex = {
      if (lowerBound == upperBound) lowerBound else {
        val middleDay: DayIndex = (lowerBound + upperBound + 1) / 2
        if (isSolution(middleDay)) search(lowerBound, middleDay)
        else if (middleDay == upperBound) upperBound
        else search(middleDay, upperBound)
      }
    }

    if (examDaysBySubject.exists(_.length == 0)) None else {
      val ub: DayIndex = numDays - 1
      if (!isSolution(ub)) None
      else {
        val lowerBoundByTotalPrepAndExamTime = prepTimes.sum + numSubjects - 1
        val lowerBoundByMaxOfFirstExamDays = examDaysBySubject.map(_(0)).max
        val lowerBoundIndex = lowerBoundByMaxOfFirstExamDays max lowerBoundByTotalPrepAndExamTime
        val lb: DayIndex = lowerBoundIndex
        if (isSolution(lb)) Some(lb) else {
          if (lowerBoundIndex >= numDays) None
          else if (lowerBoundIndex == numDays - 1) Some(lb)
          else Some(search(lb, ub))
        }
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  val time = in.next().split(' ').map(_.toInt)

  def hasSolution(endIndex: Int): Boolean = {
    val cache = Array.ofDim[Boolean](m)
    val t = (endIndex to 0 by -1).foldLeft(0) {
      case (overuse, i) if line(i) == 0 || cache(line(i) - 1) => Math.max(overuse - 1, 0)
      case (overuse, i) =>
        cache(line(i) - 1) = true
        overuse + time(line(i) - 1)

    }
    t <= 0
  }

  def binary(start: Int, end: Int): Option[Int] = {
    if (end - start == 1)
      Some(end)
    else if (start >= end) {
      None
    }
    else {
      val middle = start + Math.max(1, (end - start) / 2)
      if (hasSolution(middle))
        binary(start, middle)
      else
        binary(middle, end)
    }
  }

  if (!hasSolution(n - 1))
    println(-1)
  else {
    println(binary(0, n - 1).get + 1)
  }

}


Highway 201 is the most busy street in Rockport. Traffic cars cause a lot of hindrances to races, especially when there are a lot of them. The track which passes through this highway can be divided into $$$n$$$ sub-tracks. You are given an array $$$a$$$ where $$$a_i$$$ represents the number of traffic cars in the $$$i$$$-th sub-track. You define the inconvenience of the track as $$$\sum\limits_{i=1}^{n} \sum\limits_{j=i+1}^{n} \lvert a_i-a_j\rvert$$$, where $$$|x|$$$ is the absolute value of $$$x$$$. You can perform the following operation any (possibly zero) number of times: choose a traffic car and move it from its current sub-track to any other sub-track.Find the minimum inconvenience you can achieve.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 10\,000$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1\leq n\leq 2\cdot 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0\leq a_i\leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.

For each test case, print a single line containing a single integer: the minimum inconvenience you can achieve by applying the given operation any (possibly zero) number of times.

NoteFor the first test case, you can move a car from the $$$3$$$-rd sub-track to the $$$1$$$-st sub-track to obtain $$$0$$$ inconvenience.For the second test case, moving any car won't decrease the inconvenience of the track.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val c = an.foldLeft(0L)(_ + _) % n

    val ans = c * (n - c)

    println(ans)
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val sum    = an.foldLeft(0L)(_ + _)
    val (c, r) = (sum / n, sum % n)

    val ans = r * (n - r)

    println(ans)
  }
}


The Little Girl loves problems on games very much. Here's one of them.Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:  The players move in turns; In one move the player can remove an arbitrary letter from string s.  If the player before his turn can reorder the letters in string s so as to get a palindrome, this player wins. A palindrome is a string that reads the same both ways (from left to right, and vice versa). For example, string "abba" is a palindrome and string "abc" isn't. Determine which player will win, provided that both sides play optimally well — the one who moves first or the one who moves second.

The input contains a single line, containing string s (1 ≤ |s|  ≤  103). String s consists of lowercase English letters.

In a single line print word "First" if the first player wins (provided that both players play optimally well). Otherwise, print word "Second". Print the words without the quotes.

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P276B extends App {
  def solve(s: String): Boolean = {
    val x = s.toCharArray.groupBy(identity[Char]).map(_._2.length % 2).filter(_ == 1).size
    (x < 2) || (x % 2 == 1)
  }

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

object B {
  def main(args: Array[String]) {
    var s = readLine()
    var r=List.range('a', 'z'+1) map(x => s count(x==)) filter (_%2==1) size;
    println(if (r == 0 || r%2==1) "First" else "Second")
  }
}

object Main {
  def main(args: Array[String]) = {
    val a = readLine()
    val map = scala.collection.mutable.Map[Char, Int]()
    a.foreach(c => map(c) = map.getOrElse(c, 0) + 1)
    val count = map.values.count(_ % 2 == 1)
    if (count == 0 || count % 2 == 1) println("First")
    else println("Second")
  }
}

object B {
	def main(args: Array[String]) {
		val rawS = Console.readLine

		val sum = rawS.toSeq.sorted.groupBy(c => c).mapValues(_.length % 2).values.sum

		println(if(sum == 0) "First" else if(sum % 2 == 0) "Second" else "First")
	}
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.next().map(_ - 'a').foldLeft(0) {
    case(a, el) => a ^ (1 << el)
  }.toBinaryString.count(_ == '1')
  if (res < 2 || res % 2 == 1)
    println("First")
  else
    println("Second")
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P276B extends App {
  def solve(s: String): Boolean = false

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")

  out.flush
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P276B extends App {
  def solve(s: String): Boolean = false

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray
      .groupBy(identity[Char])
      .map(_._2.length)
      .filter(_ % 2 == 0)
      .size % 2 == 1

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray
      .groupBy(identity[Char])
      .map(_._2.length % 2)
      .filter(_ == 1)
      .size % 2 == 0

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray.groupBy(identity[Char]).size % 2 == 0

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}

object Main {
  def main(args: Array[String]) = {
    val a = readLine()
    val map = scala.collection.mutable.Map[Char, Int]()
    a.foreach(c => map(c) = map.getOrElse(c, 0) + 1)
    if (map.values.count(_ % 2 == 1) % 2 == 1) println("First")
    else println("Second")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val res = in.next().map(_ - 'a').foldLeft(0) {
    case(a, el) => a ^ (1 << el)
  }.toBinaryString.count(_ == '1') % 2 == 0
  if (!res)
    println("First")
  else
    println("Second")
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

object P276B extends App {
  def solve(s: String): Boolean =
    s.toCharArray
      .groupBy(identity[Char])
      .map(_._2.length % 2)
      .filter(_ == 1)
      .size % 2 == 1

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

  out.println(if (solve(sc.nextLine)) "First"
              else "Second")
  out.close
}


Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)

The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.

In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.

object D extends App {

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

  val n = readInt

  val as = readInts(n)
  val bs = readInts(n)
  val cs = readInts(n)

  var happy = (as(0), if (n > 1) bs(0) else 0) // (feed current before next, feed current after next)

  for (i <- 1 until n - 1) happy = happy match {
    case (before, after) => (
      (after + as(i)) max (before + bs(i)),
      (after + bs(i)) max (before + cs(i)))
  }

  if (n > 1) happy = (happy._1 + bs.last, happy._2 + as.last)

  println(happy._1 max happy._2)
}

object D extends App {

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

  val n = readInt

  val as = readInts(n)
  val bs = readInts(n)
  val cs = readInts(n)

  var happy = (as(0), bs(0)) // (feed current before next, feed current after next)

  for (i <- 1 until n - 1) happy = happy match {
    case (before, after) => (
      (after + as(i)) max (before + bs(i)),
      (after + bs(i)) max (before + cs(i)))
  }

  if (n > 1) happy = (happy._1 + bs.last, happy._2 + as.last)

  println(happy._1 max happy._2)
}

object D extends App {

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

  val n = readInt

  val as = readInts(n)
  val bs = readInts(n)
  val cs = readInts(n)

  var happy = (as(0), bs(0)) // (feed current before next, feed current after next)

  for (i <- 1 until n) happy = happy match {
    case (before, after) => (
      (after + as(i)) max (before + bs(i)),
      (after + bs(i)) max (before + cs(i)))
  }

  println(happy._1 max happy._2)
}

object D extends App {

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

  val n = readInt

  val as = readInts(n)
  val bs = readInts(n)
  val cs = readInts(n)

  var happy = (as(0), bs(0)) // (feed current before next, feed current after next)

  for (i <- 1 until n - 1) happy = happy match {
    case (before, after) => (
      (after + as(i)) max (before + bs(i)),
      (after + bs(i)) max (before + cs(i)))
  }

  happy = (happy._1 + bs.last, happy._2 + as.last)

  println(happy._1 max happy._2)
}


There is an infinite 2-dimensional grid. The robot stands in cell $$$(0, 0)$$$ and wants to reach cell $$$(x, y)$$$. Here is a list of possible commands the robot can execute:  move north from cell $$$(i, j)$$$ to $$$(i, j + 1)$$$;  move east from cell $$$(i, j)$$$ to $$$(i + 1, j)$$$;  move south from cell $$$(i, j)$$$ to $$$(i, j - 1)$$$;  move west from cell $$$(i, j)$$$ to $$$(i - 1, j)$$$;  stay in cell $$$(i, j)$$$. The robot wants to reach cell $$$(x, y)$$$ in as few commands as possible. However, he can't execute the same command two or more times in a row.What is the minimum number of commands required to reach $$$(x, y)$$$ from $$$(0, 0)$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$0 \le x, y \le 10^4$$$) — the destination coordinates of the robot.

For each testcase print a single integer — the minimum number of commands required for the robot to reach $$$(x, y)$$$ from $$$(0, 0)$$$ if no command is allowed to be executed two or more times in a row.

NoteThe explanations for the example test:We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.In the first test case, the robot can use the following sequence: NENENENENE.In the second test case, the robot can use the following sequence: NENENEN.In the third test case, the robot can use the following sequence: ESENENE0ENESE.In the fourth test case, the robot doesn't need to go anywhere at all.In the fifth test case, the robot can use the following sequence: E0E.

//package bScalaAdvanced.exercises.codeForces.edu98

import scala.io.StdIn._

object taskA extends App {
  val sets = readInt
  var res = new Array[Int](sets)

  var loc = new Array[(Int, Int)](sets)
  (0 until sets).foreach(x => {
    val single = readLine.split(" ").map(_.toInt)
    loc(x) = (single(0), single(1))
  })

  (0 until sets).foreach(x => {
    if(Math.abs(loc(x)._1 - loc(x)._2) > 1) {
      if(loc(x)._1 > loc(x)._2){
        res(x) = loc(x)._2*2+1 + ((loc(x)._1 - loc(x)._2)-1)*2
      }else{
        res(x) = loc(x)._1*2+1 + ((loc(x)._2 - loc(x)._1)-1)*2
      }
    }else res(x) = loc(x)._1 + loc(x)._2
  })

  (0 until sets).foreach(x => {
    println(res(x))

  })

}


You are given an integer $$$n$$$. You have to apply $$$m$$$ operations to it.In a single operation, you must replace every digit $$$d$$$ of the number with the decimal representation of integer $$$d + 1$$$. For example, $$$1912$$$ becomes $$$21023$$$ after applying the operation once.You have to find the length of $$$n$$$ after applying $$$m$$$ operations. Since the answer can be very large, print it modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^5$$$) — the number of test cases. The only line of each test case contains two integers $$$n$$$ ($$$1 \le n \le 10^9$$$) and $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the initial number and the number of operations.

For each test case output the length of the resulting number modulo $$$10^9+7$$$.

NoteFor the first test, $$$1912$$$ becomes $$$21023$$$ after $$$1$$$ operation which is of length $$$5$$$.For the second test, $$$5$$$ becomes $$$21$$$ after $$$6$$$ operations which is of length $$$2$$$.For the third test, $$$999$$$ becomes $$$101010$$$ after $$$1$$$ operation which is of length $$$6$$$.For the fourth test, $$$88$$$ becomes $$$1010$$$ after $$$2$$$ operations which is of length $$$4$$$.

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import scala.language.postfixOps

object CAddOne {
  def main(args: Array[String]): Unit = {
//    val start = currentTimeMillis
    val file = new BufferedReader(new InputStreamReader(System.in))
//                    val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//        "5\n1912 1\n5 6\n999 1\n88 2\n12 100".getBytes)))
//        "1\n12 100".getBytes)))
    val out: PrintWriter = new PrintWriter(System.out)
    val modulo = 1000000007

    val cache = Array.ofDim[Long](200011)
    for (i <- 0 to 9) cache(i) = 1
    for (i <- 10 to 200010) cache(i) = (cache(i-9) + cache(i-10)) % modulo

    val t = file.readLine.toInt
    var i = 0
    while (i < t) {
      val a = file.readLine.split(" ")
      val ab = a.head.toInt
      val b = a(1).toInt
      var ints = ab
      var sum = 0L
      while (ints > 0) {
        val i = ints % 10
        sum = (sum + cache(b + i)) % modulo
        ints /= 10
      }
      out.println(sum)
      i += 1
    }
//    println(currentTimeMillis - start)
    out.close()
  }
}

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import scala.language.postfixOps

object CAddOne {
  def main(args: Array[String]): Unit = {
//    val start = currentTimeMillis
    val file = new BufferedReader(new InputStreamReader(System.in))
//                    val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//        "5\n1912 1\n5 6\n999 1\n88 2\n12 100".getBytes)))
//        "1\n12 100".getBytes)))
    val out: PrintWriter = new PrintWriter(System.out)
    val modulo = 1000000007

    val cache = Array.ofDim[Long](200011)
    for (i <- 0 to 9) cache(i) = 1
    for (i <- 10 to 200010) cache(i) = (cache(i-9) + cache(i-10)) % modulo

    val t = file.readLine.toInt
    var i = 0
    while (i < t) {
      val a = file.readLine.split(" ").map(_.toInt)
      val ab = a.head
      val b = a(1)
      var ints = ab
      var sum = 0L
      while (ints > 0) {
        val i = ints % 10
        sum = (sum + cache(b + i)) % modulo
        ints /= 10
      }
      out.println(sum)
      i += 1
    }
//    println(currentTimeMillis - start)
    out.close()
  }
}

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import java.io.PrintWriter
import scala.language.postfixOps

object CAddOne {
  def main(args: Array[String]): Unit = {
//    val start = currentTimeMillis
    val file = new BufferedReader(new InputStreamReader(System.in))
//                    val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//        "5\n1912 1\n5 6\n999 1\n88 2\n12 100".getBytes)))
//        "1\n12 100".getBytes)))
    val out: PrintWriter = new PrintWriter(System.out)
    val modulo: Long = 1000000007

    val cache = Array.ofDim[Long](200011)
    for (i <- 0 to 9) cache(i) = 1
    for (i <- 10 to 200010) cache(i) = (cache(i-9) + cache(i-10)) % modulo

    val t = file.readLine.toInt
    var i = 0
    while (i < t) {
      val a = file.readLine.split(" ").map(_.toLong)
      val ab = a.head
      val b = a(1).toInt
      var ints = ab
      var sum = 0L
      while (ints > 0) {
        val i = (ints % 10).toInt
        sum = (sum + cache(b + i)) % modulo
        ints /= 10
      }
      out.println(sum)
      i += 1
    }
//    println(currentTimeMillis - start)
    out.close()
  }
}

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import java.lang.System.currentTimeMillis
import scala.language.postfixOps

object CAddOne {
  val modulo: Long = (Math.pow(10,9)+7).toLong

  val cache = Array.ofDim[Long](200005)
  def computeLength(x: Int, m: Long): Long = {
    if (m + x - 10 >= 0 && cache(m.toInt + x - 10) != 0) return cache(m.toInt + x - 10)
    var r: Long = 1
    if (m + x - 10 >= 0) {
      r += computeLength(1, m + x - 10) + computeLength(0, m + x - 10) - 1 % modulo
      cache(m.toInt + x - 10) = r
    }
//    println(s"$x,$m: $r")
    r
  }

  def solve(ab: Long, b: Long): Long = {
    val a = Array.ofDim[Long](10)
    val ints = ab.toString.map(_.toString.toInt)
    var sum = 0L
    for (i <- ints) {
      if (a(i) == 0) {
        val n = computeLength(i, b) % modulo
        a(i) = n
      }
      sum = (sum  + a(i) % modulo)
//      println("sum:"+sum)
    }
//    println(cache)
    sum
  }

  def main(args: Array[String]): Unit = {
    val start = currentTimeMillis
    val file = new BufferedReader(new InputStreamReader(System.in))
//                    val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//        "5\n1912 1\n5 6\n999 1\n88 2\n12 100".getBytes)))
//        "1\n12 100".getBytes)))
    val t = file.readLine.toInt
    var i = 0
    while (i < t) {
      val a :: b :: Nil = file.readLine.split(" ").map(_.toLong).toList
      println(solve(a, b))
      i += 1
    }
    println(currentTimeMillis - start)
  }
}