You are given a string $$$s$$$, consisting only of Latin letters 'a', and a string $$$t$$$, consisting of lowercase Latin letters.In one move, you can replace any letter 'a' in the string $$$s$$$ with a string $$$t$$$. Note that after the replacement string $$$s$$$ might contain letters other than 'a'.You can perform an arbitrary number of moves (including zero). How many different strings can you obtain? Print the number, or report that it is infinitely large.Two strings are considered different if they have different length, or they differ at some index.

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of testcases. The first line of each testcase contains a non-empty string $$$s$$$, consisting only of Latin letters 'a'. The length of $$$s$$$ doesn't exceed $$$50$$$. The second line contains a non-empty string $$$t$$$, consisting of lowercase Latin letters. The length of $$$t$$$ doesn't exceed $$$50$$$.

For each testcase, print the number of different strings $$$s$$$ that can be obtained after an arbitrary amount of moves (including zero). If the number is infinitely large, print -1. Otherwise, print the number.

NoteIn the first example, you can replace any letter 'a' with the string "a", but that won't change the string. So no matter how many moves you make, you can't obtain a string other than the initial one.In the second example, you can replace the second letter 'a' with "abc". String $$$s$$$ becomes equal to "aabc". Then the second letter 'a' again. String $$$s$$$ becomes equal to "aabcbc". And so on, generating infinitely many different strings.In the third example, you can either leave string $$$s$$$ as is, performing zero moves, or replace the only 'a' with "b". String $$$s$$$ becomes equal to "b", so you can't perform more moves on it.

 import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // ======================================
  def solve(x: String, y: String) = {
    if (y.length == 1 && y.head == 'a') 1
    else if (y.contains('a')) -1
    else Math.pow(2, x.filter(_ == 'a').length).toLong
  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt

    for (
      i <- 0 until cases;
      s = readLine();
      t = readLine()
    ) println(solve(s, t))
  }
}

 import scala.io.StdIn.readLine

object Solution {

  def rsi() = readLine().split("\\s+").map(_.toInt)
  // ======================================
  def solve(x: String, y: String) = {
    if (y.forall(_ == 'a')) {
      if (y.length == 1) 1
      else -1
    }
    else if (y.contains('a')) -1
    else 1 + x.filter(_ == 'a').length * y.length
  }

  def main(args: Array[String]): Unit = {
    val cases = readLine.toInt

    for (
      i <- 0 until cases;
      s = readLine();
      t = readLine()
    ) println(solve(s, t))
  }
}


Vova's house is an array consisting of $$$n$$$ elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The $$$i$$$-th element of the array is $$$1$$$ if there is a heater in the position $$$i$$$, otherwise the $$$i$$$-th element of the array is $$$0$$$.Each heater has a value $$$r$$$ ($$$r$$$ is the same for all heaters). This value means that the heater at the position $$$pos$$$ can warm up all the elements in range $$$[pos - r + 1; pos + r - 1]$$$.Vova likes to walk through his house while he thinks, and he hates cold positions of his house. Vova wants to switch some of his heaters on in such a way that each element of his house will be warmed up by at least one heater. Vova's target is to warm up the whole house (all the elements of the array), i.e. if $$$n = 6$$$, $$$r = 2$$$ and heaters are at positions $$$2$$$ and $$$5$$$, then Vova can warm up the whole house if he switches all the heaters in the house on (then the first $$$3$$$ elements will be warmed up by the first heater and the last $$$3$$$ elements will be warmed up by the second heater).Initially, all the heaters are off.But from the other hand, Vova didn't like to pay much for the electricity. So he wants to switch the minimum number of heaters on in such a way that each element of his house is warmed up by at least one heater.Your task is to find this number of heaters or say that it is impossible to warm up the whole house.

The first line of the input contains two integers $$$n$$$ and $$$r$$$ ($$$1 \le n, r \le 1000$$$) — the number of elements in the array and the value of heaters. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$) — the Vova's house description.

Print one integer — the minimum number of heaters needed to warm up the whole house or -1 if it is impossible to do it.

NoteIn the first example the heater at the position $$$2$$$ warms up elements $$$[1; 3]$$$, the heater at the position $$$3$$$ warms up elements $$$[2, 4]$$$ and the heater at the position $$$6$$$ warms up elements $$$[5; 6]$$$ so the answer is $$$3$$$.In the second example the heater at the position $$$1$$$ warms up elements $$$[1; 3]$$$ and the heater at the position $$$5$$$ warms up elements $$$[3; 5]$$$ so the answer is $$$2$$$.In the third example there are no heaters so the answer is -1.In the fourth example the heater at the position $$$3$$$ warms up elements $$$[1; 5]$$$, the heater at the position $$$6$$$ warms up elements $$$[4; 8]$$$ and the heater at the position $$$10$$$ warms up elements $$$[8; 10]$$$ so the answer is $$$3$$$.

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, r = ni()
    val P_buf = ArrayBuffer[Int]()
    rep(N) { i =>
      val a = ni()
      if (a == 1) P_buf += i
    }
    val P = P_buf.toArray
    var ans = 0
    var pos = -1
    var heated = -1
    while(heated < N - 1) {
      val x = heated + r
      val ix = upperBound(P, x) - 1
      if (ix == -1 || ix <= pos) {
        out.println(-1)
        return
      }
      heated = P(ix) + r - 1
      ans += 1
      pos = ix
    }

    out.println(ans)
  }

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

    step(-1, a.length)
  }

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

    step(-1, a.length)
  }

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


Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next race. It's guaranteed that given astronaut will have unique number of points before the race.

