During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.You are given a sequence $$$a$$$, consisting of $$$n$$$ distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process.  First element $$$a_1$$$ becomes the root of the tree.  Elements $$$a_2, a_3, \ldots, a_n$$$ are added one by one. To add element $$$a_i$$$ one needs to traverse the tree starting from the root and using the following rules:   The pointer to the current node is set to the root.  If $$$a_i$$$ is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node.  If at some point there is no required child, the new node is created, it is assigned value $$$a_i$$$ and becomes the corresponding child of the current node.

The first line of the input contains a single integer $$$n$$$ ($$$2 \leq n \leq 100\,000$$$) — the length of the sequence $$$a$$$. The second line contains $$$n$$$ distinct integers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) — the sequence $$$a$$$ itself.

Output $$$n - 1$$$ integers. For all $$$i > 1$$$ print the value written in the node that is the parent of the node with value $$$a_i$$$ in it.

import scala.collection.immutable.TreeMap
import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toInt)
    val ans = new Array[Int](n)
    var par = TreeMap[Int, Int]()
    val INF = 2000000000
    par += (INF -> a(0))
    for (i <- 1 until n) {
      val r = par.from(a(i)).firstKey
      val p = par(r)
      ans(i) = p
      par -= r
      if (a(i) < p) {
        par += (p -> a(i))
        if (r != p) par += (r -> p)
      } else if (a(i) > p) {
        if (!(par contains p)) par += (p -> p)
        par += (r -> a(i))
      } else {
        assert(false)
      }
    }
    println(ans.drop(1).mkString(" "))
  }
}

import scala.collection.immutable.TreeMap
import scala.io.StdIn

object Main {
  def main(args: Array[String]) {
    val n = StdIn.readInt()
    val a = StdIn.readLine().split(" ").map(_.toInt)
    val ans = new Array[Int](n)
    var par = TreeMap[Int, Int]()
    val INF = 2000000000
    par += (INF -> a(0))
    for (i <- 1 until n) {
      val r = par.from(a(i)).firstKey
      val p = par(r)
      ans(i) = p
      par -= r
      if (a(i) < p) {
        if (!(par contains p)) par += (p -> a(i))
        par += (r -> p)
      } else if (a(i) > p) {
        if (!(par contains p)) par += (p -> p)
        par += (r -> a(i))
      } else {
        assert(false)
      }
    }
    println(ans.drop(1).mkString(" "))
  }
}


Vasya has a multiset $$$s$$$ consisting of $$$n$$$ integer numbers. Vasya calls some number $$$x$$$ nice if it appears in the multiset exactly once. For example, multiset $$$\{1, 1, 2, 3, 3, 3, 4\}$$$ contains nice numbers $$$2$$$ and $$$4$$$.Vasya wants to split multiset $$$s$$$ into two multisets $$$a$$$ and $$$b$$$ (one of which may be empty) in such a way that the quantity of nice numbers in multiset $$$a$$$ would be the same as the quantity of nice numbers in multiset $$$b$$$ (the quantity of numbers to appear exactly once in multiset $$$a$$$ and the quantity of numbers to appear exactly once in multiset $$$b$$$).

The first line contains a single integer $$$n~(2 \le n \le 100)$$$. The second line contains $$$n$$$ integers $$$s_1, s_2, \dots s_n~(1 \le s_i \le 100)$$$ — the multiset $$$s$$$.

If there exists no split of $$$s$$$ to satisfy the given requirements, then print "NO" in the first line. Otherwise print "YES" in the first line. The second line should contain a string, consisting of $$$n$$$ characters. $$$i$$$-th character should be equal to 'A' if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$a$$$ and 'B' if if the $$$i$$$-th element of multiset $$$s$$$ goes to multiset $$$b$$$. Elements are numbered from $$$1$$$ to $$$n$$$ in the order they are given in the input. If there exist multiple solutions, then print any of them.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = na(N)
    val cnt = Array.ofDim[Int](101)
    S foreach (a => cnt(a) += 1)
    val ones = cnt.zipWithIndex collect { case (1, i) => i }
    val twos = cnt.zipWithIndex collect { case (2, i) => i }
    val threes = cnt.zipWithIndex collect { case (cnt, i) if cnt >= 3 => i }

    if (ones.length % 2 == 1 && threes.length == 0) {
      out.println("NO")
    } else {
      out.println("YES")

      val X = Array.fill[ArrayBuffer[Int]](2)(ArrayBuffer())
      rep(ones.length) { i =>
        val x = i % 2
        X(x) += ones(i)
      }

      rep(twos.length) { i =>
        X(0) += twos(i)
        X(0) += twos(i)
      }

      if (ones.length % 2 == 1) {
        val h = threes.head

        // oneはX(0)に１こ余計にはいっているので調整する
        X(1) += h
        rep(cnt(h) - 1)(_ => X(0) += h)

        rep(threes.length - 1, 1) { i =>
          val s = threes(i)
          rep(cnt(s))(_ => X(0) += s)
        }
      } else {
        rep(threes.length) { i =>
          val s = threes(i)
          rep(cnt(s))(_ => X(0) += s)
        }
      }

      rep(N) { i =>
        val s = S(i)
        if (X(0) contains s) {
          X(0) -= s
          out.print('A')
        } else {
          X(1) -= s
          out.print('B')
        }
      }
      out.println()
    }
  }

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

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

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

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

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


You are given an array $$$a$$$, consisting of $$$n$$$ positive integers.Let's call a concatenation of numbers $$$x$$$ and $$$y$$$ the number that is obtained by writing down numbers $$$x$$$ and $$$y$$$ one right after another without changing the order. For example, a concatenation of numbers $$$12$$$ and $$$3456$$$ is a number $$$123456$$$.Count the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$2 \le k \le 10^9$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print a single integer — the number of ordered pairs of positions $$$(i, j)$$$ ($$$i \neq j$$$) in array $$$a$$$ such that the concatenation of $$$a_i$$$ and $$$a_j$$$ is divisible by $$$k$$$.

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, K = sc.nextInt()
    val A = map(N)(_ => sc.nextInt())
    val M = Array.fill[mutable.Map[Int, Int]](11)(mutable.Map() withDefaultValue 0)
    val len = Array.ofDim[Int](N)

    val pow = Array.ofDim[Long](11)
    pow(0) = 1
    rep(10) { i => pow(i + 1) = pow(i) * 10 % K}

    def digits(x: Int): Int = {
      var d = 0
      var a = x
      while(a > 0) { a /= 10; d += 1}
      d
    }

    rep(N) { i =>
      val m = A(i) % K
      val d = digits(A(i))
      len(i) = d
      M(d)(m) = M(d)(m) + 1
    }

    var ans = 0L
    rep(N) { i =>
      rep(11) { d =>
        val m = (pow(d) * A(i) % K).toInt
        val r = if (m == 0) 0 else K - m
        ans += M(d)(r)
        if (d == len(i) && r == A(i) % K) ans -= 1
      }
    }

    out.println(ans)
  }

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

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

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

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

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

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

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

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

object D extends App {

  def countLen(x: Long): Int = {
    var l = 0
    var xx = x
    while (xx > 0) {
      xx = xx / 10
      l += 1
    }
    l
  }

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val k = in.nextLong
    val a = Array.fill(n)(in.nextLong)
    val map = scala.collection.mutable.Map[(Long, Int), Int]()
    a.foreach { v =>
      val key = (v % k, countLen(v))
      //println(key)
      map += key -> (map.getOrElse(key, 0) + 1)
    }
    var ans: Long = 0
    for {v <- a
         i <- 1 to 10
    } {
      //println((k - v * math.pow(10, i).toLong % k) % k -> i)
      ans += map.getOrElse((k - (v % k) * (math.pow(10, i) % k).toLong % k) % k -> i
        , 0
      )
    }
    //println(ans)
    a.foreach { v =>
      if (((v % k) + (v % k) * (math.pow(10, countLen(v)) % k)) % k == 0)
        ans -= 1
    }
    println(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Long = {
      next.toInt
    }

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

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

}

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, K = sc.nextInt()
    val A = map(N)(_ => sc.nextInt())
    val M = Array.fill[mutable.Map[Int, Int]](11)(mutable.Map() withDefaultValue 0)

    val pow = Array.ofDim[Long](11)
    pow(0) = 1
    rep(10) { i => pow(i + 1) = pow(i) * 10}

    def digits(x: Int): Int = x.toString.length

