You are given two strings $$$s$$$ and $$$t$$$. The string $$$s$$$ consists of lowercase Latin letters and at most one wildcard character '*', the string $$$t$$$ consists only of lowercase Latin letters. The length of the string $$$s$$$ equals $$$n$$$, the length of the string $$$t$$$ equals $$$m$$$.The wildcard character '*' in the string $$$s$$$ (if any) can be replaced with an arbitrary sequence (possibly empty) of lowercase Latin letters. No other character of $$$s$$$ can be replaced with anything. If it is possible to replace a wildcard character '*' in $$$s$$$ to obtain a string $$$t$$$, then the string $$$t$$$ matches the pattern $$$s$$$.For example, if $$$s=$$$"aba*aba" then the following strings match it "abaaba", "abacaba" and "abazzzaba", but the following strings do not match: "ababa", "abcaaba", "codeforces", "aba1aba", "aba?aba".If the given string $$$t$$$ matches the given string $$$s$$$, print "YES", otherwise print "NO".

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the string $$$s$$$ and the length of the string $$$t$$$, respectively. The second line contains string $$$s$$$ of length $$$n$$$, which consists of lowercase Latin letters and at most one wildcard character '*'. The third line contains string $$$t$$$ of length $$$m$$$, which consists only of lowercase Latin letters.

Print "YES" (without quotes), if you can obtain the string $$$t$$$ from the string $$$s$$$. Otherwise print "NO" (without quotes).