The first line contains two integer numbers $$$N$$$ ($$$1 \leq N \leq 200000$$$) representing number of F1 astronauts, and current position of astronaut $$$D$$$ ($$$1 \leq D \leq N$$$) you want to calculate best ranking for (no other competitor will have the same number of points before the race). The second line contains $$$N$$$ integer numbers $$$S_k$$$ ($$$0 \leq S_k \leq 10^8$$$, $$$k=1...N$$$), separated by a single space, representing current ranking of astronauts. Points are sorted in non-increasing order. The third line contains $$$N$$$ integer numbers $$$P_k$$$ ($$$0 \leq P_k \leq 10^8$$$, $$$k=1...N$$$), separated by a single space, representing point awards for the next race. Points are sorted in non-increasing order, so winner of the race gets the maximum number of points.

Output contains one integer number — the best possible ranking for astronaut after the race. If multiple astronauts have the same score after the race, they all share the best ranking.

NoteIf the third ranked astronaut wins the race, he will have 35 points. He cannot take the leading position, but he can overtake the second position if the second ranked astronaut finishes the race at the last position.

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, D = ni()
    val S = na(N)
    val P = na(N)
    val p = P.max + S(D - 1)

    def rank(cur: Int, prev: Int): Int = {
      if (cur == 0) 0
      else {
        val next = P.indexWhere(_ <= p - S(cur - 1), prev + 1)
        if (next == - 1) cur // 値が見つからない
        else rank(cur - 1, next)
      }
    }

    out.println(rank(D - 1, 0) + 1)
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, D = ni()
    val S = na(N)
    val P = na(N)
    val t = S(D - 1) + P.max - P.min
    out.println(lowerBound(S, t) + 1)
  }

  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) <= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N, D = ni()
    val S = na(N)
    val P = na(N)
    val p = P.max + S(D - 1)

    def rank(i: Int, prev: Int): Int = {
      if (i == 0) 0
      else {
        val next = lowerBound(P, p - S(i - 1))
        if (prev == next || next == N) i // より小さい値が見つからない
        else rank(i - 1, next)
      }
    }

    out.println(rank(D - 1, N) + 1)
  }

  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) <= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

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


You are given an array $$$a$$$ of $$$n$$$ integers and an integer $$$s$$$. It is guaranteed that $$$n$$$ is odd.In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to $$$s$$$.The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array $$$6, 5, 8$$$ is equal to $$$6$$$, since if we sort this array we will get $$$5, 6, 8$$$, and $$$6$$$ is located on the middle position.

The first line contains two integers $$$n$$$ and $$$s$$$ ($$$1\le n\le 2\cdot 10^5-1$$$, $$$1\le s\le 10^9$$$) — the length of the array and the required value of median. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1\le a_i \le 10^9$$$) — the elements of the array $$$a$$$. It is guaranteed that $$$n$$$ is odd.

In a single line output the minimum number of operations to make the median being equal to $$$s$$$.

NoteIn the first sample, $$$6$$$ can be increased twice. The array will transform to $$$8, 5, 8$$$, which becomes $$$5, 8, 8$$$ after sorting, hence the median is equal to $$$8$$$.In the second sample, $$$19$$$ can be increased once and $$$15$$$ can be increased five times. The array will become equal to $$$21, 20, 12, 11, 20, 20, 12$$$. If we sort this array we get $$$11, 12, 12, 20, 20, 20, 21$$$, this way the median is $$$20$$$.

object 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)
  val sc = new InputReader(System.in)

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

    Sorting.quickSort(A)
    var ans = 0L
    rep_r(N / 2 + 1, N / 2) { i =>
      val a = A(i)
      if (a < M) {
        ans += M - a
      }
    }

    rep_r(N / 2 + 1) { i =>
      val a = A(i)
      if (a > M) {
        ans += a - M
      }
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.StringTokenizer

import scala.io.StdIn

object B extends App with Reader {
  read()
  val n = int()
  val s = int()
  read()
  val a = Array.fill(n)(int()).sorted
  val m = n / 2

  var res = 0L

  for (i <- 0 to m) {
    if (a(i) > s) res += a(i) - s
  }
  for (i <- m until n) {
    if (a(i) < s) res += s - a(i)
  }

  println(res)
}

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

object B1037 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val temp = stdin.readLine.trim.split(" ").map(_.toLong)
    val (n,s) = (temp(0), temp(1))
    val array = stdin.readLine.trim.split(" ").map(_.toLong).sorted
    val p = ((n-1)/2).toInt
    val ans: Long = if (array(p)-s > 0) {
      array.slice(0,p+1).filter(_ > s).map(x => x-s).sum
    } else {
      if (array(p)-s < 0) {
        array.slice(p,n.toInt).filter(_ < s).map(x => s-x).sum
      }  else 0L
    }
    print(ans)
  }
}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val s = in.nextInt
    val a: Array[Int] = Array.fill(n)(in.nextInt)
    util.Sorting.quickSort(a)
    var i = n / 2
    var ans: Long = 0

    if (a(n / 2) < s) {
      while (i < n && a(i) < s) {
        ans += s - a(i)
        i += 1
      }
    } else {
      while (i >= 0 && a(i) > s) {
        ans += a(i) - s
        i -= 1
      }
    }
    println(ans)

  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

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

}