    rep(N) { i =>
      rep(11) { j =>
        val m = (pow(j) * A(i) % K).toInt
        M(j)(m) = M(j)(m) + 1
      }
    }

    var ans = 0L
    rep(N) { i =>
      val d = digits(A(i))
      val m = (K - A(i) % K) % K
      ans += M(d)(m)
      if (pow(d) * A(i) % K == m) ans -= 1
    }

    out.println(ans)
  }

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

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val sc = new InputReader(System.in)
    val N, K = sc.nextInt()
    val A = map(N)(_ => sc.nextInt())
    val M = Array.ofDim[Int](11, K)

    def digits(x: Int): Int = x.toString.length

    rep(N) { i =>
      rep(11) { j =>
        M(j)((A(i).toLong * pow(10, j) % K).toInt) += 1
      }
    }

    var ans = 0L
    rep(N) { i =>
      val d = digits(A(i))
      val m = (K - A(i) % K) % K
      ans += M(d)(m)
      if (pow(10, d) * A(i) % K == m) ans -= 1
    }

//    case class Seg(l: Int, r: Int) {
//      def length: Int = r - l
//    }
//    val S = map(N) { _ =>
//      val l, r = sc.nextInt()
//      Seg(l, r)
//    }
//
//    def intersect(s1: Seg, s2: Seg): Seg = {
//      Seg(max(s1.l, s2.l), min(s1.r, s2.r))
//    }
//
//    def merge(s1: Seg, s2: Seg): Seg = {
//      ???
//    }
//
//    val ms = S reduce intersect
//    var mx = 0
//    rep(N) { i =>
//      mx = max(mx, merge(S(i), ms).length)
//    }

    out.println(ans)
  }

  def pow(x: Int, n: Int): Int = {
    n match {
      case 0 => 1
      case _ =>
        val r = pow(x * x, n / 2)
        if (n % 2 == 1) r * x else r
    }
  }

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

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

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

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

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

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

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

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

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

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

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

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

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

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

object D extends App {

  def countLen(x: Long): Int = {
    var l = 0
    var xx = x
    while (xx > 0) {
      xx = xx / 10
      l += 1
    }
    l
  }

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val k = in.nextLong
    val a = Array.fill(n)(in.nextLong)
    val map = scala.collection.mutable.Map[(Long, Int), Int]()
    a.foreach { v =>
      val key = (v % k, countLen(v))
      //println(key)
      map += key -> (map.getOrElse(key, 0) + 1)
    }
    var ans: Long = 0
    for {v <- a
         i <- 1 to 10
    } {
      //println(map.get((k - v * math.pow(10, i).toLong % k -> i))
      ans += map.getOrElse((k - v * math.pow(10, i).toLong % k) % k -> i, 0)
    }
    //println(ans)
    a.foreach { v =>
      if ((v + v * math.pow(10, countLen(v))) % k == 0)
        ans -= 1
    }
    println(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Long = {
      next.toInt
    }

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

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

}

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

object D extends App {

  def countLen(x: Long): Int = {
    var l = 0
    var xx = x
    while (xx > 0) {
      xx = xx / 10
      l += 1
    }
    l
  }

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val k = in.nextLong
    val a = Array.fill(n)(in.nextLong)
    val map = scala.collection.mutable.Map[(Long, Int), Int]()
    a.foreach { v =>
      val key = (v % k, countLen(v))
      //println(key)
      map += key -> (map.getOrElse(key, 0) + 1)
    }
    var ans: Long = 0
    for {v <- a
         i <- 1 to 10
    } {
      //println((k - v * math.pow(10, i).toLong % k) % k -> i)
      ans += map.getOrElse((k - (v % k) * math.pow(10, i).toLong % k) % k -> i, 0)
    }
    //println(ans)
    a.foreach { v =>
      if (((v % k) + (v % k) * math.pow(10, countLen(v))) % k == 0)
        ans -= 1
    }
    println(ans)
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

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

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toInt
    }

    def nextLong: Long = {
      next.toInt
    }

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

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

}


There are $$$n$$$ warriors in a row. The power of the $$$i$$$-th warrior is $$$a_i$$$. All powers are pairwise distinct.You have two types of spells which you may cast:   Fireball: you spend $$$x$$$ mana and destroy exactly $$$k$$$ consecutive warriors;  Berserk: you spend $$$y$$$ mana, choose two consecutive warriors, and the warrior with greater power destroys the warrior with smaller power. For example, let the powers of warriors be $$$[2, 3, 7, 8, 11, 5, 4]$$$, and $$$k = 3$$$. If you cast Berserk on warriors with powers $$$8$$$ and $$$11$$$, the resulting sequence of powers becomes $$$[2, 3, 7, 11, 5, 4]$$$. Then, for example, if you cast Fireball on consecutive warriors with powers $$$[7, 11, 5]$$$, the resulting sequence of powers becomes $$$[2, 3, 4]$$$.You want to turn the current sequence of warriors powers $$$a_1, a_2, \dots, a_n$$$ into $$$b_1, b_2, \dots, b_m$$$. Calculate the minimum amount of mana you need to spend on it.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$ and the length of sequence $$$b$$$ respectively. The second line contains three integers $$$x, k, y$$$ ($$$1 \le x, y, \le 10^9; 1 \le k \le n$$$) — the cost of fireball, the range of fireball and the cost of berserk respectively. The third line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that all integers $$$a_i$$$ are pairwise distinct. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_i \le n$$$). It is guaranteed that all integers $$$b_i$$$ are pairwise distinct.

Print the minimum amount of mana for turning the sequnce $$$a_1, a_2, \dots, a_n$$$ into $$$b_1, b_2, \dots, b_m$$$, or $$$-1$$$ if it is impossible.

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

  val Array(n, m)    = readLine().split(" ").map(_.toInt)
  val Array(x, k, y) = readLine().split(" ").map(_.toLong)
  val cheap          = x.min(y * k)
  val an             = readLine().split(" ").map(_.toInt) :+ 0
  val bn             = readLine().split(" ").map(_.toInt) :+ 0

  private def destroy(from: Int, until: Int): Long = {
    val range = until - from
    val count = range / k
    val over  = range % k

//    println(s"from:$from until:$until count:$count over:$over range:$range")

    val warrior   = if (from == 0) an(until) else an(until).max(an(from - 1))
    val i         = an.indexWhere(_ > warrior, from)
    val j         = if (i == -1) until else until.min(i)
    val strongest = an(j)

//    println(s"warrior:$warrior strongest:$strongest")

    if (strongest > warrior) {
      if (count == 0 && over != 0) -1L
      else x + y * over + cheap * (count - 1)
    } else y * over + cheap * count
  }

//  println()

  val ans = bn
    .foldLeft((0L, 0)) {
      case ((-1L, _), _) => (-1L, 0)
      case ((amount, from), b) =>
        val until = an.indexOf(b, from)

        if (until == -1) (-1L, 0)
        else {
          val cost = destroy(from, until)

          if (cost == -1L) (-1L, 0)
          else (amount + cost, until + 1)
        }
    }
    ._1

  println(ans)
}

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

  val Array(n, m)    = readLine().split(" ").map(_.toInt)
  val Array(x, k, y) = readLine().split(" ").map(_.toLong)
  val cheap          = x.min(y * k)
  val an             = readLine().split(" ").map(_.toInt) :+ 0
  val bn             = readLine().split(" ").map(_.toInt) :+ 0

  private def destroy(from: Int, until: Int): Long = {
    val range = until - from
    val count = range / k
    val over  = range % k

//    println(s"from:$from until:$until count:$count over:$over range:$range")

    val warrior   = if (from == 0) an(until) else an(until).max(an(from - 1))
    val i         = an.indexWhere(_ > warrior, from)
    val j         = if (i == -1) until else until.min(i)
    val strongest = an(j)

//    println(s"warrior:$warrior strongest:$strongest")

    if (strongest > warrior) x + y * over + cheap * (count - 1)
    else y * over + cheap * count
  }

//  println()

  val ans = bn
    .foldLeft((0L, 0)) {
      case ((-1L, _), _) => (-1L, 0)
      case ((amount, from), b) =>
        val until = an.indexOf(b, from)

        if (until == -1) (-1L, 0)
        else {
          val cost = destroy(from, until)

          if (cost == -1L) (-1L, 0)
          else (amount + cost, until + 1)
        }
    }
    ._1

  println(ans)
}