NoteIn the first example a wildcard character '*' can be replaced with a string "force". So the string $$$s$$$ after this replacement is "codeforces" and the answer is "YES".In the second example a wildcard character '*' can be replaced with an empty string. So the string $$$s$$$ after this replacement is "vkcup" and the answer is "YES".There is no wildcard character '*' in the third example and the strings "v" and "k" are different so the answer is "NO".In the fourth example there is no such replacement of a wildcard character '*' that you can obtain the string $$$t$$$ so the answer is "NO".

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

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

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

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

  def solve(): Unit = {
    val N, M = ni()
    val s, t = ns()
    val ok = s.indexOf('*') match {
      case -1 =>
        s == t
      case ix =>
        val l = s.take(ix)
        val r = s.drop(ix + 1)
        N - 1 <= M && t.startsWith(l) && t.endsWith(r)
    }

    val ans = if (ok) "YES" else "NO"

    out.println(ans)
  }

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

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

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

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

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

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_504_A {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.t2)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val m = l1.int
    val s = readLine.string
    val t = readLine.string

    val ind = s.indexOf("*")
    var res = false
    if (ind == -1) {
      res = s==t
    } else {
      val start = s.substring(0,ind)
      val stop = s.substring(ind+1, s.length())
      res = t.startsWith(start) && t.drop(start.length()).endsWith(stop)
    }
    outLn( if (res) "YES" else "NO" )

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
6 10
code*s
codeforces
"""

val sa2 = """
6 5
vk*cup
vkcup
"""

val sa3 = """
1 1
v
k
"""

val t1 = """
9 10
*deforces
codeforces
"""

val t2 = """
9 10
codeforc*
codeforces
"""
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_504_A {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.t2)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val l1 = readLine
    val n = l1.int
    val m = l1.int
    val s = readLine.string
    val t = readLine.string

    val ind = s.indexOf("*")
    var res = false
    if (ind == -1) {
      res = s==t
    } else {
      val start = s.substring(0,ind)
      val stop = s.substring(ind+1, s.length())
      res = t.startsWith(start) && t.endsWith(stop)
    }
    outLn( if (res) "YES" else "NO" )

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

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

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

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

val sa1 = """
6 10
code*s
codeforces
"""

val sa2 = """
6 5
vk*cup
vkcup
"""

val sa3 = """
1 1
v
k
"""

val t1 = """
9 10
*deforces
codeforces
"""

val t2 = """
9 10
codeforc*
codeforces
"""
}

}


Recently Maxim has found an array of n integers, needed by no one. He immediately come up with idea of changing it: he invented positive integer x and decided to add or subtract it from arbitrary array elements. Formally, by applying single operation Maxim chooses integer i (1 ≤ i ≤ n) and replaces the i-th element of array ai either with ai + x or with ai - x. Please note that the operation may be applied more than once to the same position.Maxim is a curious minimalis, thus he wants to know what is the minimum value that the product of all array elements (i.e. ) can reach, if Maxim would apply no more than k operations to it. Please help him in that.

The first line of the input contains three integers n, k and x (1 ≤ n, k ≤ 200 000, 1 ≤ x ≤ 109) — the number of elements in the array, the maximum number of operations and the number invented by Maxim, respectively. The second line contains n integers a1, a2, ..., an () — the elements of the array found by Maxim.

Print n integers b1, b2, ..., bn in the only line — the array elements after applying no more than k operations to the array. In particular,  should stay true for every 1 ≤ i ≤ n, but the product of all array elements should be minimum possible. If there are multiple answers, print any of them.

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k
  if (parity == 0) {
    left -= Math.min(k, 1 + Math.abs(a(min)) / x).toInt
    if (a(min) >= 0)
      a(min) -= Math.min(k, 1 + Math.abs(a(min)) / x) * x
    else
      a(min) += Math.min(k, 1 + Math.abs(a(min)) / x) * x
  }

  if (left > 0) {
    val q = mutable.PriorityQueue(a.map(i => -Math.abs(i)).zipWithIndex: _*)
    (0 until left).foreach { _ =>
      val (value, index) = q.dequeue()
      q.enqueue((value - x, index))
    }
    q.foreach {
      case (value, index) if a(index) >= 0 => a(index) = Math.abs(value)
      case (value, index) => a(index) = -Math.abs(value)
    }

  }

  println(a.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt)
  val min = a.indices.minBy(a)
  val nValue = a(min) - Math.min(k, 1 + a(min) / x) * x
  var left = k - Math.min(k, 1 + a(min) / x)
  a(min) = -nValue

  if (left > 0) {
    val sorted = a.indices.sortBy(i => Math.abs(a(i)))
    val increments = Array.ofDim[Int](n + 1)
    var i = 1
    while (left > 0) {
      val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)
      increments(0) += 1
      if (left >= j) {
        increments(j - 1) -= 1
        i = j
        left -= j
      } else {
        increments(k - 1) -= 1
        left = 0
      }
    }
    var sum = 0
    (0 until n).foreach { i =>
      sum += x * increments(i)
      a(sorted(i)) += sum
    }

//    println(increments.mkString(" "))
  }
  a(min) *= -1

  println(a.mkString(" "))
}

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k
  if (parity == 0) {
    left -= Math.min(k, 1 + a(min) / x).toInt
    if (a(min) >= 0)
      a(min) -= Math.min(k, 1 + a(min) / x) * x
    else
      a(min) += Math.min(k, 1 + a(min) / x) * x
  }

  if (left > 0) {
    val q = mutable.PriorityQueue(a.map(i => -Math.abs(i)).zipWithIndex: _*)
    (0 until left).foreach { _ =>
      val (value, index) = q.dequeue()
      q.enqueue((value - x, index))
    }
    q.foreach {
      case (value, index) if a(index) >= 0 => a(index) = Math.abs(value)
      case (value, index) => a(index) = -Math.abs(value)
    }

  }

  println(a.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k.toLong
  if (parity == 0) {
    left -= Math.min(k, 1 + a(min) / x)
    if (a(min) >= 0)
      a(min) -= Math.min(k, 1 + a(min) / x) * x
    else
      a(min) += Math.min(k, 1 + a(min) / x) * x
  }

  if (left > 0) {
    val sorted = a.indices.sortBy(i => Math.abs(a(i)))
    val increments = Array.ofDim[Int](n + 1)
    var i = 1
    while (left > 0) {
      val j = (i until n).find(z => Math.abs(a(sorted(z))) >= Math.abs(a(sorted(0)) + (increments(0) + 1) * x)).getOrElse(n)
      increments(0) += 1
      if (left >= j) {
        increments(j) -= 1
        i = j
        left -= j
      } else {
        increments(left.toInt) -= 1
        left = 0
      }
    }
    var sum = 0l
    (0 until n).foreach { i =>
      sum += x * increments(i)
      if (a(sorted(i)) >= 0)
        a(sorted(i)) += sum
      else
        a(sorted(i)) -= sum
    }

    //    println(increments.mkString(" "))
  }

  println(a.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k.toLong
  if (parity == 0) {
    val nValue = a(min) - Math.min(k, 1 + a(min) / x) * x
    left -= Math.min(k, 1 + a(min) / x)
    a(min) = -nValue
  }

  if (left > 0) {
    val sorted = a.indices.sortBy(i => Math.abs(a(i)))
    val increments = Array.ofDim[Int](n + 1)
    var i = 1
    while (left > 0) {
      val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)
      increments(0) += 1
      if (left >= j) {
        increments(j - 1) -= 1
        i = j
        left -= j
      } else {
        increments(left.toInt) -= 1
        left = 0
      }
    }
    var sum = 0l
    (0 until n).foreach { i =>
      sum += x * increments(i)
      if (a(sorted(i)) >= 0)
        a(sorted(i)) += sum
      else
        a(sorted(i)) -= sum
    }

    //    println(increments.mkString(" "))
  }
  if (parity == 0)
    a(min) *= -1

  println(a.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k.toLong
  if (parity == 0) {
    left -= Math.min(k, 1 + a(min) / x)
    if (a(min) >= 0)
      a(min) -= Math.min(k, 1 + a(min) / x) * x
    else
      a(min) += Math.min(k, 1 + a(min) / x) * x
  }

  if (left > 0) {
    val sorted = a.indices.sortBy(i => Math.abs(a(i)))
    val increments = Array.ofDim[Int](n + 1)
    var i = 1
    while (left > 0) {
      val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)
      increments(0) += 1
      if (left >= j) {
        increments(j - 1) -= 1
        i = j
        left -= j
      } else {
        increments(left.toInt) -= 1
        left = 0
      }
    }
    var sum = 0l
    (0 until n).foreach { i =>
      sum += x * increments(i)
      if (a(sorted(i)) >= 0)
        a(sorted(i)) += sum
      else
        a(sorted(i)) -= sum
    }

    //    println(increments.mkString(" "))
  }

  println(a.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k.toLong
  if (parity == 0) {
    val nValue = a(min) - Math.min(k, 1 + a(min) / x) * x
    left -= Math.min(k, 1 + a(min) / x)
    a(min) = -nValue
  }

  if (left > 0) {
    val sorted = a.indices.sortBy(i => Math.abs(a(i)))
    val increments = Array.ofDim[Int](n + 1)
    var i = 1
    while (left > 0) {
      val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)
      increments(0) += 1
      if (left >= j) {
        increments(j - 1) -= 1
        i = j
        left -= j
      } else {
        increments(left.toInt - 1) -= 1
        left = 0
      }
    }
    var sum = 0l
    (0 until n).foreach { i =>
      sum += x * increments(i)
      if (a(sorted(i)) >= 0)
        a(sorted(i)) += sum
      else
        a(sorted(i)) -= sum
    }

//    println(increments.mkString(" "))
  }
  if (parity == 0)
    a(min) *= -1

  println(a.mkString(" "))
}

import scala.collection.mutable

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k
  if (parity == 1) {
    left -= Math.min(k, 1 + Math.abs(a(min)) / x).toInt
    if (a(min) >= 0)
      a(min) -= Math.min(k, 1 + Math.abs(a(min)) / x) * x
    else
      a(min) += Math.min(k, 1 + Math.abs(a(min)) / x) * x
  }

  if (left > 0) {
    val q = mutable.PriorityQueue(a.map(i => -Math.abs(i)).zipWithIndex: _*)
    (0 until left).foreach { _ =>
      val (value, index) = q.dequeue()
      q.enqueue((value - x, index))
    }
    q.foreach {
      case (value, index) if a(index) >= 0 => a(index) = Math.abs(value)
      case (value, index) => a(index) = -Math.abs(value)
    }

  }

  println(a.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, k, x) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toLong)
  val parity = a.count(_ < 0) % 2
  val zeros = a.count(_ == 0)

  val min = a.indices.minBy(i => Math.abs(a(i)))
  var left = k.toLong
  if (parity == 0) {
    left -= Math.min(k, 1 + a(min) / x)
    if (a(min) >= 0)
      a(min) -= Math.min(k, 1 + a(min) / x) * x
    else
      a(min) += Math.min(k, 1 + a(min) / x) * x
  }

  if (left > 0) {
    val sorted = a.indices.sortBy(i => Math.abs(a(i)))
    val increments = Array.ofDim[Int](n + 1)
    var i = 1
    while (left > 0) {
      val j = (i until n).find(z => a(sorted(z)) >= a(sorted(0)) + x).getOrElse(n)
      increments(0) += 1
      if (left >= j) {
        increments(j) -= 1
        i = j
        left -= j
      } else {
        increments(left.toInt) -= 1
        left = 0
      }
    }
    var sum = 0l
    (0 until n).foreach { i =>
      sum += x * increments(i)
      if (a(sorted(i)) >= 0)
        a(sorted(i)) += sum
      else
        a(sorted(i)) -= sum
    }

    //    println(increments.mkString(" "))
  }

  println(a.mkString(" "))
}


Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.

The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree. The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.

If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print  integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence.

NoteThe only tree in the first example and the two printed trees from the second example are shown on the picture:

import java.util

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

object Solution {

  //Console.setIn(new FileReader(new java.io.File("input")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  var caseNo = 1

  def doCase() : Unit = {
    val Array(h) = readIntLine()
    val heightCounts = readIntLine()
    val n = heightCounts.sum
    val ambiguous = heightCounts.sliding(2).exists(a => a(0) > 1 && a(1) > 1)
    if (!ambiguous) {
      println("perfect")
      return
    }

    println("ambiguous")
    println(construct(h, heightCounts, true).mkString(" "))
    println(construct(h, heightCounts, false).mkString(" "))
  }

  def construct(h : Int, heightCounts : Array[Int], mode : Boolean): Array[Int] = {
    val heightSums : Array[Int] = Array.ofDim(h + 1)
    heightSums.indices.tail.foreach{
      i =>
        heightSums(i) = heightSums(i - 1) + heightCounts(i - 1)
    }
    val parents = Array.ofDim[Int](heightSums.last + heightCounts.last)
    parents(0) = 0
    for ((count, height) <- heightCounts.zipWithIndex.tail) {
      val nodeIdx = heightSums(height)
      for (i <- 0 until count) {
        if (mode) {
          parents(i + nodeIdx) = (nodeIdx - 1) + 1
        } else {
          parents(i + nodeIdx) = Math.min(nodeIdx - 1, heightSums(height - 1) + i) + 1
        }
      }
    }
    parents
  }

  def main(args: Array[String]) {
    var tests = 1
    for (test <- 0 until tests) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

}


$$$n$$$ heroes fight against each other in the Arena. Initially, the $$$i$$$-th hero has level $$$a_i$$$.Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $$$1$$$.The winner of the tournament is the first hero that wins in at least $$$100^{500}$$$ fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.Calculate the number of possible winners among $$$n$$$ heroes.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of heroes. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the initial level of the $$$i$$$-th hero.

For each test case, print one integer — the number of possible winners among the given $$$n$$$ heroes.

NoteIn the first test case of the example, the only possible winner is the first hero.In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner.

import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._

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

        for(i <- 1 to t) {
            val n = readInt()
            var arr = readLine.split(" ").map(_.toInt)
            val idx = arr.sorted.indexWhere(_ > arr.min)
            if (idx == -1) println(0)
            else println(arr.length - idx)
        }
    }
}

object A {
  import scala.io.{StdIn => in}

  def main(args: Array[String]): Unit = {
    val tests = in.readInt()
    (1 to tests).foreach { _ =>
      in.readInt()
      val levels = in.readLine().split(' ').map(_.toInt)
      val min = levels.fold(Int.MaxValue) { case (a, b) => Math.min(a, b) }
      println(levels.count(_ > min))
    }
  }
}

//package codeforces.contests._1487

object Arena {

  def main(args: Array[String]): Unit = {
    println({
      for (_ <- 1 to io.StdIn.readInt()) yield {
        val n   = io.StdIn.readInt
        val arr = io.StdIn.readLine.split(" ").map(_.toInt)

        val minE = arr.min
        val mineECount = arr.count(_ == minE)

        if(n == mineECount) 0 else n - mineECount
      }
    }.mkString("\n"))
  }
}

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val as = nextInts(n)
      val min = as.min

      out.println(as.count(_ > min))
    }

    out.flush()
  }

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


A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].After each query you have to determine whether the number of inversions is odd or even.

The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.  The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct. The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process. Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.

Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.

NoteThe first example:  after the first query a = [2, 1, 3], inversion: (2, 1);  after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2). The second example:  a = [1, 2, 4, 3], inversion: (4, 3);  a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);  a = [1, 2, 4, 3], inversion: (4, 3);  a = [1, 4, 2, 3], inversions: (3, 2), (4, 2).

import java.io.FileReader
import java.util
import java.util.Comparator

import collection.Searching._
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))
  var caseNo = 1
  val magicMod = 1000000007

  def inversionCount[T](a : Array[T])(implicit ev: T => Ordered[T]) : Int = {
    inversionCountHelp(a, a.clone(), 0, a.length)
  }

  def inversionCountHelp[T](a : Array[T], b : Array[T], from : Int, to : Int)(implicit ev: T => Ordered[T]) : Int = {
    if (to - from <= 1) {
      return 0
    }
    var mid = (from + to) / 2
    var sum = inversionCountHelp(b, a, from, mid) + inversionCountHelp(b, a, mid, to)
    var i = from
    var j = mid
    var c = from
    while (i < mid && j < to) {
      if (b(i) < b(j)) {
        a(c) = b(i)
        i += 1
      } else {
        sum += mid - i
        a(c) = b(j)
        j += 1
      }
      c += 1
    }
    var x = i
    while (x < mid) {
      a(c) = b(x)
      c += 1
      x += 1
    }
    x = j
    while (x < to) {
      a(c) = b(x)
      c += 1
      x += 1
    }
    sum
  }

  def doCase() : Unit = {
    val Array(n) = readIntLine()
    val perm = readIntLine().map(_ - 1)
    val Array(m) = readIntLine()

    var count = inversionCount(perm.clone()) % 2
    var record : List[String] = List()
    var i = 0
    while (i < m) {
      var Array(l, r) = readIntLine()
      val changes = (r - l + 1) * (r - l) / 2
      count = (count + changes) % 2

      if (count % 2 == 1) {
        record ::= "odd"
      } else {
        record ::= "even"
      }
      i += 1
    }
    print(record.toArray.reverse.mkString("\n"))
    print("\n")
  }

  def main(args: Array[String]): Unit = {
    val noCases = 1
    for (i <- 0 until noCases) {
      doCase()
    }
  }

  def readIntLine(): Array[Int] = {
    StdIn.readLine().split(" ").map(_.toInt)
  }

  def readLongLine(): Array[Long] = {
    StdIn.readLine().split(" ").map(_.toLong)
  }

  def readBigIntLine(): Array[BigInt] = {
    StdIn.readLine().split(" ").map(BigInt.apply)
  }
}


Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?

The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively. The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.

Print a single integer — the minimum possible valid width of the road.

NoteIn the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.

import java.io.BufferedReader
import java.io.InputStreamReader

object HelloScala {
  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val line1 = br.readLine().split(" ")
    val n = line1.head.toInt
    val h = line1.last.toInt
    val line2 = br.readLine().split(" ")
    val heights = line2.map(_.toInt)
    val heightPartitions = heights.partition(_ > h)
    val output = heightPartitions._1.length*2+heightPartitions._2.length
    println(output)
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader

object HelloScala {
  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val line1 = br.readLine().split(" ")
    val n = line1.head.toInt
    val h = line1.last.toInt
    val line2 = br.readLine().split(" ")
    val heights = line2.map(_.toInt)
    val tallerCount = heights.count(_ > h)
    val output = tallerCount*2+n-tallerCount
    println(output)
  }
}

object Solution extends App {
  val Array (n, h) = readLine.split(" ").map(_.toInt)
  val tab = readLine.split(" ").map(_.toInt)

  val wyzsi = tab.sorted.dropWhile(_ <= h)

  println(tab.size + wyzsi.size)
}

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

  println(line.length + line.count(_ > h))
}

import scala.io.StdIn

object VanyaAndFence extends App {

  val l1 = StdIn.readLine().split(" ")
  val n = l1(0).toInt
  val h = l1(1).toInt

  val l2 = StdIn.readLine().split(" ")
  val heights = l2.map(_.toInt)
  print(impl(heights, h))

  def impl(heights: Array[Int], max: Int): Int = {
    var width: Int = 0
    for (height <- heights) {
      if (height > max) {
        width += 2
      } else {
        width += 1
      }
    }
    width
  }
}

object A677 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n, h) = readInts(2)
    val input = readInts(n)
    println(input.map(x => if(x > h) 2 else 1).sum)
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _677A extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, h = io[Int]
    val heights = io[Vector, Int](n)
    io += heights.sumWith(i => if (i > h) 2 else 1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f) findWithIndex c
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] {
  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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.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: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    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[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def array[A]: Write[Array[A]] = Write(_ mkString " ")
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    val Array(n, h) = readLine.split(" ").map(_.toInt)
    val people = readLine.split(" ").map(_.toInt)
    print(people.count(p => p <= h) + 2 * people.count(p => p > h))
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    val Array(_, h) = Console.readLine().split(" ").map(_.toInt)
    println(Console.readLine().split(" ").map(s => if(s.toInt > h) 2 else 1).sum)
  }
}

import java.util.Scanner

object Main2 extends App {
  val scanner = new Scanner(System.in)
  val personNumber = scanner.nextInt()
  val fenceHeight = scanner.nextInt()
  var personNumberNotGreaterThanFence: Int = 0
  for (_ <- 0 until personNumber) if (scanner.nextInt() <= fenceHeight) personNumberNotGreaterThanFence += 1
  println(personNumber * 2 - personNumberNotGreaterThanFence)
}

object Solution extends App {
  val Array(n, h) = readLine.split(" ").map(_.toInt)
  val hs = readLine.split(" ").map(_.toInt)

  val higher = hs.sorted.dropWhile(_ <= h)

  println(hs.size + higher.size)
}

import scala.io.StdIn._

object TaskA extends App {
  var n :: h :: Nil = readInts
  println(n + readInts.count(_ > h))

  def readInts = readLine.split(" ").map(_.toInt).toList
}


You are given two arrays of integers $$$a_1,\ldots,a_n$$$ and $$$b_1,\ldots,b_m$$$.Your task is to find a non-empty array $$$c_1,\ldots,c_k$$$ that is a subsequence of $$$a_1,\ldots,a_n$$$, and also a subsequence of $$$b_1,\ldots,b_m$$$. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, find any. If there are no such arrays, you should report about it.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero) elements. For example, $$$[3,1]$$$ is a subsequence of $$$[3,2,1]$$$ and $$$[4,3,1]$$$, but not a subsequence of $$$[1,3,3,7]$$$ and $$$[3,10,4]$$$.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 1000$$$)  — the number of test cases. Next $$$3t$$$ lines contain descriptions of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 1000$$$)  — the lengths of the two arrays. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$1\le a_i\le 1000$$$)  — the elements of the first array. The third line of each test case contains $$$m$$$ integers $$$b_1,\ldots,b_m$$$ ($$$1\le b_i\le 1000$$$)  — the elements of the second array. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ across all test cases does not exceed $$$1000$$$ ($$$\sum\limits_{i=1}^t n_i, \sum\limits_{i=1}^t m_i\le 1000$$$).

For each test case, output "YES" if a solution exists, or "NO" otherwise. If the answer is "YES", on the next line output an integer $$$k$$$ ($$$1\le k\le 1000$$$)  — the length of the array, followed by $$$k$$$ integers $$$c_1,\ldots,c_k$$$ ($$$1\le c_i\le 1000$$$)  — the elements of the array. If there are multiple solutions with the smallest possible $$$k$$$, output any.

NoteIn the first test case, $$$[4]$$$ is a subsequence of $$$[10, 8, 6, 4]$$$ and $$$[1, 2, 3, 4, 5]$$$. This array has length $$$1$$$, it is the smallest possible length of a subsequence of both $$$a$$$ and $$$b$$$.In the third test case, no non-empty subsequences of both $$$[3]$$$ and $$$[2]$$$ exist, so the answer is "NO".

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val m = in.nextInt()
      val d = in.nextInt()

      val number1 = in.line().split(" ").map(_.toInt)
      val number2 = in.line().split(" ").map(_.toInt)

      val t = number1.find(number2.contains)

      if (t.isDefined) {
        println("YES")
        println(s"1 ${t.get}")
      } else {
        println("NO")
      }
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


Little Paul wants to learn how to play piano. He already has a melody he wants to start with. For simplicity he represented this melody as a sequence $$$a_1, a_2, \ldots, a_n$$$ of key numbers: the more a number is, the closer it is to the right end of the piano keyboard.Paul is very clever and knows that the essential thing is to properly assign fingers to notes he's going to play. If he chooses an inconvenient fingering, he will then waste a lot of time trying to learn how to play the melody by these fingers and he will probably not succeed.Let's denote the fingers of hand by numbers from $$$1$$$ to $$$5$$$. We call a fingering any sequence $$$b_1, \ldots, b_n$$$ of fingers numbers. A fingering is convenient if for all $$$1\leq i \leq n - 1$$$ the following holds:  if $$$a_i < a_{i+1}$$$ then $$$b_i < b_{i+1}$$$, because otherwise Paul needs to take his hand off the keyboard to play the $$$(i+1)$$$-st note;  if $$$a_i > a_{i+1}$$$ then $$$b_i > b_{i+1}$$$, because of the same;  if $$$a_i = a_{i+1}$$$ then $$$b_i\neq b_{i+1}$$$, because using the same finger twice in a row is dumb. Please note that there is $$$\neq$$$, not $$$=$$$ between $$$b_i$$$ and $$$b_{i+1}$$$. Please provide any convenient fingering or find out that there is none.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) denoting the number of notes. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$) denoting the positions of notes on the keyboard.

If there is no convenient fingering, print $$$-1$$$. Otherwise, print $$$n$$$ numbers $$$b_1, b_2, \ldots, b_n$$$, each from $$$1$$$ to $$$5$$$, denoting a convenient fingering, separated by spaces.

NoteThe third sample test is kinda "Non stop" song by Reflex.

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 A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
      else if (d > 0) 1
      else -1
    }

    val All = 1 to 5
    val Mid = Seq(3, 2, 4, 1, 5)

    def filter(i: Int) = {
      C(i) match {
        case 0 => All filterNot (_ == B(i))
        case 1 => B(i) + 1 to 5
        case -1 => 1 until B(i)
      }
    }

    def pick(i: Int, range: IndexedSeq[Int]) = {
      C(i) match {
        case 0 => Mid.find(range.contains).get
        case 1 => range.head
        case -1 => range.last
      }
    }

    def allocate(): Boolean = {
      B(0) = pick(0, All)

      rep(N - 2) { i =>
        val range = filter(i)
        if (range.isEmpty) return false
        B(i + 1) = pick(i + 1, range)
      }

      val rangeN = filter(N - 2)
      if (rangeN.isEmpty) return false
      B(N - 1) = rangeN.head

      true
    }

    if (N == 1) {
      out.println(1)
    } else {
      val ok = allocate()

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-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 C extends App {

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

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

  var min = 1
  var max = 5

  val dp = Array.fill(n, 5)(-1)
  for (j <- 0 until 5) dp(0)(j) = 0

  for (i <- 1 until n) {
    var prev = 0
    while (prev < 5) {
      if (dp(i - 1)(prev) >= 0) {
        var b = 0
        while (b < 5) {
          if (as(i - 1) < as(i) && prev < b) dp(i)(b) = prev
          if (as(i - 1) > as(i) && prev > b) dp(i)(b) = prev
          if (as(i - 1) == as(i) && prev != b) dp(i)(b) = prev
          b += 1
        }
      }
      prev += 1
    }
  }
//dp.foreach(d => println(d.mkString(" ")))
  val solved = dp.last.indexWhere(_ >= 0)
  if (solved == -1) {
    println(-1)
  } else {

    val bs = Array.ofDim[Int](n)
    var b = solved
    for (i <- n - 1 to 0 by -1) {
      bs(i) = b + 1
      b = dp(i)(b)
    }

    Console.setOut(new java.io.BufferedOutputStream(Console.out))

    println(bs.mkString(" "))

    Console.flush
  }
}

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 A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
        else if (d > 0) 1
        else -1
    }

    if (N == 1) {
      out.println(1)
    } else {
      B(0) = C(0) match {
        case 0 => 2
        case 1 => 1
        case -1 => 5
      }

      rep(N - 2) { i =>
        val c0 = C(i)
        val c1 = C(i + 1)
        val b = (c0, c1) match {
          case (0, 0) => if (B(i) != 2) 2 else 3
          case (0, 1) => if (B(i) != 1) 1 else 2
          case (0, -1) => if (B(i) != 5) 5 else 4

          case (1, 0) => if (B(i) != 2) 2 else 3
          case (1, 1) => B(i) + 1
          case (1, -1) => 5

          case (-1, 0) => if (B(i) != 2) 2 else 3
          case (-1, 1) => 1
          case (-1, -1) => B(i) - 1
        }
        B(i + 1) = b
      }

      B(N - 1) = C(N - 2) match {
        case 0 => if (B(N - 2) != 2) 2 else 3
        case 1 => B(N - 2) + 1
        case -1 => B(N - 2) - 1
      }

      val ok = (0 until N - 2 forall { i =>
        C(i) match {
          case 0 => B(i) != B(i + 1)
          case 1 => B(i) < B(i + 1)
          case -1 => B(i) > B(i + 1)
        }
      }) && B.forall(b => 1 <= b && b <= 5)

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-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 A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
      else if (d > 0) 1
      else -1
    }

    val All = 1 to 5

    def filter(i: Int) = {
      C(i) match {
        case 0 => All filterNot (_ == B(i))
        case 1 => B(i) + 1 to 5
        case -1 => 1 until B(i)
      }
    }

    def pick(i: Int, range: IndexedSeq[Int]) = {
      C(i) match {
        case 0 => range(range.length / 2)
        case 1 => range.head
        case -1 => range.last
      }
    }

    def allocate(): Boolean = {
      B(0) = pick(0, All)

      rep(N - 2) { i =>
        val range = filter(i)
        if (range.isEmpty) return false
        B(i + 1) = pick(i + 1, range)
      }

      val rangeN = filter(N - 2)
      if (rangeN.isEmpty) return false
      B(N - 1) = rangeN.head

      true
    }

    if (N == 1) {
      out.println(1)
    } else {
      val ok = allocate()

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-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 A = na(N)
    val B = Array.ofDim[Int](N)
    val C = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      val d = A(i + 1) - A(i)
      C(i) = if (d == 0) 0
        else if (d > 0) 1
        else -1
    }

    if (N == 1) {
      out.println(1)
    } else {
      B(0) = C(0) match {
        case 0 => 2
        case 1 => 1
        case -1 => 5
      }

      rep(N - 2) { i =>
        val c0 = C(i)
        val c1 = C(i + 1)
        val b = (c0, c1) match {
          case (0, 0) => if (B(i) != 2) 2 else 3
          case (0, 1) => if (B(i) != 1) 1 else 2
          case (0, -1) => if (B(i) != 5) 5 else 4

          case (1, 0) => if (B(i) != 2) 2 else 3
          case (1, 1) => B(i) + 1
          case (1, -1) => 5

          case (-1, 0) => if (B(i) != 2) 2 else 3
          case (-1, 1) => 1
          case (-1, -1) => B(i) - 1
        }
        B(i + 1) = b
      }

      B(N - 1) = C(N - 2) match {
        case 0 => if (B(N - 2) != 2) 2 else 3
        case 1 => B(N - 2) + 1
        case -1 => B(N - 2) - 1
      }

      val ok = (0 until N - 1 forall { i =>
        C(i) match {
          case 0 => B(i) != B(i + 1)
          case 1 => B(i) < B(i + 1)
          case -1 => B(i) > B(i + 1)
        }
      }) && B.forall(b => 1 <= b && b <= 5)

      if (ok) {
        out.println(B.mkString(" "))
      } else {
        out.println(-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
  }
}


You are given two sequences $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$. Each element of both sequences is either $$$0$$$, $$$1$$$ or $$$2$$$. The number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$a$$$ is $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ respectively, and the number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$b$$$ is $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ respectively.You can rearrange the elements in both sequences $$$a$$$ and $$$b$$$ however you like. After that, let's define a sequence $$$c$$$ as follows:$$$c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}$$$You'd like to make $$$\sum_{i=1}^n c_i$$$ (the sum of all elements of the sequence $$$c$$$) as large as possible. What is the maximum possible sum?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \le x_1, y_1, z_1 \le 10^8$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$a$$$. The second line of each test case also contains three integers $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \le x_2, y_2, z_2 \le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$b$$$.

For each test case, print the maximum possible sum of the sequence $$$c$$$.

import scala.io.StdIn

object Solution2 extends App {

  val t = StdIn.readLine().toInt

  val cases = for {
    _ <- 0 until t
  } yield (StdIn.readLine().split(" ").map(_.toInt), StdIn.readLine().split(" ").map(_.toInt))

  for {
    c <- cases
  } {
    var (Array(z1, y1, x1), Array(z2, y2, x2)) = c

    var sum = 0
    val twosWithOnes = Math.min(x1, y2)
    sum += twosWithOnes * 2
    x1 -= twosWithOnes
    y2 -= twosWithOnes

    val twosWithTwos = Math.min(x1, x2)
    x1 -= twosWithTwos
    x2 -= twosWithTwos
  //  println("burn twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    // burn twos in second
    val zeros = Math.min(z1, x2)
    x2 -= zeros
    z1 -= zeros

  //  println("burn zeros", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    val OnesWithTwos = Math.min(y1, x2)
    y1 -= OnesWithTwos
    x2 -= OnesWithTwos
    sum -= OnesWithTwos * 2

    //println("burn other twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    //println("final", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    println(sum)
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x1, y1, z1) = readLine().split(" ").map(_.toInt) // a: 0, 1, 2
    val Array(x2, y2, z2) = readLine().split(" ").map(_.toInt) // b: 0, 1, 2

    val t1 = z1 min y2
    val t2 = z2 min x1
    val t3 = (z1 - t1) min (z2 - t2)
    val t4 = y1 min (z2 - t2 - t3)

    val ans = 2L * (t1 - t4)

    println(ans)
  }
}

object DistanceAxis {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn._
    val input = readInt()
    var i = 0
    while(i < input) {
      var rline = readLine().split(" ")
      var a0 = rline(0).toInt
      var a1 = rline(1).toInt
      var a2 = rline(2).toInt
      rline = readLine().split(" ")
      var b0 = rline(0).toInt
      var b1 = rline(1).toInt
      var b2 = rline(2).toInt
      val usedMaxa2b1 = math.min(a2, b1)
      val result = 2 * usedMaxa2b1 - 2 * math.max(0, (a1 - (b0 + b1 - usedMaxa2b1)))
      println(result)
      i += 1
    }
  }
}

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      var a0 = in.nextInt()
      var a1 = in.nextInt()
      var a2 = in.nextInt()

      var b0 = in.nextInt()
      var b1 = in.nextInt()
      var b2 = in.nextInt()

      var tem = 0
      // a2
      var result = {
        tem = math.min(a2, b1)
        a2 = a2 - tem
        b1 = b1 - tem
        tem * 2
      }
      {
        tem = math.min(a2, b2) // zero
        a2 = a2 - tem
        b2 = b2 - tem
      }
      {
        tem = math.min(a2, b0) // zero
        a2 = a2 - tem
        b0 = b0 - tem
      }
      // a1
      {
        tem = math.min(a1, b1) // zero
        a1 = a1 - tem
        b1 = b1 - tem
      }
      {
        tem = math.min(a1, b0) // zero
        a1 = a1 - tem
        b0 = b0 - tem
      }
      result = result + {
        tem = math.min(a1, b2) // zero
        a1 = a1 - tem
        b2 = b2 - tem
        tem * 2 * -1
      }
      // a0
      {
        tem = math.min(a0, b2) // zero
        a0 = a0 - tem
        b2 = b2 - tem
      }
      {
        tem = math.min(a0, b1) // zero
        a0 = a0 - tem
        b1 = b1 - tem
      }
      {
        tem = math.min(a0, b0) // zero
        a0 = a0 - tem
        b0 = b0 - tem
      }
      println(result)
//      val connectivity = Array.ofDim[Boolean](airports, airports)

    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] =
      current.find(_.hasMoreTokens) orElse {
        current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
        current
      }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

    def nextDouble(): Double = next().toDouble

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

import scala.io.StdIn

object Solution2 extends App {

  val t = StdIn.readLine().toInt

  val cases = for {
    _ <- 0 until t
  } yield (StdIn.readLine().split(" ").map(_.toInt), StdIn.readLine().split(" ").map(_.toInt))

  for {
    c <- cases
  } {
    var (Array(z1, y1, x1), Array(z2, y2, x2)) = c

    var sum = 0
    val twosWithOnes = Math.min(x1, y2)
    sum += twosWithOnes * 2
    x1 -= twosWithOnes
    y2 -= twosWithOnes
  //  println("burn twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    // burn twos in second
    val zeros = Math.min(z1, x2)
    x2 -= zeros
    z1 -= zeros

  //  println("burn zeros", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)

    val OnesWithTwos = Math.min(y1, x2)
    y1 -= OnesWithTwos
    x2 -= OnesWithTwos
    sum -= OnesWithTwos * 2

    //println("burn other twos", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    //println("final", sum, "a=", x1, y2, z1, " b= ", x2, y2, z2)
    println(sum)
  }

}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(x1, y1, z1) = readLine().split(" ").map(_.toInt) // a: 0, 1, 2
    val Array(x2, y2, z2) = readLine().split(" ").map(_.toInt) // b: 0, 1, 2

    val ans = 2L * ((z1 min y2) - ((z2 - (z2 min x1)) min y1))

    println(ans)
  }
}


In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.

The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.

Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.  If there is no valid common subsequence, output 0.

import scala.collection.immutable.StringOps
import scala.util.control.Breaks._

object Main {

  def kmpMatch(s: StringOps): Array[Int] = {
    val n = s.length
    val ret = (1 to n).map(_ => -1).toArray
    for (i <- 0 to n - 1) {
      var j = i - 1
      breakable {
        while (j != -1) {
          if (s(ret(j) + 1) == s(i)) {
            break
          }
          j = ret(j)
        }
      }
      if (j != -1) {
        ret.update(i, ret(j) + 1)
      }
    }
    return ret
  }

  def solve(s: StringOps, t: StringOps, virus: StringOps): String = {
    def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {
      if (x == 0 || y == 0) {
        return ""
      }
      if (rec(x)(y)(z) == 0) {
        return build(x - 1, y, z, rec)
      } else if (rec(x)(y)(z) == 1) {
        return build(x, y - 1, z, rec)
      } else {
        return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))
      }
    }
    val ns = s.length
    val nt = t.length
    val nv = virus.length
    val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val kmp = kmpMatch(virus)
    for (i <- 0 to ns) {
      dp(i)(0)(0) = 0
    }
    for (j <- 0 to nt) {
      dp(0)(j)(0) = 0
    }
    for (i <- 0 to ns - 1) {
      for (j <- 0 to nt - 1) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) != -1) {
            if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {
              rec(i + 1)(j)(k) = 0
              dp(i + 1)(j)(k) = dp(i)(j)(k)
            }
            if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {
              rec(i)(j + 1)(k) = 1
              dp(i)(j + 1)(k) = dp(i)(j)(k)
            }
            if (s(i) == t(j)) {
              var idx = k - 1
              breakable {
                while (idx != -1) {
                  if (virus(idx + 1) == s(i)) {
                    break
                  }
                  idx = kmp(idx)
                }
              }
              if (virus(idx + 1) == s(i)) {
                idx = idx + 1
              }
              if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {
                rec(i + 1)(j + 1)(idx + 1) = -(k + 1)
                dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1
              }
            }
          }
        }
      }
    }
    var r = -1
    var x = -1
    var y = -1
    var z = -1
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) > r) {
            r = dp(i)(j)(k)
            x = i
            y = j
            z = k
          }
        }
      }
    }
    return if (r > 0) build(x, y, z, rec) else "0"
  }

  def main(args: Array[String]) {
    val s = readLine()
    val t = readLine()
    val virus = readLine()
    println(solve(s, t, virus))
  }

}

import scala.collection.immutable.StringOps
import scala.util.control.Breaks._

object Main {

  def kmpMatch(s: StringOps): Array[Int] = {
    val n = s.length
    val ret = (1 to n).map(_ => -1).toArray
    for (i <- 0 to n - 1) {
      var j = i - 1
      breakable {
        while (j != -1) {
          if (s(ret(j) + 1) == s(i)) {
            break
          }
          j = ret(j)
        }
      }
      if (j != -1) {
        ret.update(i, ret(j) + 1)
      }
    }
    return ret
  }

  def solve(s: StringOps, t: StringOps, virus: StringOps): String = {
    def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {
      if (x == 0 || y == 0) {
        return ""
      }
      if (rec(x)(y)(z) == 0) {
        return build(x - 1, y, z, rec)
      } else if (rec(x)(y)(z) == 1) {
        return build(x, y - 1, z, rec)
      } else {
        return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))
      }
    }
    val ns = s.length
    val nt = t.length
    val nv = virus.length
    val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val kmp = kmpMatch(virus)
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        dp(i)(j)(0) = 0
      }
    }
    for (i <- 0 to ns - 1) {
      for (j <- 0 to nt - 1) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) != -1) {
            if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {
              rec(i + 1)(j)(k) = 0
              dp(i + 1)(j)(k) = dp(i)(j)(k)
            }
            if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {
              rec(i)(j + 1)(k) = 1
              dp(i)(j + 1)(k) = dp(i)(j)(k)
            }
            if (s(i) == t(j)) {
              var idx = k
              breakable {
                while (idx != -1) {
                  if (virus(idx) == s(i)) {
                    break
                  }
                  idx = kmp(idx)
                }
              }
              if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {
                rec(i + 1)(j + 1)(idx + 1) = -(k + 1)
                dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1
              }
            }
          }
        }
      }
    }
    var r = -1
    var x = -1
    var y = -1
    var z = -1
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) > r) {
            r = dp(i)(j)(k)
            x = i
            y = j
            z = k
          }
        }
      }
    }
    return if (r > 0) build(x, y, z, rec) else "0"
  }

  def main(args: Array[String]) {
    val s = readLine()
    val t = readLine()
    val virus = readLine()
    println(solve(s, t, virus))
  }

}

import scala.collection.immutable.StringOps
import scala.util.control.Breaks._

object Main {

  def kmpMatch(s: StringOps): Array[Int] = {
    val n = s.length
    val ret = (1 to n).map(_ => -1).toArray
    for (i <- 0 to n - 1) {
      var j = i - 1
      breakable {
        while (j != -1) {
          if (s(ret(j) + 1) == s(i)) {
            break
          }
          j = ret(j)
        }
      }
      if (j != -1) {
        ret.update(i, ret(j) + 1)
      }
    }
    return ret
  }

  def solve(s: StringOps, t: StringOps, virus: StringOps): String = {
    def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {
      if (x == 0 || y == 0) {
        return ""
      }
      if (rec(x)(y)(z) == 0) {
        return build(x - 1, y, z, rec)
      } else if (rec(x)(y)(z) == 1) {
        return build(x, y - 1, z, rec)
      } else {
        return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))
      }
    }
    val ns = s.length
    val nt = t.length
    val nv = virus.length
    val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val kmp = kmpMatch(virus)
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        dp(i)(j)(0) = 0
      }
    }
    for (i <- 0 to ns - 1) {
      for (j <- 0 to nt - 1) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) != -1) {
            if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {
              rec(i + 1)(j)(k) = 0
              dp(i + 1)(j)(k) = dp(i)(j)(k)
            }
            if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {
              rec(i)(j + 1)(k) = 1
              dp(i)(j + 1)(k) = dp(i)(j)(k)
            }
            if (s(i) == t(j)) {
              var idx = k
              breakable {
                while (idx != -1) {
                  if (virus(idx) == s(i)) {
                    break
                  }
                  idx = kmp(idx)
                }
              }
              if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {
                rec(i + 1)(j + 1)(idx + 1) = -(k + 1)
                dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1
              }
            }
          }
        }
      }
    }
    var r = -1
    var x = -1
    var y = -1
    var z = -1
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) > r) {
            r = dp(i)(j)(k)
            x = i
            y = j
            z = k
          }
        }
      }
    }
    return build(x, y, z, rec)
  }

  def main(args: Array[String]) {
    val s = readLine()
    val t = readLine()
    val virus = readLine()
    println(solve(s, t, virus))
  }

}

import scala.collection.immutable.StringOps
import scala.util.control.Breaks._

object Main {

  def kmpMatch(s: StringOps): Array[Int] = {
    val n = s.length
    val ret = (1 to n).map(_ => -1).toArray
    for (i <- 0 to n - 1) {
      var j = i - 1
      breakable {
        while (j != -1) {
          if (s(ret(j) + 1) == s(i)) {
            break
          }
          j = ret(j)
        }
      }
      if (j != -1) {
        ret.update(i, ret(j) + 1)
      }
    }
    return ret
  }

  def solve(s: StringOps, t: StringOps, virus: StringOps): String = {
    def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {
      if (x == 0 || y == 0) {
        return ""
      }
      if (rec(x)(y)(z) == 0) {
        return build(x - 1, y, z, rec)
      } else if (rec(x)(y)(z) == 1) {
        return build(x, y - 1, z, rec)
      } else {
        return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))
      }
    }
    val ns = s.length
    val nt = t.length
    val nv = virus.length
    val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val kmp = kmpMatch(virus)
    for (i <- 0 to ns) {
      dp(i)(0)(0) = 0
    }
    for (j <- 0 to nt) {
      dp(0)(j)(0) = 0
    }
    for (i <- 0 to ns - 1) {
      for (j <- 0 to nt - 1) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) != -1) {
            if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {
              rec(i + 1)(j)(k) = 0
              dp(i + 1)(j)(k) = dp(i)(j)(k)
            }
            if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {
              rec(i)(j + 1)(k) = 1
              dp(i)(j + 1)(k) = dp(i)(j)(k)
            }
            if (s(i) == t(j)) {
              var idx = k
              breakable {
                while (idx != -1) {
                  if (virus(idx) == s(i)) {
                    break
                  }
                  idx = kmp(idx)
                }
              }
              if (idx < nv - 1 && virus(idx + 1) == s(i)) {
                idx = idx + 1
              }
              if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {
                rec(i + 1)(j + 1)(idx + 1) = -(k + 1)
                dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1
              }
            }
          }
        }
      }
    }
    var r = -1
    var x = -1
    var y = -1
    var z = -1
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) > r) {
            r = dp(i)(j)(k)
            x = i
            y = j
            z = k
          }
        }
      }
    }
    return if (r > 0) build(x, y, z, rec) else "0"
  }

  def main(args: Array[String]) {
    val s = readLine()
    val t = readLine()
    val virus = readLine()
    println(solve(s, t, virus))
  }

}

import scala.collection.immutable.StringOps
import scala.util.control.Breaks._

object Main {

  def kmpMatch(s: StringOps): Array[Int] = {
    val n = s.length
    val ret = (1 to n).map(_ => -1).toArray
    for (i <- 0 to n - 1) {
      var j = i - 1
      breakable {
        while (j != -1) {
          if (s(ret(j) + 1) == s(i)) {
            break
          }
          j = ret(j)
        }
      }
      if (j != -1) {
        ret.update(i, ret(j) + 1)
      }
    }
    return ret
  }

  def solve(s: StringOps, t: StringOps, virus: StringOps): String = {
    def build(x: Int, y: Int, z: Int, rec: Array[Array[Array[Int]]]): String = {
      if (x == 0 || y == 0) {
        return ""
      }
      if (rec(x)(y)(z) == 0) {
        return build(x - 1, y, z, rec)
      } else if (rec(x)(y)(z) == 1) {
        return build(x, y - 1, z, rec)
      } else {
        return build(x - 1, y - 1, -rec(x)(y)(z) - 1, rec).:+(s(x - 1))
      }
    }
    val ns = s.length
    val nt = t.length
    val nv = virus.length
    val dp = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val rec = Array.fill[Int](ns + 1, nt + 1, nv + 1)(-1)
    val kmp = kmpMatch(virus)
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        dp(i)(0)(0) = 0
        dp(0)(j)(0) = 0
      }
    }
    for (i <- 0 to ns - 1) {
      for (j <- 0 to nt - 1) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) != -1) {
            if (dp(i)(j)(k) > dp(i + 1)(j)(k)) {
              rec(i + 1)(j)(k) = 0
              dp(i + 1)(j)(k) = dp(i)(j)(k)
            }
            if (dp(i)(j)(k) > dp(i)(j + 1)(k)) {
              rec(i)(j + 1)(k) = 1
              dp(i)(j + 1)(k) = dp(i)(j)(k)
            }
            if (s(i) == t(j)) {
              var idx = k
              breakable {
                while (idx != -1) {
                  if (virus(idx) == s(i)) {
                    break
                  }
                  idx = kmp(idx)
                }
              }
              if (dp(i)(j)(k) + 1 > dp(i + 1)(j + 1)(idx + 1)) {
                rec(i + 1)(j + 1)(idx + 1) = -(k + 1)
                dp(i + 1)(j + 1)(idx + 1) = dp(i)(j)(k) + 1
              }
            }
          }
        }
      }
    }
    var r = -1
    var x = -1
    var y = -1
    var z = -1
    for (i <- 0 to ns) {
      for (j <- 0 to nt) {
        for (k <- 0 to nv - 1) {
          if (dp(i)(j)(k) > r) {
            r = dp(i)(j)(k)
            x = i
            y = j
            z = k
          }
        }
      }
    }
    return if (r > 0) build(x, y, z, rec) else "0"
  }

  def main(args: Array[String]) {
    val s = readLine()
    val t = readLine()
    val virus = readLine()
    println(solve(s, t, virus))
  }

}


Given $$$n$$$, find any array $$$a_1, a_2, \ldots, a_n$$$ of integers such that all of the following conditions hold: $$$1 \le a_i \le 10^9$$$ for every $$$i$$$ from $$$1$$$ to $$$n$$$.$$$a_1 < a_2 < \ldots <a_n$$$For every $$$i$$$ from $$$2$$$ to $$$n$$$, $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$It can be shown that such an array always exists under the constraints of the problem.

The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ — the array you found. If there are multiple arrays satisfying all the conditions, print any of them.

NoteIn the first test case, array $$$[1]$$$ satisfies all the conditions.In the second test case, array $$$[2, 3]$$$ satisfies all the conditions, as $$$2<3$$$ and $$$3$$$ is not divisible by $$$2$$$.In the third test case, array $$$[111, 1111, 11111, 111111, 1111111, 11111111, 111111111]$$$ satisfies all the conditions, as it's increasing and $$$a_i$$$ isn't divisible by $$$a_{i-1}$$$ for any $$$i$$$ from $$$2$$$ to $$$7$$$.

import scala.io.StdIn._
object Main extends App {
    var a = readInt
    for(k<-1 to a){
        val n = readInt
        for(i<-2 to n+1){
            print(i+" ")
        }
        print("\n")
    }
}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

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

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(val a: Int, val b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return -1 * a.compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 998244353L
    val maxn = 200010
    val mp = mutable.Map[Char, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        for (i <- 1 to n) {
            writer.print(i+1 + " ")
        }
        writer.println()

        def check(kk: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long): Long = {
            if (en - st <= 1L) {
                if (check(st))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid))
                return bs(st, mid)
            else
                return bs(mid, en)
        }
    }
    writer.flush()
}