object Main {
  import java.io._
  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)
  val sc = new InputReader(System.in)

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

    Sorting.quickSort(A)
    var ans = 0L
    rep_r(N / 2 + 1, N / 2) { i =>
      val a = A(i)
      if (a < M) {
        ans += M - a
      }
    }

    out.println(ans)
  }

  def main(args: Array[String]): Unit = {
    solve()
    out.flush()
  }

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

  implicit class ArrayOpts[A](val as: Array[A]) extends AnyVal {
    // todo Orderingだとboxing発生するので自作Orderを用意したい
    def maxByOpt[B: Ordering](f: A => B): Option[A] = {
      if (as.nonEmpty) Some(as.maxBy(f)) else None
    }

    def grpBy[K](f: A => K): mutable.Map[K, ArrayBuffer[A]] = {
      val map = mutable.Map.empty[K, ArrayBuffer[A]]
      rep(as.length)(i => map.getOrElseUpdate(f(as(i)), ArrayBuffer()) += as(i))
      map
    }

    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      var sum = num.zero
      rep(as.length)(i => sum = num.plus(sum, f(as(i))))
      sum
    }

    def minByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.lt)
    }

    def maxByEx[B](f: A => B, ixRange: Range = as.indices)(implicit cmp: Ordering[B]): (A, B) = {
      limit(f, ixRange)(cmp.gt)
    }

    private def limit[B](f: A => B, ixRange: Range)(cmp: (B, B) => Boolean): (A, B) = {
      var limA = as(ixRange.head)
      var limB = f(limA)

      for (i <- ixRange.tail) {
        val a = as(i)
        val b = f(a)
        if (cmp(b, limB)) {
          limA = a
          limB = b
        }
      }
      (limA, limB)
    }
  }

  implicit class IterableOpts[A](val as: Iterable[A]) extends AnyVal {
    def sumBy[B](f: A => B)(implicit num: Numeric[B]): B = {
      as.foldLeft(num.zero)((acc, a) => num.plus(acc, f(a)))
    }
  }
}

import java.util.StringTokenizer

import scala.io.StdIn

object B extends App with Reader {
  read()
  val n = int()
  val s = int()
  read()
  val a = Array.fill(n)(int()).sorted
  val m = n / 2

  var res = 0

  for (i <- 0 to m) {
    if (a(i) > s) res += a(i) - s
  }
  for (i <- m until n) {
    if (a(i) < s) res += s - a(i)
  }

  println(res)
}

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

object B1037 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val temp = stdin.readLine.trim.split(" ").map(_.toInt)
    val (n,s) = (temp(0), temp(1))
    val array = stdin.readLine.trim.split(" ").map(_.toInt).sorted
    val p = (n-1)/2
    val ans = if (array(p)-s > 0) {
      array.slice(0,p+1).filter(_ > s).map(x => x-s).sum
    } else if (array(p)-s < 0) {
      array.slice(p,n+1).filter(_ < s).map(x => s-x).sum
    }
    print(ans)
  }
}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val s = in.nextInt
    val a: Array[Int] = Array.fill(n)(in.nextInt)
    util.Sorting.quickSort(a)
    var i = n / 2
    var ans = 0

    if (a(n / 2) < s) {
      while (i < n && a(i) < s) {
        ans += s - a(i)
        i += 1
      }
    } else {
      while (i >= 0 && a(i) > s) {
        ans += a(i) - s
        i -= 1
      }
    }
    println(ans)

  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Double = {
      next.toInt
    }

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

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

}