To celebrate your birthday you have prepared a festive table! Now you want to seat as many guests as possible.The table can be represented as a rectangle with height $$$h$$$ and width $$$w$$$, divided into $$$h \times w$$$ cells. Let $$$(i, j)$$$ denote the cell in the $$$i$$$-th row and the $$$j$$$-th column of the rectangle ($$$1 \le i \le h$$$; $$$1 \le j \le w$$$).Into each cell of the table you can either put a plate or keep it empty.As each guest has to be seated next to their plate, you can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. Formally, for each cell $$$(i, j)$$$ you put a plate into, at least one of the following conditions must be satisfied: $$$i = 1$$$, $$$i = h$$$, $$$j = 1$$$, $$$j = w$$$.To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if cell $$$(i, j)$$$ contains a plate, you can't put plates into cells $$$(i - 1, j)$$$, $$$(i, j - 1)$$$, $$$(i + 1, j)$$$, $$$(i, j + 1)$$$, $$$(i - 1, j - 1)$$$, $$$(i - 1, j + 1)$$$, $$$(i + 1, j - 1)$$$, $$$(i + 1, j + 1)$$$.Put as many plates on the table as possible without violating the rules above.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each of the following $$$t$$$ lines describes one test case and contains two integers $$$h$$$ and $$$w$$$ ($$$3 \le h, w \le 20$$$) — the height and the width of the table.

For each test case, print $$$h$$$ lines containing $$$w$$$ characters each. Character $$$j$$$ in line $$$i$$$ must be equal to $$$1$$$ if you are putting a plate into cell $$$(i, j)$$$, and $$$0$$$ otherwise. If there are multiple answers, print any. All plates must be put on the edge of the table. No two plates can be put into cells that have a common side or corner. The number of plates put on the table under these conditions must be as large as possible. You are allowed to print additional empty lines.

NoteFor the first test case, example output contains the only way to put $$$6$$$ plates on the table.For the second test case, there are many ways to put $$$4$$$ plates on the table, example output contains one of them.Putting more than $$$6$$$ plates in the first test case or more than $$$4$$$ plates in the second test case is impossible.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(h, w) = readLine().split(" ").map(_.toInt)

    (1 to h).foreach {
      case i if i == 1 || i == h   => println((1 to w).map(_ % 2).mkString(""))
      case i if i > 2 && i < h - 1 => println(s"${i % 2}${"0" * (w - 2)}${i % 2}")
      case _                       => println("0" * w)
    }
    println()
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(h, w) = readLine().split(" ").map(_.toInt)

    (1 to h).foreach {
      case i if i == 1 || i == h   =>
        val row = (1 to w).map(_ % 2).mkString("")
        println(row)
      case i if i > 2 && i < h - 1 =>
        val row = s"${i % 2}" + "0" * (w - 2) + s"${i % 2}"
        println(row)
      case _                       => println("0" * w)
    }
    println()
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(h, w) = readLine().split(" ").map(_.toInt)

    (0 until h).foreach { i =>
      val row = (0 until w).map {
        case j if i == 0 || i == h - 1                         => (j + 1) % 2
        case j if (j == 0 || j == w - 1) && i > 1 && i < h - 2 => (i + 1) % 2
        case _                                                 => 0
      }
      println(row.mkString(""))
    }
    println()
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(h, w) = readLine().split(" ").map(_.toInt)

    (1 to h).foreach {
      case i if i == 1 || i == h   =>
        val row = (1 to w).map(_ % 2).mkString("")
        println(row)
      case i if i > 2 && i < h - 1 =>
        val row = "s${i % 2}" + "0" * (w - 2) + "s${i % 2}"
        println(row)
      case _                       => println("0" * w)
    }
    println()
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(h, w) = readLine().split(" ").map(_.toInt)

    (1 to h).foreach {
      case i if i == 1 || i == h   => (1 to w).map(_ % 2).mkString("")
      case i if i > 2 && i < h - 1 => "s${i % 2}" + "0" * (w - 2) + "s${i % 2}"
      case _                       => "0" * 2
    }
    println()
  }
}


During the hypnosis session, Nicholas suddenly remembered a positive integer $$$n$$$, which doesn't contain zeros in decimal notation. Soon, when he returned home, he got curious: what is the maximum number of digits that can be removed from the number so that the number becomes not prime, that is, either composite or equal to one?For some numbers doing so is impossible: for example, for number $$$53$$$ it's impossible to delete some of its digits to obtain a not prime integer. However, for all $$$n$$$ in the test cases of this problem, it's guaranteed that it's possible to delete some of their digits to obtain a not prime number.Note that you cannot remove all the digits from the number.A prime number is a number that has no divisors except one and itself. A composite is a number that has more than two divisors. $$$1$$$ is neither a prime nor a composite number.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$k$$$ ($$$1 \le k \le 50$$$) — the number of digits in the number. The second line of each test case contains a positive integer $$$n$$$, which doesn't contain zeros in decimal notation ($$$10^{k-1} \le n < 10^{k}$$$). It is guaranteed that it is always possible to remove less than $$$k$$$ digits to make the number not prime. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^4$$$.

For every test case, print two numbers in two lines. In the first line print the number of digits, that you have left in the number. In the second line print the digits left after all delitions.  If there are multiple solutions, print any.

NoteIn the first test case, you can't delete $$$2$$$ digits from the number $$$237$$$, as all the numbers $$$2$$$, $$$3$$$, and $$$7$$$ are prime. However, you can delete $$$1$$$ digit, obtaining a number $$$27 = 3^3$$$.In the second test case, you can delete all digits except one, as $$$4 = 2^2$$$ is a composite number.

object B extends App {
  def remove(input: String): String = {
    lazy val singles  = input.collectFirst { case char @ ('1' | '4' | '6' | '8' | '9') => char.toString }
    lazy val pairs    = input.tail.collectFirst { case char @ ('2' | '5') => s"${input.head}$char" }
    lazy val doubles  = input.groupBy(identity).collectFirst { case (char, slice) if slice.length > 1 => s"$char$char" }
    lazy val specials = s"${input.head}7"

    singles getOrElse (pairs getOrElse (doubles getOrElse specials))
  }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val k      = readInt()
    val number = readLine()

    val output = remove(number)

    println(output.length)
    println(output)
  }

}

object B extends App {
  def remove(input: String): String =
    input.collectFirst { case char @ ('1' | '4' | '6' | '8' | '9') => char.toString } getOrElse {
      input.tail.collectFirst { case char @ ('2' | '5') => s"${input.head}$char" } getOrElse {
        input.groupBy(identity).collectFirst { case (char, slice) if slice.length > 1 => s"$char$char" } getOrElse {
          input.head match {
            case '2' => "27"
            case '5' => "57"
          }
        }
      }
    }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val k      = readInt()
    val number = readLine()

    val output = remove(number)

    println(s"${output.length}\n$output")
  }

}

object B extends App {
  def remove(input: String): String =
    input.head match {
      case char @ ('1' | '4' | '6' | '8' | '9') => char.toString
      case _                                    =>
        input.contains('1') match {
          case true => "1"
          case _    =>
            input.tail.indexWhere { char =>
              val digit = char - 48
              digit == 5 || digit % 2 == 0
            } match {
              case i if i >= 0 => input.take(i + 2)
              case _           =>
                input.groupBy(_ - 48).collectFirst {
                  case (digit, slice) if slice.length > 1 => s"$digit$digit"
                } match {
                  case Some(output) => output
                  case _            => input.take(input.indexOf('7') + 1)
                }
            }
        }

    }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val k      = readInt()
    val number = readLine()

    val output = remove(number)

    println(s"${output.length}\n$output")
  }

}

object B extends App {
  def remove(input: String): String =
    input.head match {
      case char @ ('1' | '4' | '6' | '8' | '9') => char.toString
      case _                                    =>
        input.contains('1') match {
          case true => "1"
          case _    =>
            input.tail.indexWhere { char =>
              val digit = char - 48
              digit == 5 || digit % 2 == 0
            } match {
              case i if i >= 0 => input.take(i + 2)
              case _           =>
                input.groupBy(_ - 48).collectFirst {
                  case (digit, slice) if slice.length > 1 => s"$digit$digit"
                } match {
                  case Some(output) => output
                  case _            => input.take(input.indexOf('7') + 1)
                }
            }
        }

    }

  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val k      = readInt()
    val number = readLine()