A telephone number is a sequence of exactly $$$11$$$ digits such that its first digit is 8.Vasya and Petya are playing a game. Initially they have a string $$$s$$$ of length $$$n$$$ ($$$n$$$ is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it from the current string. For example, if the current string 1121, after the player's move it may be 112, 111 or 121. The game ends when the length of string $$$s$$$ becomes 11. If the resulting string is a telephone number, Vasya wins, otherwise Petya wins.You have to determine if Vasya has a winning strategy (that is, if Vasya can win the game no matter which characters Petya chooses during his moves).

The first line contains one integer $$$n$$$ ($$$13 \le n < 10^5$$$, $$$n$$$ is odd) — the length of string $$$s$$$. The second line contains the string $$$s$$$ ($$$|s| = n$$$) consisting only of decimal digits.

If Vasya has a strategy that guarantees him victory, print YES. Otherwise print NO.

NoteIn the first example Vasya needs to erase the second character. Then Petya cannot erase a character from the remaining string 880011223344 so that it does not become a telephone number.In the second example after Vasya's turn Petya can erase one character character 8. The resulting string can't be a telephone number, because there is no digit 8 at all.

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 java.util.Arrays.sort

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

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

  def solve(): Unit = {
    val N = ni()
    val S = ns(N)
    val t = N - 10
    val cnt = S.take(t).count(_ == '8') // 左 t個の中に'8'が(t+1)/2個以上ある
    debug(s"t:$t cnt:$cnt need:${(t + 1) / 2}")
    if (cnt >= (t + 1) / 2) {
      out.println("YES")
    } else {
      out.println("NO")
    }
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

  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 = 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 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]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


You're given an array $$$a$$$ of length $$$2n$$$. Is it possible to reorder it in such way so that the sum of the first $$$n$$$ elements isn't equal to the sum of the last $$$n$$$ elements?

The first line contains an integer $$$n$$$ ($$$1 \le n \le 1000$$$), where $$$2n$$$ is the number of elements in the array $$$a$$$. The second line contains $$$2n$$$ space-separated integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{2n}$$$ ($$$1 \le a_i \le 10^6$$$) — the elements of the array $$$a$$$.

If there's no solution, print "-1" (without quotes). Otherwise, print a single line containing $$$2n$$$ space-separated integers. They must form a reordering of $$$a$$$. You are allowed to not change the order.

NoteIn the first example, the first $$$n$$$ elements have sum $$$2+1+3=6$$$ while the last $$$n$$$ elements have sum $$$1+1+2=4$$$. The sums aren't equal.In the second example, there's no solution.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(2 * N)
    val sum = A.sum
    val half = A.take(N).sum
    if (half * 2 == sum) {
      REP(N) { i =>
        REP(N) { j =>
          if (A(i) != A(N + j)) {
            val t = A(i)
            A(i) = A(N + j)
            A(N + j) = t
            out.println(A.mkString(" "))
            return
          }
        }
      }
      out.println(-1)
    } else {
      out.println(A.mkString(" "))
    }
  }
}

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

  override def apply(io: IO): io.type = {
    val n = io.read[Int]
    val arr = io.read[Seq, Int](2*n)
    val ans = arr.distinct.size match {
      case 1 => "-1"
      case _ => arr.sorted.mkString(" ")
    }
    io.write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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


The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.During the registration, the organizers asked each of the n participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:   the size he wanted, if he specified one size;  any of the two neibouring sizes, if he specified two sizes. If it is possible, the program should find any valid distribution of the t-shirts.

The first line of the input contains six non-negative integers — the number of t-shirts of each size. The numbers are given for the sizes S, M, L, XL, XXL, XXXL, respectively. The total number of t-shirts doesn't exceed 100 000. The second line contains positive integer n (1 ≤ n ≤ 100 000) — the number of participants. The following n lines contain the sizes specified by the participants, one line per participant. The i-th line contains information provided by the i-th participant: single size or two sizes separated by comma (without any spaces). If there are two sizes, the sizes are written in increasing order. It is guaranteed that two sizes separated by comma are neighboring.

If it is not possible to present a t-shirt to each participant, print «NO» (without quotes). Otherwise, print n + 1 lines. In the first line print «YES» (without quotes). In the following n lines print the t-shirt sizes the orginizers should give to participants, one per line. The order of the participants should be the same as in the input. If there are multiple solutions, print any of them.

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    val labels = Array("S","M","L","XL","XXL","XXXL")
    val labelMap = labels.zipWithIndex.toMap
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelMap).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    val ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labels(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labels(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labels(shirt._1.last)
      }
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    var cnt = input(0).split(" ").map(_.toInt)
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    var ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labelString(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    val labels = Array("S","M","L","XL","XXL","XXXL")
    val labelMap = labels.zipWithIndex.toMap
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelMap).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    val ans = new Array[Int](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = shirt._1.head
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = shirt._1.head
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = shirt._1.last
      }
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.map(labels).mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    val ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labelString(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    val cnt = input(0).split(" ").map(_.toInt).toArray
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    var ans = new Array[String](n)
    for(shirt <- single){
      cnt(shirt._1.head) = cnt(shirt._1.head)-1
      ans(shirt._2) = labelString(shirt._1.head)
    }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}

import scala.io.Source._
object Solution{
  def main(args: Array[String]){
    def labelString(id: Int) = List("S","M","L","XL","XXL","XXXL")(id)
    def labelInt(id: String) = List("S","M","L","XL","XXL","XXXL").indexOf(id)
    val input = stdin.getLines().toList
    var cnt = input(0).split(" ").map(_.toInt)
    val n = input(1).toInt
    val (single,double) = input.drop(2).map(_.split(",").map(labelInt).toList).zipWithIndex.sortWith(_._1.head < _._1.head).partition(_._1.size == 1)
    var ans = new Array[String](n)
    for(shirt <- single)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
    for(shirt <- double)
      if(cnt(shirt._1.head) > 0){
        cnt(shirt._1.head) = cnt(shirt._1.head)-1
        ans(shirt._2) = labelString(shirt._1.head)
      }
      else{
        cnt(shirt._1.last) = cnt(shirt._1.last)-1
        ans(shirt._2) = labelString(shirt._1.last)
      }
    //println(cnt.toList)
    if(cnt.min < 0){
      println("NO")
      return
    }
    println("YES")
    println(ans.mkString("\n"))
  }
}


Recently Monocarp got a job. His working day lasts exactly $$$m$$$ minutes. During work, Monocarp wants to drink coffee at certain moments: there are $$$n$$$ minutes $$$a_1, a_2, \dots, a_n$$$, when he is able and willing to take a coffee break (for the sake of simplicity let's consider that each coffee break lasts exactly one minute). However, Monocarp's boss doesn't like when Monocarp takes his coffee breaks too often. So for the given coffee break that is going to be on minute $$$a_i$$$, Monocarp must choose the day in which he will drink coffee during the said minute, so that every day at least $$$d$$$ minutes pass between any two coffee breaks. Monocarp also wants to take these $$$n$$$ coffee breaks in a minimum possible number of working days (he doesn't count days when he is not at work, and he doesn't take coffee breaks on such days). Take into account that more than $$$d$$$ minutes pass between the end of any working day and the start of the following working day.For each of the $$$n$$$ given minutes determine the day, during which Monocarp should take a coffee break in this minute. You have to minimize the number of days spent.

The first line contains three integers $$$n$$$, $$$m$$$, $$$d$$$ $$$(1 \le n \le 2\cdot10^{5}, n \le m \le 10^{9}, 1 \le d \le m)$$$ — the number of coffee breaks Monocarp wants to have, the length of each working day, and the minimum number of minutes between any two consecutive coffee breaks. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le m)$$$, where $$$a_i$$$ is some minute when Monocarp wants to have a coffee break.

In the first line, write the minimum number of days required to make a coffee break in each of the $$$n$$$ given minutes.  In the second line, print $$$n$$$ space separated integers. The $$$i$$$-th of integers should be the index of the day during which Monocarp should have a coffee break at minute $$$a_i$$$. Days are numbered from $$$1$$$. If there are multiple optimal solutions, you may print any of them.

NoteIn the first example, Monocarp can take two coffee breaks during the first day (during minutes $$$1$$$ and $$$5$$$, $$$3$$$ minutes will pass between these breaks). One break during the second day (at minute $$$2$$$), and one break during the third day (at minute $$$3$$$).In the second example, Monocarp can determine the day of the break as follows: if the minute when he wants to take a break is odd, then this break is on the first day, if it is even, then this break is on the second day.

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 = {
    import java.util
    val N, M, D = ni()
    val A = na(N)
    val A_rev = mutable.Map[Int, Int]()
    rep(N) { i =>
      A_rev(A(i)) = i
    }
    val bt = new util.TreeSet[Int]()
    A foreach bt.add
    val ans = Array.ofDim[Int](N)
    var days = 1

    while(!bt.isEmpty) {
      var x = bt.first()
      while(x != 0) {
//        System.err.println(x)
        bt.remove(x)
        ans(A_rev(x)) = days
        x = bt.higher(x + D)
      }
      days += 1
    }

    out.println(days - 1)
    out.println(ans.mkString(" "))
  }

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


You are given a bracket sequence $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.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 "()()", "(())" are regular (the resulting expressions are: "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.You can change the type of some bracket $$$s_i$$$. It means that if $$$s_i = $$$ ')' then you can change it to '(' and vice versa.Your task is to calculate the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the bracket sequence. The second line of the input contains the string $$$s$$$ consisting of $$$n$$$ opening '(' and closing ')' brackets.

Print one integer — the number of positions $$$i$$$ such that if you change the type of the $$$i$$$-th bracket, then the resulting bracket sequence becomes regular.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = ns(N).map {
      case '(' => 1
      case ')' => -1
    }
    val cum = cumSum(S)
    val minL = Array.ofDim[Int](N + 1) // 左からiこまでのcumのmin
    REP(N, 1) { i =>
      minL(i) = min(minL(i - 1), cum(i))
    }
    val minR = Array.ofDim[Int](N + 1) // 右からiこまでのcumのmin
    minR(1) = cum(N)
    REP(N - 1, 2) { i =>
      minR(i) = min(minR(i - 1), cum(N + 1 - i))
    }

    def count(d: Int): Int = {
      var sum = 0
      REP(N) { i =>
        if (S(i) == d && minL(i) == 0 && minR(N - i) == d * 2) {
          sum += 1
        }
      }
      sum
    }

    val ms = cum.min
    if (ms == 0 && cum(N) == 0 || ms < -2 || cum(N) > 2 || cum(N) < -2) {
      out.println(0)
    } else {
      val ans = cum(N) match {
        case 2 => count(1)
        case -2 => count(-1)
        case _ => 0
      }
      out.println(ans)
    }
  }

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, 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 = ni()
    val S = ns(N).map {
      case '(' => 1
      case ')' => -1
    }
    val cum = cumSum(S)
    val minR = Array.ofDim[Int](N + 1) // 右からiこまでのcumのmin
    minR(1) = cum(N)
    REP(N - 1, 2) { i =>
      minR(i) = min(minR(i - 1), cum(N + 1 - i))
    }

    def find1: Option[Int] = {
      REP(N) { i =>
        if (S(i) == 1 && cum(i + 1) >= 2 && minR(N - i) == 2) {
          return Some(i)
        }
      }
      None
    }

    def find_1: Option[Int] = {
      REP(N) { i =>
        if (S(i) == -1 && cum(i + 1) < 0 && minR(N - i) == -2) {
          return Some(i)
        }
      }
      None
    }

    val ms = cum.min
    if (ms == 0 && cum(N) == 0 || ms < -2 || cum(N) > 2 || cum(N) < -2) {
      out.println(0)
    } else {
      val ans = cum(N) match {
        case 2 => find1
        case -2 => find_1
        case _ => None
      }
      ans match {
        case None => out.println(0)
        case Some(i) => out.println(i + 1)
      }
    }
  }

  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 = ni()
    val S = ns(N).map {
      case '(' => 1
      case ')' => -1
    }
    val cum = cumSum(S)
    val minR = Array.ofDim[Int](N + 1) // 右からiこまでのcumのmin
    minR(1) = cum(N)
    REP(N - 1, 2) { i =>
      minR(i) = min(minR(i - 1), cum(N + 1 - i))
    }

    def find(d: Int): Option[Int] = {
      REP(N) { i =>
        if (S(i) == d && cum(i + 1) >= d * 2 && minR(N - i) == d * 2) {
          return Some(i)
        }
      }
      None
    }

    val ms = cum.min
    if (ms == 0 && cum(N) == 0 || ms < -2 || cum(N) > 2 || cum(N) < -2) {
      out.println(0)
    } else {
      val ans = cum(N) match {
        case 2 => find(1)
        case -2 => find(-1)
        case _ => None
      }
      ans match {
        case None => out.println(0)
        case Some(i) => out.println(i + 1)
      }
    }
  }

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


A bow adorned with nameless flowers that bears the earnest hopes of an equally nameless person.You have obtained the elegant bow known as the Windblume Ode. Inscribed in the weapon is an array of $$$n$$$ ($$$n \ge 3$$$) positive distinct integers (i.e. different, no duplicates are allowed).Find the largest subset (i.e. having the maximum number of elements) of this array such that its sum is a composite number. A positive integer $$$x$$$ is called composite if there exists a positive integer $$$y$$$ such that $$$1 < y < x$$$ and $$$x$$$ is divisible by $$$y$$$.If there are multiple subsets with this largest size with the composite sum, you can output any of them. It can be proven that under the constraints of the problem such a non-empty subset always exists.

Each test consists of multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$3 \leq n \leq 100$$$) — the length of the array. The second line of each test case contains $$$n$$$ distinct integers $$$a_{1},a_{2},\dots,a_{n}$$$ ($$$1 \leq a_{i} \leq 200$$$) — the elements of the array.

Each test case should have two lines of output. The first line should contain a single integer $$$x$$$: the size of the largest subset with composite sum. The next line should contain $$$x$$$ space separated integers representing the indices of the subset of the initial array.

NoteIn the first test case, the subset $$$\{a_2, a_1\}$$$ has a sum of $$$9$$$, which is a composite number. The only subset of size $$$3$$$ has a prime sum equal to $$$11$$$. Note that you could also have selected the subset $$$\{a_1, a_3\}$$$ with sum $$$8 + 2 = 10$$$, which is composite as it's divisible by $$$2$$$.In the second test case, the sum of all elements equals to $$$21$$$, which is a composite number. Here we simply take the whole array as our subset.

import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLine

object WimbledumOde extends App {

  def f(s: Stream[Int], head: Int): Stream[Int] = {
    val r = s filter {
      x => if(x % head != 0) true else false
    }
    r
  }