    val output = remove(number)

    println(output.length)
    println(output)
  }

}


Let's call the following process a transformation of a sequence of length $$$n$$$.If the sequence is empty, the process ends. Otherwise, append the greatest common divisor (GCD) of all the elements of the sequence to the result and remove one arbitrary element from the sequence. Thus, when the process ends, we have a sequence of $$$n$$$ integers: the greatest common divisors of all the elements in the sequence before each deletion.You are given an integer sequence $$$1, 2, \dots, n$$$. Find the lexicographically maximum result of its transformation.A sequence $$$a_1, a_2, \ldots, a_n$$$ is lexicographically larger than a sequence $$$b_1, b_2, \ldots, b_n$$$, if there is an index $$$i$$$ such that $$$a_j = b_j$$$ for all $$$j < i$$$, and $$$a_i > b_i$$$.

The first and only line of input contains one integer $$$n$$$ ($$$1\le n\le 10^6$$$).

Output $$$n$$$ integers  — the lexicographically maximum result of the transformation.

NoteIn the first sample the answer may be achieved this way:  Append GCD$$$(1, 2, 3) = 1$$$, remove $$$2$$$.  Append GCD$$$(1, 3) = 1$$$, remove $$$1$$$.  Append GCD$$$(3) = 3$$$, remove $$$3$$$. We get the sequence $$$[1, 1, 3]$$$ as the result.

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)

  val pow2 = Array.ofDim[Int](21)
  pow2(0) = 1
  rep(pow2.length - 1)(i => pow2(i + 1) = pow2(i) * 2)

  def solve(): Unit = {
    val N = ni()
    N match {
      case 1 => out.println("1")
      case 2 => out.println("1 2")
      case 3 => out.println("1 1 3")
      case _ =>
        val cnt = Array.ofDim[Int](21)
        rep(20, 1) { i =>
          cnt(i) = N / pow2(i)
        }

        val lastK = cnt.lastIndexWhere(_ > 1)
        var ix = N - 1
        val ans = Array.fill[Int](N)(1)
        def write(x: Int): Unit = {
          ans(ix) = x
          ix -= 1
        }

        write(N / pow2(lastK) * pow2(lastK))
        rep_r(lastK, 1) { k =>
          N - cnt(k) to ix foreach (_ => write(pow2(k)))
        }

        out.println(ans.mkString(" "))
    }
  }

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

    step(-1, a.length)
  }

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

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

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

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

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


An array $$$b$$$ of length $$$k$$$ is called good if its arithmetic mean is equal to $$$1$$$. More formally, if $$$$$$\frac{b_1 + \cdots + b_k}{k}=1.$$$$$$Note that the value $$$\frac{b_1+\cdots+b_k}{k}$$$ is not rounded up or down. For example, the array $$$[1,1,1,2]$$$ has an arithmetic mean of $$$1.25$$$, which is not equal to $$$1$$$.You are given an integer array $$$a$$$ of length $$$n$$$. In an operation, you can append a non-negative integer to the end of the array. What's the minimum number of operations required to make the array good?We have a proof that it is always possible with finitely many operations.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the initial array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,\ldots,a_n$$$ ($$$-10^4\leq a_i \leq 10^4$$$), the elements of the array.

For each test case, output a single integer — the minimum number of non-negative integers you have to append to the array so that the arithmetic mean of the array will be exactly $$$1$$$.

NoteIn the first test case, we don't need to add any element because the arithmetic mean of the array is already $$$1$$$, so the answer is $$$0$$$.In the second test case, the arithmetic mean is not $$$1$$$ initially so we need to add at least one more number. If we add $$$0$$$ then the arithmetic mean of the whole array becomes $$$1$$$, so the answer is $$$1$$$.In the third test case, the minimum number of elements that need to be added is $$$16$$$ since only non-negative integers can be added.In the fourth test case, we can add a single integer $$$4$$$. The arithmetic mean becomes $$$\frac{-2+4}{2}$$$ which is equal to $$$1$$$.

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

object Solution {
  def solve(arr: Array[Int]): Long = {
    val sum = arr.sum.toLong
    val count = arr.length.toLong

    if (sum == count) 0 else {
      // if sum < count then just add one more number with count-sum+1

      // you want to add (count-sum+1)
      // sum goes to sum+(count-sum+1)=count+1, and count goes to count+1
      // count-sum+1 >= 0, count >= sum-1
      if (count >= sum-1) 1 else {
        // count < sum-1
        // so we need to add a lot of zeros...
        // k zeros so (count+k) = sum => k = sum-count
        sum-count
      }
    }
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      val n = input.nextInt()
      output.println(solve((1 to n).map { _ => input.nextInt() }.toArray))
    }

    output.flush()
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

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

  val t = readInt()

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

    val ans =
      if (n < asum) asum - n
      else if (n > asum) 1
      else 0

    println(ans)
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]) {
    val t : Int = readInt()
    for (i <- Range(0,t)) {
      val n = readInt()
      val vec = readLine().split(" ").map(_.toInt)
      val sum = vec.sum
      if(sum == n) {
        println(0)
      } else if(sum > n) {
        println(sum - n)
      } else {
        println(1)
      }
    }
  }
}


Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers.Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Roma's got n positive integers. He wonders, how many of those integers have not more than k lucky digits? Help him, write the program that solves the problem.

The first line contains two integers n, k (1 ≤ n, k ≤ 100). The second line contains n integers ai (1 ≤ ai ≤ 109) — the numbers that Roma has.  The numbers in the lines are separated by single spaces.

In a single line print a single integer — the answer to the problem.

NoteIn the first sample all numbers contain at most four lucky digits, so the answer is 3.In the second sample number 447 doesn't fit in, as it contains more than two lucky digits. All other numbers are fine, so the answer is 2.

import java.util

object Main {
  def lucky(n: Int, k: Int) = {
    var c = 0
    var x = n
    while (x != 0) {
      c += (x % 10 match {
        case 4 | 7 => 1
        case _ => 0
      })
      x = x / 10
    }
    c <= k
  }

  def main(args: Array[String]) {
    val n = readToken.toInt
    val k = readToken.toInt
    println((0 until n).filter(i => lucky(readToken.toInt, k)).size)
  }

  var st = new util.StringTokenizer("")
  def readToken() = {
    while (!st.hasMoreTokens) st = new java.util.StringTokenizer(readLine)
    st.nextToken
  }
}

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  val n = in.nextInt()
  val k = in.nextInt()
  var cnt = 0
  for (i <- 0 until n) {
    var a = in.nextInt()
    var len = 0
    while (a > 0) {
      var b = a % 10
      a /= 10
      if (b == 4 || b == 7) {
        len += 1
      }
    }
    if (len <= k) {
      cnt += 1
    }
  }
  println(cnt)
}

import scala.io._

object Test {
  def main(args: Array[String]): Unit = {
    val lines = Source.stdin.getLines().take(2).toArray
    val a = lines(0).split(' ').map(_.toInt)
    val (n,k) = (a(0), a(1))
    val ns = lines(1).split(' ').count(_.count(p => p=='4' || p=='7') <= k)
    println(ns)
  }

}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  println(in.next().split(" ").map(_.count(ch => ch == '4' || ch == '7')).filter(_ <= k).size)

}

import java.util.Scanner

object Main extends App {
  def luckyCount(n : Int) = {
    var x = n
    var result = 0

    while(x != 0) {
      if(x % 10 == 4 || x % 10 == 7) result += 1
      x /= 10
    }

    result
  }

  val scanner = new Scanner(System.in)
  val n = scanner.nextInt()
  val k = scanner.nextInt()
  var answer = 0

  for(i <- 1 to n)
    if(luckyCount(scanner.nextInt) <= k)
      answer += 1

  println(answer)
}

object A extends App{
  val nk = readLine.split(" ").map(_.toInt)
  val nums = readLine.split(" ")
  println((nums.filter(_.filter(x=> x=='4' || x=='7').length <= nk(1))).length)
}

object J {

  def main (args : Array[String]){
    var Array(n,k) = readLine.split(" ").map(_.toInt)
    var a = readLine.split(" ").map(_.toInt)
    var ans = 0;
    for (i <- a){
      var s = String.valueOf(i)
      var cnt = 0
      for (ch <- s){
        if (ch == '4' || ch == '7')cnt +=1
      }
      if (cnt<=k)ans += 1
    }
    println(ans)
  }

}

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

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

  val N, K = sc.nextInt

  def isLucky(c: Char): Boolean = c == '4' || c == '7'

  val answer = List.fill(N)(sc.nextInt).map(_.toString).filter { s =>
      s.filter(isLucky).size <= K
    }.size

  out.println(answer)
  out.close
}