  def numStream(n: Int): Stream[Int] = Stream.from(n)

  def sieve(stream: Stream[Int]): Stream[Int] = stream.head #:: sieve(f(stream.tail, stream.head))

  val primes = sieve(numStream(2))

  def isPrime(n: Int): Boolean = {
    for (i <- primes) {
      if(i == n) return true
      if (i > n) return false
    }
    false
  }

  val t = readLine.trim.toInt
  for (_ <- 0 until t) {
    val n = readLine.trim.toInt
    val arr = readLine.trim.split(' ').map(_.toInt).toList
    val sum = arr.sum
    if(!isPrime(sum)) {
      println(n)
      val idx = 1 to n
      println(idx.mkString(" "))
    } else {
      val oddIndexes : ListBuffer[Int] = ListBuffer()
      for(i <- arr.indices) {
        if(arr(i) % 2 != 0) oddIndexes += i
      }

      val ans:ListBuffer[Int] = ListBuffer()
      for(i <- arr.indices) {
        if(i != oddIndexes.head) ans += (i+1)
      }

      println(n-1)
      println(ans.mkString(" "))
    }
  }
}

import scala.io.StdIn.readLine

object WimbledumOde extends App {

  def f(s: Stream[Int], head: Int): Stream[Int] = {
    val r = s filter {
      x => if(x % head != 0) true else false
    }
    r
  }

  def numStream(n: Int): Stream[Int] = Stream.from(n)

  def sieve(stream: Stream[Int]): Stream[Int] = stream.head #:: sieve(f(stream.tail, stream.head))

  val primes = sieve(numStream(2))

  def isPrime(n: Int): Boolean = {
    for (i <- primes) {
      if(i == n) return true
      if (i > n) return false
    }
    false
  }

  val t = readLine.trim.toInt
  for (_ <- 0 until t) {
    val n = readLine.trim.toInt
    val arr = readLine.trim.split(' ').map(_.toInt).toList
    val sum = arr.sum
    if(!isPrime(sum)) {
      println(n)
      val idx = 1 to n
      println(idx.mkString(" "))
    } else {
      val oddIndexes = arr.map(x => if (x%2 != 0) arr.indexOf(x) else -1).filter(x => x > -1)
      val ans = arr.map(x => if(x != oddIndexes.head) arr.indexOf(x)+1 else -1).filter(x => x > -1)
      println(n-1)
      println(ans.mkString(" "))
    }
  }
}


One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?

The first line contains an integer n (2 ≤ n ≤ 105). The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.

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

/**
 * Created by arseny on 01.08.14.
 */
object B extends App {

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

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

  def solve() = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    if (a.toList == a.sorted.toList) {
      out.println(0)
    } else {
      var r = -1
      for (i <- n - 1 to 1 by(-1) if r == -1) {
        if (a(i) < a(i - 1)) {
          r = i
        }
      }
      //out.println(r)
      val b = a.takeRight(n - r) ++ a.take(r)
      //out.println(b.toList)
      if (b.toList == b.sorted.toList) {
        out.println(n - r)
      } else {
        out.println(-1)
      }
    }

  }

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

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val min = data.min
  if (data.forall(_ == min))
    println(0)
  else {
    var start = data.indexOf(min)
    if (start == 0)
      if (data.last == min) {
        start = n - 1
        while (data(start - 1) == min)
          start = start - 1
      }
    val candidate = (start to start + n - 1).map(i => data(i % n))

    if (candidate.tail.foldLeft((false, min)){
      case((true, prev), el) => (true, el)
      case((false, prev), el) => (prev > el, el)
    }._1)
      println(-1)
    else
      println((n - start) % n)
  }
}

object B454 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val a = readInts(n)
    var idx = -1
    for(i <- 1 until n if idx == -1)
      if(a(i-1) > a(i))
        idx = i
    if(idx != -1) {
      val newA = a.takeRight(n-idx) ++ a.take(idx)
      if(newA.zip(a.sorted).forall(arr => arr._1 == arr._2))
        println(n-idx)
      else
        println("-1")
    } else {
      if(a.sorted.zip(a).forall(arr => arr._1 == arr._2))
        println("0")
      else
        println("-1")
    }
  }

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

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

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

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

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

}

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object B extends App {

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

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

  var i = 1

  while (i < n && as(i) >= as(i - 1)) i += 1
  if (i == n) {
    println(0)
    System.exit(0)
  }

  if (as.last > as.head) {
    println(-1)
    System.exit(0)
  }
  //println(i)
  var j = n - 2
  while (j >= i && as(j) <= as(j + 1)) j -= 1
  //println(j)
  if (j < i && as(j + 1) <= as.head) println(n - j - 1)
  else println(-1)
}

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

object B {

  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)
    }
    return st.nextToken
  }

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

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

  def smartSolver(n: Int, a: Array[Int]): Int = {
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev <= a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      else {
        prev = a(ind)
        ind = (ind + 1) % n
        terminate += 1
      }
    }
    if (flag) {
      return n - ind - 1
    } else {
      return -1
    }
  }

  def stupidSolver(n: Int, a: Array[Int]): Int = {
    var ans = 1000000
    for (i <- 0 until n) {
      var len = 0
      var ind = i
      var cnt = 0
      var prev = a(ind)
      while (len < n - 1) {
        ind = (ind + 1) % n
        if (prev <= a(ind)) {
          cnt += 1
        }
        len += 1
        prev = a(ind)
      }
      if (cnt == n - 1) {
        ans = Math.min(i, ans)
      }
    }
    return ans
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    //    val rand = new Random
    //    for (i <- 0 until n) {
    //      a(i) = rand.nextInt(5)
    //    }
    //    for (i <- 0 until n) {
    //      out.print(a(i) + " ")
    //    }
    //    out.println
    //    out.println("smart = " + smartSolver(n, a))
    //    out.println("stupid = " + stupidSolver(n, a))
    out.println(smartSolver(n, a))
    return 1
  }

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

/**
 * I've tried to make this piece of code as readable as possible.
 * Enjoy hacking it!
 */
import scala.collection._

object B extends App {

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

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

  var i = 1

  while (i < n && as(i) >= as(i - 1)) i += 1
  if (i == n) {
    println(0)
    System.exit(0)
  }

  if (as.last > as.head) {
    println(-1)
    System.exit(0)
  }

  var j = n - 2
  while (j >= i && as(j) >= as(j + 1)) j -= 1

  if (j < i) println(n - j - 1)
  else println(-1)
}

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

object B {

  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)
    }
    return st.nextToken
  }

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

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

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev <= a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      prev = a(ind)
      ind = (ind + 1) % n
      terminate += 1
    }
    if (flag) {
      out.println(terminate - n + 1)
    } else {
      out.println(-1)
    }
    return 1
  }

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

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

object B {

  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)
    }
    return st.nextToken
  }

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

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

  def smartSolver(n: Int, a: Array[Int]): Int = {
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev <= a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      else {
        prev = a(ind)
        ind = (ind + 1) % n
        terminate += 1
      }
    }
    if (flag) {
      return terminate - n + 2
    } else {
      return -1
    }
  }

  def stupidSolver(n: Int, a: Array[Int]): Int = {
    var ans = 1000000
    for (i <- 0 until n) {
      var len = 0
      var ind = i
      var cnt = 0
      var prev = a(ind)
      while (len < n - 1) {
        ind = (ind + 1) % n
        if (prev <= a(ind)) {
          cnt += 1
        }
        len += 1
        prev = a(ind)
      }
      if (cnt == n - 1) {
        ans = Math.min(i, ans)
      }
    }
    return ans
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
    //    val rand = new Random
    //    for (i <- 0 until n) {
    //      a(i) = rand.nextInt(100)
    //    }
    //    for (i <- 0 until n) {
    //      out.print(a(i) + " ")
    //    }
    //    out.println
    //    out.println("smart = " + smartSolver(n, a))
    //    out.println("stupid = " + stupidSolver(n, a))
    out.println(smartSolver(n, a))
    return 1
  }

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

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

object B {

  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)
    }
    return st.nextToken
  }

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

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

  def smartSolver(n: Int, a: Array[Int]): Int = {
    var ind = 1
    var flag = false
    var prev = a(0)
    var count = 0
    var terminate = 0
    while (terminate <= 3 * n && !flag) {
      if (prev < a(ind)) {
        count += 1
      } else {
        count = 0
      }
      if (count == n - 1) {
        flag = true
      }
      else {
        prev = a(ind)
        ind = (ind + 1) % n
        terminate += 1
      }
    }
    if (flag) {
      return terminate - n + 2
    } else {
      return -1
    }
  }

  def stupidSolver(n: Int, a: Array[Int]): Int = {
    var ans = 1000000
    for (i <- 0 until n) {
      var len = 0
      var ind = i
      var cnt = 0
      var prev = a(ind)
      while (len < n - 1) {
        ind = (ind + 1) % n
        if (prev <= a(ind)) {
          cnt += 1
        }
        len += 1
        prev = a(ind)
      }
      if (cnt == n - 1) {
        ans = Math.min(i, ans)
      }
    }
    return ans
  }

  def solve: Int = {
    val n = nextInt
    val a = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
    }
//    val rand = new Random
//    for (i <- 0 until n) {
//      a(i) = rand.nextInt(5)
//    }
//    for (i <- 0 until n) {
//      out.print(a(i) + " ")
//    }
//    out.println
//    out.println("smart = " + smartSolver(n, a))
//    out.println("stupid = " + stupidSolver(n, a))
        out.println(smartSolver(n, a))
    return 1
  }

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


Let's define the following recurrence: $$$$$$a_{n+1} = a_{n} + minDigit(a_{n}) \cdot maxDigit(a_{n}).$$$$$$Here $$$minDigit(x)$$$ and $$$maxDigit(x)$$$ are the minimal and maximal digits in the decimal representation of $$$x$$$ without leading zeroes. For examples refer to notes.Your task is calculate $$$a_{K}$$$ for given $$$a_{1}$$$ and $$$K$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of independent test cases. Each test case consists of a single line containing two integers $$$a_{1}$$$ and $$$K$$$ ($$$1 \le a_{1} \le 10^{18}$$$, $$$1 \le K \le 10^{16}$$$) separated by a space.

For each test case print one integer $$$a_{K}$$$ on a separate line.

import scala.collection.mutable.ArrayBuffer

object CodeforcesRound643a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    var Array(a1, k) = rll_long
    (2L to Math.min(k, 100L)).foreach(_ => a1 = a1 + minDigit(a1) * maxDigit(a1))
    writer.println(a1)
  }

  def minDigit(n: Long): Long = {
    digits(n).fold(9L) { case (a, b) => Math.min(a, b) }
  }

  def maxDigit(n: Long): Long = {
    digits(n).fold(0L) { case (a, b) => Math.max(a, b) }
  }

  // Allocates memory, but should work
  def digits(n: Long): Array[Long] = {
    val digits = ArrayBuffer[Long]()
    var nn = n
    while (nn > 0) {
      digits.append(nn % 10L)
      nn = nn / 10
    }
    if (digits.isEmpty) {
      Array(0L)
    } else {
      digits.toArray
    }
  }

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

import java.util.Scanner

object Main extends App {

  val s = new Scanner(System.in)

  var t = s.nextInt()

  for(_ <- 0 until t) {
    val a1 = s.nextLong()
    val k = s.nextLong()

    var i: Long = 1L
    var ai: Long = a1

    while(i < k && minDigit(ai) != 0) {
      i += 1
      ai = ai + minDigit(ai) * maxDigit(ai)
    }

    println(ai)
  }