import annotation.tailrec
import java.io._

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

  val Array(n, k) = readInts
  def ans = reader.readLine().split(" ").count(_.count("47".contains(_)) <= k)

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

object Main {
  def main(args: Array[String]) {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(1)
    val a = readLine().split(" ")
    val r = a.count(_.count(c => c == '4' || c == '7') <= k)
    println(r)
  }
}

import scala.Math.pow;

object App {
	def readInts:Array[Int] = (readLine split " ") map (_.toInt)
                                                  //> readInts: => Array[Int]
	//def solve(s: java.lang.String, a:Int):Int = {
	//}                                         //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)

	def f1_io() = {
		val Array(n, k) = readInts
		val ans = (readLine split " ") map (x => (x filter(p => p == '4' || p == '7')).length)
		print((ans filter (p => p <= k)).length)
	}
  def main(args: Array[String]): Unit = {
	f1_io
  }

}

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

    //n,k
    val (n,k)={
      val sp=readLine.split(" ")
      (sp(0).toInt,sp(1).toInt)
    }

    //a,ans
    println(
      readLine.split(" ").toList.map({
          _.toList.filter(s=> s=='4'||s=='7').length
        })
        .filter({
          _<=k
        })
        //ans
        .length
    )
  }
}

object A extends App{
  val nk = readLine.split(" ").map(_.toInt)
  val nums = readLine.split(" ")
  println((nums.filter(cNum => cNum.filter(x=> x=='4' || x=='7').length < nk(0))).length)

}

object A extends App{
  // val in = io.Source//.stdin.getLines
  val nk = readLine.split(" ").map(_.toInt)
  val nums = readLine.split(" ")
  // println(n + " " + k)
  nums.foreach(println)
  println(nums.filter(_.length <= nk(1)).length)

}

object A extends App{
  // val in = io.Source//.stdin.getLines
  val nk = readLine.split(" ").map(_.toInt)
  val nums = readLine.split(" ")
  // println(n + " " + k)
  // nums.foreach(println)
  println(nums.filter(_.length <= nk(1)).length)

}


While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s.  He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k messages in his own bag, each was a palindrome string and all those strings had the same length.He asked you to help him and tell him if he has worn his own back-bag. Check if the given string s is a concatenation of k palindromes of the same length.

The first line of input contains string s containing lowercase English letters (1 ≤ |s| ≤ 1000). The second line contains integer k (1 ≤ k ≤ 1000).

Print "YES"(without quotes) if he has worn his own back-bag or "NO"(without quotes) otherwise.

NotePalindrome is a string reading the same forward and backward.In the second sample, the faxes in his back-bag can be "saddas" and "tavvat".

import scala.collection._

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

    var inLoop = true
    while (inLoop) {
      val words = scala.io.StdIn.readLine
      if (words != null) {
        var good = true
        val k = scala.io.StdIn.readLine.toInt

        if ((words.length % k) == 0) {
          val wordLen = words.length / k

          var i = 0
          var j = 0
          for (i <- 0 to (k - 1)) {
            val word = words.substring((i * wordLen), (i + 1) * wordLen)
            for (j <- 0 to (word.length / 2)) {
              if (word.charAt(j) != word.charAt(word.length - j - 1)) {
                good = false;
              }
            }
          }
        } else {
          good = false
        }

        if (good) println("YES") else println("NO")

      } else {

        inLoop = false
      }
    }
  }
}

import scala.math._
import scala.collection.mutable
import scala.util.control.Breaks
import scala.annotation.tailrec

object Problem extends App {
  import Scanner._
  def exit() = System.exit(0)

  val line = readLine
  val k = readInt
  val n = line.length

  if(n%k!=0) {
    println("NO")
    exit
  }

  val len = n/k

  for(i <- 0 until k; p <- 0 until len; if line(i*len+p) != line(i*len+len-p-1)) {
    println("NO")
    exit
  }

  println("YES")
}

object Scanner {
  def readInt() = {
    var acc = 0
    readWith {
      case c if c >= '0' && c <= '9' && (Int.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
    }
    acc
  }
  def readLong() = {
    var acc = 0L
    readWith {
      case c if c >= '0' && c <= '9' && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10L) + (c - '0')
    }
    acc
  }
  def readDouble() = {
    var (acc, frac, fracPow, readFrac) = (0L, 0L, 1L, false)
    readWith {
      case c if c >= '0' && c <= '9' && !readFrac && (Long.MaxValue - acc) >= (c - '0') =>
        acc = (acc * 10) + (c - '0')
      case c if c >= '0' && c <= '9' && readFrac && (Long.MaxValue - frac) >= (c - '0') =>
        frac = (frac * 10) + (c - '0')
        fracPow *= 10
      case c if c == '.' && !readFrac =>
        readFrac = true
    }
    acc + (frac.toDouble / fracPow)
  }
  def readString() = {
    var string = new StringBuilder
    readWith { case c => string += c }
    string.toString
  }
  def readLine() = Console.in.readLine()
  def readChar() = Console.in.read().toChar
  def readWith(func: PartialFunction[Char, Unit]) {
    val handler = func orElse[Char, Unit] {
      case _ => throw new java.io.IOException("unexpected token")
    }

    var c = readChar
    while(c.isWhitespace)
      c = readChar

    while(!c.isWhitespace) {
      handler(c)

      c = readChar
    }
  }
}

import java.util.StringTokenizer

object _548A extends App {
  var token = new StringTokenizer("")

  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }

  val s = next
  val k = next.toInt

  if (s.length % k != 0) println("NO")
  else {
    val a = s.grouped(s.length / k)

    def isPalindrome(s: String) = {
      def is(l: Int, r: Int): Boolean =
        if (l > r) true
        else if (s(l) == s(r)) is(l + 1, r - 1)
        else return false
      is(0, s.length - 1)
    }

    if (a.forall(isPalindrome)) println("YES")
    else println("NO")
  }
}

import scala.io.StdIn._

object A {

	def isPalindromSubstring(s:String, pos:Int, length:Int):Boolean = {
		for {
			i <- 0 until length / 2
			c1 = s.charAt(pos + i)
			c2 = s.charAt(pos + length - 1 - i)
		} {
			if (c1 != c2)
				return false
		}
		return true
	}

	def isContainsKPalindroms(s:String, k:Int):Boolean = {
		if (s.length() % k == 0) {
			val length = s.length() / k;
			for (pos <- 0 until s.length() by length) {
				if (!isPalindromSubstring(s, pos, length)) {
					return false
				}
			}
			return true
		} else {
			return false
		}
	}

	def main(args:Array[String]) {
		println(if (isContainsKPalindroms(readLine, readInt)) "YES" else "NO")
	}

}

import java.io._
import java.util._
import scala.collection.mutable

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

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

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

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

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???
    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val s = next.toCharArray
    val k = nextInt
    val len = s.length / k
    if (len == 0 || s.length % k != 0) {
      out.println("NO")
      return 1
    }
    var i = 0
    while (i < s.length) {
      var i1 = i
      var j1 = i + len - 1
      while (i1 <= j1) {
        if (i1 >= 0 && i1 < s.length && j1 >= 0 && j1 < s.length && s(i1) != s(j1)) {
          out.println("NO")
          return 1
        }
        j1 -= 1
        i1 += 1
      }
      i += len
    }
    out.println("YES")
    return 0
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    val s = StdIn.readLine();
    val k = StdIn.readInt();

    if(s.length % k != 0) {
      println("NO");
      return;
    }

    def isPolyndrome : String => Boolean = {
      case str if str.length < 2 => true
      case str =>
        if(str.head != str.last)
          false
        else
          isPolyndrome(str.substring(1, str.length - 1));
    }

    println(if(s.grouped(s.length / k).forall(isPolyndrome)) "YES" else "NO");
  }
}

import scala.io.StdIn._

object A extends App {
  val input = readLine()
  val k = readInt()

  def solve() = {
    if (input.length % k != 0) "NO"
    else {
      var str = input
      var size = input.length / k
//      println(str.take(size))
      while (str.length > 0 && isPalindrome(str.take(size))) {
//        println(str.take(size) + " considered")
        str = str.drop(size)
      }
      if (str.length == 0) "YES" else "NO"
    }
  }