  def minDigit(n: Long): Long = {
    n.toString.min - '0'
  }
  def maxDigit(n: Long): Long = {
    n.toString.max - '0'
  }

}

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 C643A(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 C643A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t = ni()
    REP(t) { _ =>
      val a = nl()
      val k = nl()

      var continue = true
      var run = 1
      var vl = a
      while (continue && run < k) {
        val x = vl + minE(vl) * maxE(vl)
        if(x == vl) continue = false
        run += 1
        vl = x
      }

      out.println(vl)
    }
  }

  def minE(u: Long): Int = {
    var v = u
    var rt = 10

    while (v > 0) {
      if(v % 10 < rt) rt = (v % 10).toInt
      v /= 10
    }
    rt
  }

  def maxE(u: Long): Int = {
    var v = u
    var rt = -1

    while (v > 0) {
      if(v % 10 > rt) rt = (v % 10).toInt
      v /= 10
    }
    rt
  }
}

object A extends App {
  private def an(a1: Long, n: Long): Long = {
    def go(a1: String, n: Long): String =
      if (a1.contains('0') || n == 1) a1
      else go((a1.toLong + (a1.min - 48) * (a1.max - 48)).toString(), n - 1)

    go(a1.toString, n).toLong
  }

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

  (0 until t).foreach { _ =>
    val Array(a1, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    val ai = an(a1, k)

    println(ai)
  }
}

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

  (0 until t).foreach { _ =>
    val Array(a1, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    var i  = 1L
    var ai = a1
    var ds = (a1 % 10, a1 % 10)

    while (i < k && ds._1 != 0) {
      var a = ai
      ds = (a % 10, a % 10)
      while (a != 0 && ds._1 != 0) {
        val d = a % 10
        a /= 10
        ds = (if (d < ds._1) d else ds._1, if (d > ds._2) d else ds._2)
      }

      i += 1L
      ai += ds._1 * ds._2
    }

    println(ai)
  }
}

import scala.io.StdIn._

object solver {
    def main(args:Array[String]) = {
        val t:Int = readInt()

        (1 to t).foreach(_=>{
            val Array(a1,k) = readLine.split(" ").map(_.toLong)
            def transform(a:Long,k:Long):Long = {
                val x = a.toString.split("").map(_.toLong).toList
                if(x.min==0) a
                else if(k==1) a
                else transform(x.min*x.max+a,k-1)
            }

            println(transform(a1,k))
            ()
        })
    }
}

object ProblemA extends App {
  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

    def nextToken(): String = {
      while (st == null || !st.hasMoreTokens) {
        st = new StringTokenizer(in.readLine);
      }
      return st.nextToken();
    }

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

    def nextLong(): Long = {
      nextToken().toLong;
    }

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val t = in.nextInt()

  for (_ <- 1 to t) {
    var a1 = in.nextLong()
    var k = in.nextLong()

    while (k > 1) {
      k = k - 1
      a1 = a1 + (a1.toString.min.toInt - 48) * (a1.toString.max.toInt - 48)
      if (a1.toString.contains('0'))  k = 0
    }
    println(a1)
  }

}

import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {

  @tailrec
  private def perform(start: Long, element: Long, last: Long = -1): Long = {
    (start, element) match {
      case (s, 1) => s
      case (s, _) if s == last => s
      case (s, e) =>
        val sth = ((s.toString.max - '0').toLong * (s.toString.min - '0').toLong) + s
        perform(sth, e - 1, start)
    }
  }

  def foo(list: List[(Long, Long)]) = {
    list.map(x => perform(x._1, x._2))
  }

 val scan = new Scanner(System.in)
 val n = scan.nextLong()
 val seq = for {
   _ <- 0.toLong until n.toLong
   (x, y) = (scan.nextLong(), scan.nextLong())
 } yield x -> y

  foo(seq.toList).foreach(println)

}

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

  (0 until t).foreach { _ =>
    val Array(a1, k) = scala.io.StdIn.readLine().split(" ").map(_.toLong)

    var i  = 1L
    var ai = a1
    var ds = (a1 % 10, a1 % 10)

    do {
      var a = ai
      ds = (a % 10, a % 10)
      while (a != 0 && (ds._1 != 0 || ds._2 != 9)) {
        val d = a % 10
        a /= 10
        ds = (if (d < ds._1) d else ds._1, if (d > ds._2) d else ds._2)
      }

      i += 1L
      ai += ds._1 * ds._2
    } while (i < k && (ds._1 != 0 || ds._2 != 9))

    println(ai)
  }
}

import scala.io.StdIn._

object solver {
    def main(args:Array[String]) = {
        val t:Int = readInt()

        (1 to t).foreach(_=>{
            val Array(a1,k) = readLine.split(" ").map(_.toInt)
            def transform(a:Int,k:Int):Int = {
                val x = a.toString.split("").map(_.toInt).toList
                if(x.min==0) 0
                else if(k==1) a
                else transform(x.min*x.max+a,k-1)
            }

            println(transform(a1,k))
            ()
        })
    }
}

import java.util.Scanner

import scala.annotation.tailrec

object Main extends App {

  @tailrec
  private def perform(start: Long, element: Long, last: Long = -1): Long = {
    (start, element) match {
      case (s, 0) => s
      case (s, _) if s == last => s
      case (s, e) =>
        val sth = ((s.toString.max - '0').toLong * (s.toString.min - '0').toLong) + s
        perform(sth, e - 1, start)
    }
  }

  def foo(list: List[(Long, Long)]) = {
    list.map(x => perform(x._1, x._2))
  }

 val scan = new Scanner(System.in)
 val n = scan.nextLong()
 val seq = for {
   _ <- 0.toLong until n.toLong
   (x, y) = (scan.nextLong(), scan.nextLong())
 } yield x -> y

  foo(seq.toList).foreach(println)

}