  def isPalindrome(s: String): Boolean = s == s.reverse

  println(solve())
}


A positive integer is called composite if it can be represented as a product of two positive integers, both greater than $$$1$$$. For example, the following numbers are composite: $$$6$$$, $$$4$$$, $$$120$$$, $$$27$$$. The following numbers aren't: $$$1$$$, $$$2$$$, $$$3$$$, $$$17$$$, $$$97$$$.Alice is given a sequence of $$$n$$$ composite numbers $$$a_1,a_2,\ldots,a_n$$$.She wants to choose an integer $$$m \le 11$$$ and color each element one of $$$m$$$ colors from $$$1$$$ to $$$m$$$ so that:  for each color from $$$1$$$ to $$$m$$$ there is at least one element of this color;  each element is colored and colored exactly one color;  the greatest common divisor of any two elements that are colored the same color is greater than $$$1$$$, i.e. $$$\gcd(a_i, a_j)>1$$$ for each pair $$$i, j$$$ if these elements are colored the same color. Note that equal elements can be colored different colors — you just have to choose one of $$$m$$$ colors for each of the indices from $$$1$$$ to $$$n$$$.Alice showed already that if all $$$a_i \le 1000$$$ then she can always solve the task by choosing some $$$m \le 11$$$.Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $$$m$$$ from $$$1$$$ to $$$11$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then the descriptions of the test cases follow. The first line of the test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the amount of numbers in a sequence $$$a$$$. The second line of the test case contains $$$n$$$ composite integers $$$a_1,a_2,\ldots,a_n$$$ ($$$4 \le a_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^4$$$.

For each test case print $$$2$$$ lines. The first line should contain a single integer $$$m$$$ ($$$1 \le m \le 11$$$) — the number of used colors. Consider colors to be numbered from $$$1$$$ to $$$m$$$. The second line should contain any coloring that satisfies the above conditions. Print $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le m$$$), where $$$c_i$$$ is the color of the $$$i$$$-th element. If there are multiple solutions then you can print any of them. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some $$$m$$$ from $$$1$$$ to $$$11$$$. Remember that each color from $$$1$$$ to $$$m$$$ should be used at least once. Any two elements of the same color should not be coprime (i.e. their GCD should be greater than $$$1$$$).

NoteIn the first test case, $$$\gcd(6,10)=2$$$, $$$\gcd(6,15)=3$$$ and $$$\gcd(10,15)=5$$$. Therefore, it's valid to color all elements the same color. Note that there are other colorings which satisfy Alice's requirement in this test case.In the second test case there is only one element of each color, so the coloring definitely satisfies Alice's requirement.

object B extends App {
  private val ps = List(31, 29, 23, 19, 17, 13, 11, 7, 5, 3, 2)

  private def colorize(ns: List[Int]): List[Int] = {

    val cs = ns.foldLeft(List.empty[Int]) { (cs, n) =>
      val p = ps.find(n % _ == 0).get

      p :: cs
    }

    val p2c = Map(cs.distinct.zipWithIndex: _*)

    cs.map(1 + p2c(_)).reverse
  }

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

  val input: List[List[Int]] = (0 until t)
    .foldLeft(List.empty[List[Int]]) {
      case (input, _) =>
        val _ = scala.io.StdIn.readInt()
        val ns = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

        ns :: input
    }
    .reverse

  val output = input.map(colorize)

  output.foreach(cs => {
    println(cs.distinct.length)
    println(cs.mkString(" "))
  })
}

object B extends App {
  private val primesToColor = Map[Int, Int](31 -> 11,
                                            29 -> 10,
                                            23 -> 9,
                                            19 -> 8,
                                            17 -> 7,
                                            13 -> 6,
                                            11 -> 5,
                                            7 -> 4,
                                            5 -> 3,
                                            2 -> 2,
                                            3 -> 1)

  private val primes = Map[Int, List[Int]](31 -> List(),
                                           29 -> List(),
                                           23 -> List(),
                                           19 -> List(),
                                           17 -> List(),
                                           13 -> List(),
                                           11 -> List(),
                                           7 -> List(),
                                           5 -> List(),
                                           2 -> List(),
                                           3 -> List())

  private def colorize(ns: List[Int]): List[Int] =
    ns.foldLeft((List.empty[Int], primes)) {
      case ((cs, ps), n) =>
        val (p, ls) = ps.filter {
          case (k, vs) => n % k == 0 && !vs.contains(n)
        }.head

        val c = primesToColor(p)

        (c :: cs, ps + (p -> (n :: ls)))
    }._1.reverse

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

  val input: List[List[Int]] = (0 until t)
    .foldLeft(List.empty[List[Int]]) {
      case (input, _) =>
        scala.io.StdIn.readInt()
        val ns = scala.io.StdIn.readLine().split(" ").map(_.toInt).toList

        ns :: input
    }
    .reverse

  val output = input.map(colorize)

  output.foreach(cs => {
    println(cs.distinct.length)
    println(cs.mkString(" "))
  })
}


You are given a rebus of form ? + ? - ? + ? = n, consisting of only question marks, separated by arithmetic operation '+' and '-', equality and positive integer n. The goal is to replace each question mark with some positive integer from 1 to n, such that equality holds.

The only line of the input contains a rebus. It's guaranteed that it contains no more than 100 question marks, integer n is positive and doesn't exceed 1 000 000, all letters and integers are separated by spaces, arithmetic operations are located only between question marks.

The first line of the output should contain "Possible" (without quotes) if rebus has a solution and "Impossible" (without quotes) otherwise. If the answer exists, the second line should contain any valid rebus with question marks replaced by integers from 1 to n. Follow the format given in the samples.

import scala.io.StdIn._

object B extends App {
  val str = "+" + readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = normalized.count(_ == '+') // m
  val negatives = normalized.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    for (s1 <- positivies * n to Math.max(positivies * 1, n) by -1) {
      val s2 = s1 - n
      if (s2 >= 0 && s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)
    }

    None
  }

  findFirst match {
    case None =>
      println("Impossible")
    case Some((s1, s2)) =>
      println("Possible")

      var S1 = s1
      var S2 = s2
      var leftPos = positivies - 1
      var leftNeg = negatives - 1

      //      println(S1 + " " + S2)

      val values = normalized.map { sign =>
        if (sign == '+') {
          if (S1 - leftPos <= n) {
            val tmp = S1 - leftPos
            leftPos -= 1
            S1 -= tmp
            "+"+tmp
          } else {
            S1 -= n
            leftPos -= 1
            "+"+n
          }
        } else {
          if (S2 - leftNeg <= n) {
            val tmp = S2 - leftNeg
            leftNeg -= 1
            S2 -= tmp
            "-"+tmp
          } else {
            S2 -= n
            leftNeg -= 1
            "-"+n
          }
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + ") + " = " + n)
  }
}

import scala.io.StdIn._

object B extends App {
  val str = readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = normalized.count(_ == '+') // m
  val negatives = normalized.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    if (negatives == 0) Some(n, 0)
    else {
      for {
        s1 <- positivies * n to Math.max(positivies * 1, n) by -1
      } {
        val s2 = s1 - n
        if (s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)
      }

      None
    }
  }

  findFirst match {
    case None =>
      println("Impossible")
    case Some((s1, s2)) =>
      println("Possible")

      var S1 = s1
      var S2 = s2
      var leftPos = positivies - 1
      var leftNeg = negatives - 1

//      println(S1 + " " + S2)

      val values = normalized.map { sign =>
        if (sign == '+') {
          if (S1 - leftPos <= n) {
            val tmp = S1 - leftPos
            leftPos -= 1
            S1 -= tmp
            "+"+tmp
          } else {
            S1 -= n
            leftPos -= 1
            "+"+n
          }
        } else {
          if (S2 - leftNeg <= n) {
            val tmp = S2 - leftNeg
            leftNeg -= 1
            S2 -= tmp
            "-"+tmp
          } else {
            S2 -= n
            leftNeg -= 1
            "-"+n
          }
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + ") + " = " + n)
  }

}

import scala.io.StdIn._

object B extends App {
  val str = readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = normalized.count(_ == '+') // m
  val negatives = normalized.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    for {
      s1 <- positivies * n to positivies * 1 by -1
      s2 = s1 - n
      if s2 >= 0 && s2 >= negatives * 1 && s2 <= negatives * n
    } {
      return Some(s1, s2)
    }

    None
  }

  findFirst match {
    case None =>
      println("Impossible")
    case Some((s1, s2)) =>
      println("Possible")

      var S1 = s1
      var S2 = s2
//      println(S1 + " " + S2)

      val posDiv = S1 / positivies + 1
      val negDiv = if (negatives == 0) 0 else {
        S2 / negatives + 1
      }

      val values = normalized.map { sign =>
        if (sign == '+') {
          if (S1 >= posDiv) {
            S1 -= posDiv
            "+"+posDiv
          } else {
            "+"+S1
          }
        } else {
          if (S2 >= negDiv) {
            S2 -= negDiv
            "-"+negDiv
          } else {
            "-"+S2
          }
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + ") + " = " + n)
  }

}

import scala.io.StdIn._

object B extends App {
  val str = readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = normalized.count(_ == '+') // m
  val negatives = normalized.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    if (negatives == 0) Some(n, 0)
    else {
      for {
        s1 <- positivies * n to Math.max(positivies * 1, n + 1) by -1
      } {
        val s2 = s1 - n
        if (s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)
      }

      None
    }
  }

  findFirst match {
    case None =>
      println("Impossible")
    case Some((s1, s2)) =>
      println("Possible")

      var S1 = s1
      var S2 = s2
      var leftPos = positivies - 1
      var leftNeg = negatives - 1

//      println(S1 + " " + S2)

      val values = normalized.map { sign =>
        if (sign == '+') {
          if (S1 - leftPos <= n) {
            val tmp = S1 - leftPos
            leftPos -= 1
            S1 -= tmp
            "+"+tmp
          } else {
            S1 -= n
            leftPos -= 1
            "+"+n
          }
        } else {
          if (S2 - leftNeg <= n) {
            val tmp = S2 - leftNeg
            leftNeg -= 1
            S2 -= tmp
            "-"+tmp
          } else {
            S2 -= n
            leftNeg -= 1
            "-"+n
          }
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + ") + " = " + n)
  }

}

import scala.io.StdIn._

object B extends App {
  val str = readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = normalized.count(_ == '+') // m
  val negatives = normalized.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    if (negatives == 0) Some(n, 0)
    else {
      for {
        s1 <- positivies * n to positivies * 1 by -1
      } {
        val s2 = s1 - n
        if (s2 >= negatives * 1 && s2 <= negatives * n) return Some(s1, s2)
      }

      None
    }
  }

  findFirst match {
    case None =>
      println("Impossible")
    case Some((s1, s2)) =>
      println("Possible")

      var S1 = s1
      var S2 = s2
      var leftPos = positivies - 1
      var leftNeg = negatives - 1

//      println(S1 + " " + S2)

      val values = normalized.map { sign =>
        if (sign == '+') {
          if (S1 - leftPos <= n) {
            val tmp = S1 - leftPos
            leftPos -= 1
            S1 -= tmp
            "+"+tmp
          } else {
            S1 -= n
            leftPos -= 1
            "+"+n
          }
        } else {
          if (S2 - leftNeg <= n) {
            val tmp = S2 - leftNeg
            leftNeg -= 1
            S2 -= tmp
            "-"+tmp
          } else {
            S2 -= n
            leftNeg -= 1
            "-"+n
          }
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + ") + " = " + n)
  }

}

import scala.io.StdIn._

object B extends App {
  val str = readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = normalized.count(_ == '+') // m
  val negatives = normalized.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    if (negatives == 0) Some(n, 0)
    else {
      for {
        s1 <- positivies * n to positivies * 1 by -1
        s2 = s1 - n
        if s2 >= 0 && s2 >= negatives * 1 && s2 <= negatives * n
      } {
        return Some(s1, s2)
      }

      None
    }
  }

  findFirst match {
    case None =>
      println("Impossible")
    case Some((s1, s2)) =>
      println("Possible")

      var S1 = s1
      var S2 = s2
      var leftPos = positivies - 1
      var leftNeg = negatives - 1

      //      println(S1 + " " + S2)

      val values = normalized.map { sign =>
        if (sign == '+') {
          if (S1 - leftPos <= n) {
            val tmp = S1 - leftPos
            leftPos -= 1
            S1 -= tmp
            "+"+tmp
          } else {
            S1 -= n
            leftPos -= 1
            "+"+n
          }
        } else {
          if (S2 - leftNeg <= n) {
            val tmp = S2 - leftNeg
            leftNeg -= 1
            S2 -= tmp
            "-"+tmp
          } else {
            S2 -= n
            leftNeg -= 1
            "-"+n
          }
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + ") + " = " + n)
  }

}

import scala.io.StdIn._

object B extends App {
  val str = readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = normalized.count(_ == '+') // m
  val negatives = normalized.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    for {
      s1 <- positivies * n to Math.max(positivies * 1, n + 1) by -1
      s2 = s1 - n
      if s2 >= negatives * 1 && s2 <= negatives * n
    } {
      return Some(s1, s2)
    }

    None
  }

  findFirst match {
    case None =>
      println("Impossible")
    case Some((s1, s2)) =>
      println("Possible")

      var S1 = s1
      var S2 = s2
      var leftPos = positivies - 1
      var leftNeg = negatives - 1

//      println(S1 + " " + S2)

      val values = normalized.map { sign =>
        if (sign == '+') {
          if (S1 - leftPos <= n) {
            val tmp = S1 - leftPos
            leftPos -= 1
            S1 -= tmp
            "+"+tmp
          } else {
            S1 -= n
            leftPos -= 1
            "+"+n
          }
        } else {
          if (S2 - leftNeg <= n) {
            val tmp = S2 - leftNeg
            leftNeg -= 1
            S2 -= tmp
            "-"+tmp
          } else {
            S2 -= n
            leftNeg -= 1
            "-"+n
          }
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + ") + " = " + n)
  }

}

import scala.io.StdIn._

object B extends App {
  val str = readLine().replace(" ", "")
  val rebus = str.toCharArray
  val normalized = Array('+') ++ rebus.filter(ch => ch == '-' || ch == '+')
  val positivies = 1 + rebus.count(_ == '+') // m
  val negatives = rebus.count(_ == '-') // k
  val n = str.split("=").tail.head.toInt

  def findFirst: Option[(Int, Int)] = {
    for (s1 <- positivies * n to positivies by -1) {
      val s2 = s1 - n
      if (s2 >= negatives && s2 <= negatives * n) return Some(s1, s2)
    }

    None
  }

  findFirst match {
    case None => println("Impossible")
    case Some((s1, s2)) =>
      var S1 = s1
      var positivesLeft = positivies
      var S2 = s2
      var negativesLeft = negatives

      println("Possible")

      val values = normalized.map { sign =>
        if (sign == '+') {
          val v = Math.min(S1 - positivesLeft + 1, n - positivesLeft + 1)
          positivesLeft -= 1
          S1 -= v
          "+"+v
        } else {
          val v = Math.min(S2 - negativesLeft + 1, n - negativesLeft + 1)
          negativesLeft -= 1
          S2 -= v
          "-"+v
        }
      }

      println(values.mkString("").drop(1).mkString("").replaceAll("\\-", " - ").replaceAll("\\+", " + "))
  }

}


Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose several of the subarrays suggested by her mother. After that, each of the flowers will add to the girl's happiness its mood multiplied by the number of chosen subarrays the flower is in.For example, consider the case when the mother has 5 flowers, and their moods are equal to 1,  - 2, 1, 3,  - 4. Suppose the mother suggested subarrays (1,  - 2), (3,  - 4), (1, 3), (1,  - 2, 1, 3). Then if the girl chooses the third and the fourth subarrays then:   the first flower adds 1·1 = 1 to the girl's happiness, because he is in one of chosen subarrays,  the second flower adds ( - 2)·1 =  - 2, because he is in one of chosen subarrays,  the third flower adds 1·2 = 2, because he is in two of chosen subarrays,  the fourth flower adds 3·2 = 6, because he is in two of chosen subarrays,  the fifth flower adds ( - 4)·0 = 0, because he is in no chosen subarrays. Thus, in total 1 + ( - 2) + 2 + 6 + 0 = 7 is added to the girl's happiness. Alyona wants to choose such subarrays from those suggested by the mother that the value added to her happiness would be as large as possible. Help her do this!Alyona can choose any number of the subarrays, even 0 or all suggested by her mother.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of flowers and the number of subarrays suggested by the mother. The second line contains the flowers moods — n integers a1, a2, ..., an ( - 100 ≤ ai ≤ 100). The next m lines contain the description of the subarrays suggested by the mother. The i-th of these lines contain two integers li and ri (1 ≤ li ≤ ri ≤ n) denoting the subarray a[li], a[li + 1], ..., a[ri]. Each subarray can encounter more than once.

Print single integer — the maximum possible value added to the Alyona's happiness.

NoteThe first example is the situation described in the statements.In the second example Alyona should choose all subarrays.The third example has answer 0 because Alyona can choose none of the subarrays.

object B {
  def main(args: Array[String]): Unit = {
    val Array(n, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val flowers = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    val count = Array.fill[Int](n)(0)
    for(i <- 1 to k) {
      val Array(q, w) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
//      println(flowers.slice(q-1, w).mkString(" "))
      if (flowers.slice(q-1, w).sum > 0){
        for (j <- q - 1 until w){
          count(j) += 1
        }
      }
    }
//    println(count.mkString(" "))
    println(flowers.toStream.zip(count).map(x => x._2 * x._1).sum)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt).scanLeft(0)(_+_)
  println((1 to m).foldLeft(0) {
    case (acc, _) =>
      val Array(x, y) = in.next().split(' ').map(_.toInt)
      acc + Math.max(0, a(y) - a(x - 1))
  })
}


Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half.  English alphabet You are given a string s. Check if the string is "s-palindrome".

The only line contains the string s (1 ≤ |s| ≤ 1000) which consists of only English letters.

Print "TAK" if the string s is "s-palindrome" and "NIE" otherwise.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y', 'A', 'H')
  if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2)))
    println("NIE")
  else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||
    (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {
    println("TAK")
  } else println("NIE")
}

import scala.io.StdIn._

object B extends App {
  val Sym = Map(
    'A' -> 'A',
    'b' -> 'd',
    'd' -> 'b',
    'H' -> 'H',
    'I' -> 'I',
    'M' -> 'M',
    'O' -> 'O',
    'o' -> 'o',
    'T' -> 'T',
    'U' -> 'U',
    'V' -> 'V',
    'v' -> 'v',
    'W' -> 'W',
    'w' -> 'w',
    'X' -> 'X',
    'x' -> 'x',
    'Y' -> 'Y',
    'p' -> 'q',
    'q' -> 'p'
  )

  val S = readLine().toCharArray

  def isSPal: Boolean = {
    for (i <- 0 until S.length / 2) {
      if (Sym.get(S(i)).isEmpty || Sym(S(i)) != S(S.length - i - 1)) {
        return false
      }
    }

    if (S.length % 2 == 0) true
    else {
      val mid = S(S.length / 2)
      Sym.get(mid).isDefined && Sym(mid) == mid
    }
  }

  println(if (isSPal) "TAK" else "NIE")

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  if (line.length % 2 == 0)
    println("NIE")
  else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => i._1 == i._2 ||
    (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {
    println("TAK")
  } else println("NIE")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')
  if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2 + 1)))
    println("NIE")
  else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||
    (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {
    println("TAK")
  } else println("NIE")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')
  if (line.length % 2 == 0 || !symmetric.contains(line(line.length / 2)))
    println("NIE")
  else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||
    (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {
    println("TAK")
  } else println("NIE")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y', 'A')
  if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2)))
    println("NIE")
  else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||
    (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {
    println("TAK")
  } else println("NIE")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')
  if (line.length % 2 == 1 && !symmetric.contains(line(line.length / 2)))
    println("NIE")
  else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||
    (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {
    println("TAK")
  } else println("NIE")
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next()
  val symmetric = Set('o', 'O', 'v', 'V', 'I', 'M', 'T', 'U', 'w', 'W', 'x', 'X', 'Y')
  if (line.length % 2 == 0 && symmetric.contains(line(line.length / 2)))
    println("NIE")
  else if (line.take(line.length / 2).zip(line.takeRight(line.length / 2).reverse).forall(i => (i._1 == i._2 && symmetric.contains(i._1)) ||
    (Math.min(i._1, i._2) == 'b' && Math.max(i._1, i._2) == 'd') || (Math.min(i._1, i._2) == 'p' && Math.max(i._1, i._2) == 'q'))) {
    println("TAK")
  } else println("NIE")
}

import scala.io.StdIn._

object B extends App {
  val Sym = Map(
    'A' -> 'A',
    'b' -> 'd',
    'd' -> 'b',
    'H' -> 'H',
    'I' -> 'I',
    'M' -> 'M',
    'm' -> 'm',
    'O' -> 'O',
    'o' -> 'o',
    'T' -> 'T',
    'U' -> 'U',
    'V' -> 'V',
    'v' -> 'v',
    'W' -> 'W',
    'w' -> 'w',
    'X' -> 'X',
    'x' -> 'x',
    'Y' -> 'Y',
    'p' -> 'q',
    'q' -> 'p'
  )

  val S = readLine().toCharArray

  def isSPal: Boolean = {
    for (i <- 0 until S.length / 2) {
      if (Sym.get(S(i)).isEmpty || Sym(S(i)) != S(S.length - i - 1)) {
        return false
      }
    }

    if (S.length % 2 == 0) true
    else {
      val mid = S(S.length / 2)
      Sym.get(mid).isDefined && Sym(mid) == mid
    }
  }

  println(if (isSPal) "TAK" else "NIE")

}

import scala.io.StdIn._

object B extends App {
  val Sym = Map(
    'A' -> 'A',
    'b' -> 'd',
    'd' -> 'b',
    'H' -> 'H',
    'I' -> 'I',
    'M' -> 'M',
    'm' -> 'm',
    'O' -> 'O',
    'o' -> 'o',
    'T' -> 'T',
    'U' -> 'U',
    'V' -> 'V',
    'v' -> 'v',
    'W' -> 'W',
    'w' -> 'w',
    'X' -> 'X',
    'x' -> 'x',
    'Y' -> 'Y'
  )

  val S = readLine().toCharArray

  def isSPal: Boolean = {
    for (i <- 0 until S.length / 2) {
      if (Sym.get(S(i)).isEmpty || Sym(S(i)) != S(S.length - i - 1)) {
        return false
      }
    }

    if (S.length % 2 == 0) true
    else {
      val mid = S(S.length / 2)
      Sym.get(mid).isDefined && Sym(mid) == mid
    }
  }

  println(if (isSPal) "TAK" else "NIE")

}


Alyona has recently bought a miniature fridge that can be represented as a matrix with $$$h$$$ rows and $$$2$$$ columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but separates the inside of the fridge to the lower and upper part.  An example of a fridge with $$$h = 7$$$ and two shelves. The shelves are shown in black. The picture corresponds to the first example. Alyona has $$$n$$$ bottles of milk that she wants to put in the fridge. The $$$i$$$-th bottle is $$$a_i$$$ cells tall and $$$1$$$ cell wide. She can put a bottle on some shelf if the corresponding space above the shelf is at least as tall as the bottle. She can not put a bottle on top of another bottle (if there is no shelf between them). Two bottles can not share a cell.Alyona is interested in the largest integer $$$k$$$ such that she can put bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. Find this largest $$$k$$$.

The first line contains two integers $$$n$$$ and $$$h$$$ ($$$1 \le n \le 10^3$$$, $$$1 \le h \le 10^9$$$) — the number of bottles and the height of the fridge. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \le a_i \le h$$$) — the heights of the bottles.

Print the single integer $$$k$$$ — the maximum integer such that Alyona can put the bottles $$$1$$$, $$$2$$$, ..., $$$k$$$ in the fridge at the same time. If Alyona can put all bottles in the fridge, print $$$n$$$. It is easy to see that Alyona can always put at least one bottle in the fridge.

NoteOne of optimal locations in the first example is shown on the picture in the statement.One of optimal locations in the second example is shown on the picture below.  One of optimal locations in the third example is shown on the picture below.

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

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

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

    REP(N) { i =>
      Arrays.sort(A, 0, i + 1)
      var cnt = 0
      val l = i / 2 + 1
      debug(s"l:$l")
      debug(A)
      REP(l) { j =>
        debug(s"ix:${i - 2 * j}")
        cnt += A(i - 2 * j)
      }
      if (cnt > H) {
        out.println(i)
        return
      }
    }

    out.println(N)
  }

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

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

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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