Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t):  where  is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") =  h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +  h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +  h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =  1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.

The first line of the input contains a single integer n (1 ≤ n ≤ 105). The second line of the input contains a single string of length n, consisting of characters "ACGT".

Print a single number — the answer modulo 109 + 7.

NotePlease note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.In the third sample, ρ("TTT", "TTT") = 27

import java.io.InputStreamReader

/**
 * Created by pva701 on 4/7/15.
 */
object HelloWorld {
    val MOD = 1000000000 + 7
    def pow(x:Int, y:Int):Int=if (y == 0) 1 else (1L * x * pow(x, y - 1) % MOD).toInt
    def main(args:Array[String]):Unit= {
        val n = readInt()
        val s = readLine()
        val AL = List('A', 'C', 'G', 'T')
        val cnt = new Array[Int](256)
        s.foreach(c=>cnt(c) += 1)
        val cnChar = cnt(AL.reduceLeft((a, b)=>if (cnt(a) > cnt(b)) a else b))
        val num = AL.foldLeft(0)((a, b)=>if (cnChar == cnt(b)) a + 1 else a)
        println(pow(num, n))
    }
}

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

object C {

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

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

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

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

  val MOD = 1e9 + 7

  def solve: Int = {
    val n = nextInt
    val ch = next.toCharArray
    val cnt = new Array[Int](4)
    for (i <- 0 until n) {
      ch(i) match {
        case 'A' => cnt(0) += 1
        case 'C' => cnt(1) += 1
        case 'G' => cnt(2) += 1
        case 'T' => cnt(3) += 1
        case _ =>
      }
    }
    val max = cnt.toList.max
    var k = 0
    for (i <- 0 until 4) {
      if (cnt(i) == max) {
        k += 1
      }
    }
    out.println(BigInt.int2bigInt(k).pow(n).%(BigInt.int2bigInt(MOD.toInt)))
    return 1
  }

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

object A extends App {
  val n = readLine.toInt
  val counts = readLine.groupBy(identity).map(_._2.size)
  val maxCount = counts.max
  val withMaxCount = counts.count(_ == maxCount)
  println(BigInt(withMaxCount).pow(n).mod(1000000007))
}

import scala.collection._

object A extends App {

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

  val Array(n) = readInts(1)
  val s = readLine.map {
    case 'A' => 0
    case 'C' => 1
    case 'G' => 2
    case 'T' => 3
  }

  val cntA = s.count(_ == 0)
  val cntC = s.count(_ == 1)
  val cntG = s.count(_ == 2)
  val cntT = s.count(_ == 3)
  val cnt = (if (cntA > 0) 1 else 0) + (if (cntC > 0) 1 else 0) + (if (cntG > 0) 1 else 0) +(if (cntT > 0) 1 else 0)

  println(BigInt(cnt).pow(n).mod(1000000007))
}

object A extends App {

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

  val Array(n) = readInts(1)
  val s = readLine.map {
    case 'A' => 0
    case 'C' => 1
    case 'G' => 2
    case 'T' => 3
  }

  val cntA = s.count(_ == 0)
  val cntC = s.count(_ == 1)
  val cntG = s.count(_ == 2)
  val cntT = s.count(_ == 3)
  val cnt = (if (cntA > 0) 1 else 0) max (if (cntC > 0) 1 else 0) max (if (cntG > 0) 1 else 0) max (if (cntT > 0) 1 else 0)

  println(BigInt(cnt).pow(n).mod(1000000007))
}


You are given two integers $$$A$$$ and $$$B$$$, calculate the number of pairs $$$(a, b)$$$ such that $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, and the equation $$$a \cdot b + a + b = conc(a, b)$$$ is true; $$$conc(a, b)$$$ is the concatenation of $$$a$$$ and $$$b$$$ (for example, $$$conc(12, 23) = 1223$$$, $$$conc(100, 11) = 10011$$$). $$$a$$$ and $$$b$$$ should not contain leading zeroes.

The first line contains $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case contains two integers $$$A$$$ and $$$B$$$ $$$(1 \le A, B \le 10^9)$$$.

Print one integer — the number of pairs $$$(a, b)$$$ such that $$$1 \le a \le A$$$, $$$1 \le b \le B$$$, and the equation $$$a \cdot b + a + b = conc(a, b)$$$ is true.

NoteThere is only one suitable pair in the first test case: $$$a = 1$$$, $$$b = 9$$$ ($$$1 + 9 + 1 \cdot 9 = 19$$$).

import java.io.BufferedInputStream
import java.util.Scanner

object Main extends App {
  val inputReader = new Scanner(new BufferedInputStream(System.in))
  val T = inputReader.nextInt()
  for (_ <- 0 until T) {
    val A = inputReader.nextLong()
    val B = inputReader.nextDouble()
    val log10B = Math.log10(B + 1.001).toLong
    println(A * log10B)
  }
}

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val Array(a, b) = readLine.split(" ").map(_.toLong)
        println(f2(a, b))
    }

    def f2(a: Long, b: Long): Long = {
        a * log10(b + 1)
    }
    def log10(x: Long): Long = {
        if (x < 10) 0 else log10(x / 10) + 1
    }
  }

  // ab + a + b = a * 10^(log(b)) + b => b + 1 = 10^log(b) (for b)

import scala.annotation.tailrec
import scala.io.StdIn._
object Main extends App {

  for (_ ← 0 until readInt) {
    val Array(a, b) = readLine.trim.split(' ').map(_.toLong)
    println(
      (1 to digit(b)).map(d ⇒ power(10, d) - 1).count(_ <= b) * a
    )
  }
  def power(base: Long, exp: Int): Long = {
    exp match {
      case 0 ⇒ 1L
      case 1 ⇒ base
      case _ ⇒ power(base, exp & 1) * power(base * base, exp >> 1)
    }
  }
  def digit(value: Long): Int = {
    value match {
      case 0 ⇒ 0
      case _ ⇒ 1 + digit(value / 10)
    }
  }
}

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val Array(a, b) = readLine.split(" ").map(_.toInt)
        println(f2(a, b))
    }

    def f2(a: Long, b: Long): Long = {
        a * log10(b)
    }
    def log10(x: Long): Long = {
        if (x < 10) 0 else log10(x / 10) + 1
    }
  }

  // ab + a = a * 10^(log(b)) => b + 1 = 10^log(b) (for b)

object Main {
    def main(args: Array[String]) = {
      val t = readInt
      (0 until t).foreach((x) => f1)
    }
    def f1(): Unit = {
        val Array(a, b) = readLine.split(" ").map(_.toLong)
        println(f2(a, b))
    }

    def f2(a: Long, b: Long): Long = {
        a * log10(b)
    }
    def log10(x: Long): Long = {
        if (x < 10) 0 else log10(x / 10) + 1
    }
  }

  // ab + a + b = a * 10^(log(b)) + b => b + 1 = 10^log(b) (for b)


Kamil likes streaming the competitive programming videos. His MeTube channel has recently reached $$$100$$$ million subscribers. In order to celebrate this, he posted a video with an interesting problem he couldn't solve yet. Can you help him?You're given a tree — a connected undirected graph consisting of $$$n$$$ vertices connected by $$$n - 1$$$ edges. The tree is rooted at vertex $$$1$$$. A vertex $$$u$$$ is called an ancestor of $$$v$$$ if it lies on the shortest path between the root and $$$v$$$. In particular, a vertex is an ancestor of itself.Each vertex $$$v$$$ is assigned its beauty $$$x_v$$$ — a non-negative integer not larger than $$$10^{12}$$$. This allows us to define the beauty of a path. Let $$$u$$$ be an ancestor of $$$v$$$. Then we define the beauty $$$f(u, v)$$$ as the greatest common divisor of the beauties of all vertices on the shortest path between $$$u$$$ and $$$v$$$. Formally, if $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ are the vertices on the shortest path between $$$u$$$ and $$$v$$$, then $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Here, $$$\gcd$$$ denotes the greatest common divisor of a set of numbers. In particular, $$$f(u, u) = \gcd(x_u) = x_u$$$.Your task is to find the sum$$$$$$ \sum_{u\text{ is an ancestor of }v} f(u, v). $$$$$$As the result might be too large, please output it modulo $$$10^9 + 7$$$.Note that for each $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. In particular, $$$\gcd(0, 0) = 0$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the number of vertices in the tree. The following line contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). The value $$$x_v$$$ denotes the beauty of vertex $$$v$$$. The following $$$n - 1$$$ lines describe the edges of the tree. Each of them contains two integers $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — the vertices connected by a single edge.

Output the sum of the beauties on all paths $$$(u, v)$$$ such that $$$u$$$ is ancestor of $$$v$$$. This sum should be printed modulo $$$10^9 + 7$$$.

NoteThe following figure shows all $$$10$$$ possible paths for which one endpoint is an ancestor of another endpoint. The sum of beauties of all these paths is equal to $$$42$$$:

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

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

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val n = ni()
    val x = nal(n)
    val (from, to) = na2(n - 1, -1)
    val g = packUGraph(n, from, to)
    val (_, p, q) = traceBfs(g)
    type Value = mutable.Map[Long, Int]
    def zero: Value = mutable.Map().withDefaultValue(0) // 変更加えるのでdefになってる
    val dp = Array.fill[Value](n)(zero)

    def merge(v: Value, x: Long): Value = {
      val res = zero
      res(x) = 1
      val it = v.iterator
      while(it.hasNext) {
        val (g, cnt) = it.next()
        res(gcd(g, x)) += cnt
      }
      res
    }

    var ans = 0L
    REP(n) { i =>
      val v = q(i)
      if (p(v) != -1) {
        dp(v) = merge(dp(p(v)), x(v))
      } else {
        dp(v) = zero + (x(v) -> 1)
      }
      val it = dp(v).iterator
      while(it.hasNext) {
        val (g, cnt) = it.next()
        ans += g % MOD * cnt % MOD
      }
    }
    debug(dp.mkString(" "))
    out.println(ans % MOD)
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a
    else gcd(b, a % b)
  }
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }
}


Slime has a sequence of positive integers $$$a_1, a_2, \ldots, a_n$$$.In one operation Orac can choose an arbitrary subsegment $$$[l \ldots r]$$$ of this sequence and replace all values $$$a_l, a_{l + 1}, \ldots, a_r$$$ to the value of median of $$$\{a_l, a_{l + 1}, \ldots, a_r\}$$$.In this problem, for the integer multiset $$$s$$$, the median of $$$s$$$ is equal to the $$$\lfloor \frac{|s|+1}{2}\rfloor$$$-th smallest number in it. For example, the median of $$$\{1,4,4,6,5\}$$$ is $$$4$$$, and the median of $$$\{1,7,5,8\}$$$ is $$$5$$$.Slime wants Orac to make $$$a_1 = a_2 = \ldots = a_n = k$$$ using these operations.Orac thinks that it is impossible, and he does not want to waste his time, so he decided to ask you if it is possible to satisfy the Slime's requirement, he may ask you these questions several times.

The first line of the input is a single integer $$$t$$$: the number of queries. The first line of each query contains two integers $$$n\ (1\le n\le 100\,000)$$$ and $$$k\ (1\le k\le 10^9)$$$, the second line contains $$$n$$$ positive integers $$$a_1,a_2,\dots,a_n\ (1\le a_i\le 10^9)$$$ The total sum of $$$n$$$ is at most $$$100\,000$$$.

The output should contain $$$t$$$ lines. The $$$i$$$-th line should be equal to 'yes' if it is possible to make all integers $$$k$$$ in some number of operations or 'no', otherwise. You can print each letter in lowercase or uppercase.

NoteIn the first query, Orac can't turn all elements into $$$3$$$.In the second query, $$$a_1=6$$$ is already satisfied.In the third query, Orac can select the complete array and turn all elements into $$$2$$$.In the fourth query, Orac can't turn all elements into $$$3$$$.In the fifth query, Orac can select $$$[1,6]$$$ at first and then select $$$[2,10]$$$.

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

  val t = readInt()

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

    val ans =
      an.contains(k) && an.sliding(3).exists {
        case Array(x, y, z) => x >= k && y <= k && z >= k || x >= k && y >= k || y >= k && z >= k
        case Array(x, y)    => x == k && y >= k || y == k && x >= k
        case Array(_)       => true
      }

    if (ans) println("yes")
    else println("no")
  }
}

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

  val t = readInt()

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

    val ans =
      an.contains(k) && an.sliding(3).exists {
        case Array(x, y, z) => x >= k && y <= k && z >= k || x >= k && y >= k || y >= k && z >= k
        case _              => true
      }

    if (ans) println("yes")
    else println("no")
  }
}


Asya loves animals very much. Recently, she purchased $$$n$$$ kittens, enumerated them from $$$1$$$ and $$$n$$$ and then put them into the cage. The cage consists of one row of $$$n$$$ cells, enumerated with integers from $$$1$$$ to $$$n$$$ from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were $$$n - 1$$$ partitions originally. Initially, each cell contained exactly one kitten with some number.Observing the kittens, Asya noticed, that they are very friendly and often a pair of kittens in neighboring cells wants to play together. So Asya started to remove partitions between neighboring cells. In particular, on the day $$$i$$$, Asya:  Noticed, that the kittens $$$x_i$$$ and $$$y_i$$$, located in neighboring cells want to play together.  Removed the partition between these two cells, efficiently creating a single cell, having all kittens from two original cells. Since Asya has never putted partitions back, after $$$n - 1$$$ days the cage contained a single cell, having all kittens.For every day, Asya remembers numbers of kittens $$$x_i$$$ and $$$y_i$$$, who wanted to play together, however she doesn't remember how she placed kittens in the cage in the beginning. Please help her and find any possible initial arrangement of the kittens into $$$n$$$ cells.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 150\,000$$$) — the number of kittens. Each of the following $$$n - 1$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — indices of kittens, which got together due to the border removal on the corresponding day. It's guaranteed, that the kittens $$$x_i$$$ and $$$y_i$$$ were in the different cells before this day.

For every cell from $$$1$$$ to $$$n$$$ print a single integer — the index of the kitten from $$$1$$$ to $$$n$$$, who was originally in it. All printed integers must be distinct. It's guaranteed, that there is at least one answer possible. In case there are multiple possible answers, print any of them.

NoteThe answer for the example contains one of several possible initial arrangements of the kittens.The picture below shows how the cells were united for this initial arrangement. Note, that the kittens who wanted to play together on each day were indeed in adjacent cells.

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 uf = new UnionFind(N)
    val sets = Array.fill[ArrayBuffer[Int]](N)(ArrayBuffer())
    REP(N) { i =>
      sets(i) += i
    }

    def merge(s1: ArrayBuffer[Int], s2: ArrayBuffer[Int]): ArrayBuffer[Int] = {
      if (s1.length > s2.length) {
        s1 ++= s2
        s1
      } else {
        s2 ++= s1
        s2
      }
    }

    REP(N - 1) { _ =>
      val v, u = ni() - 1
      val s1 = sets(uf.find(v))
      val s2 = sets(uf.find(u))
      uf.unite(v, u)
      sets(uf.find(u)) = merge(s1, s2)
    }

    val ans = sets(uf.find(0))
    out.println(ans.map(_+1).mkString(" "))
  }

  class UnionFind(val n: Int) {
    private val par = Array.ofDim[Int](n)
    par.indices foreach (i => par(i) = i)
    private val rank = Array.ofDim[Int](n)

    def find(x: Int): Int = {
      val stack = ListBuffer[Int]()
      def step(x: Int): Int = {
        if (par(x) == x) x
        else {
          stack += x
          step(par(x))
        }
      }

      val res = step(x)
      stack foreach (i => par(i) = res)
      res
    }

    def unite(x: Int, y: Int): Unit = {
      val x1 = find(x)
      val y1 = find(y)
      if (x1 != y1) {
        if (rank(x1) < rank(y)) {
          par(x1) = y1
        } else {
          par(y1) = x1
          if (rank(x1) == rank(y1)) rank(x1) += 1
        }
      }
    }
  }

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

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

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

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

  def debug(num: Long): Unit = {
    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 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
  }
}


Polycarp thinks about the meaning of life very often. He does this constantly, even when typing in the editor. Every time he starts brooding he can no longer fully concentrate and repeatedly presses the keys that need to be pressed only once. For example, instead of the phrase "how are you" he can type "hhoow aaaare yyoouu". Polycarp decided to automate the process of correcting such errors. He decided to write a plug-in to the text editor that will remove pairs of identical consecutive letters (if there are any in the text). Of course, this is not exactly what Polycarp needs, but he's got to start from something! Help Polycarp and write the main plug-in module. Your program should remove from a string all pairs of identical letters, which are consecutive. If after the removal there appear new pairs, the program should remove them as well. Technically, its work should be equivalent to the following: while the string contains a pair of consecutive identical letters, the pair should be deleted. Note that deleting of the consecutive identical letters can be done in any order, as any order leads to the same result.

The input data consists of a single line to be processed. The length of the line is from 1 to 2·105 characters inclusive. The string contains only lowercase Latin letters.

Print the given string after it is processed. It is guaranteed that the result will contain at least one character.

import scala.collection.mutable.ArrayBuffer

object Flask {

  def plugin(s: String): String = {
    var data:ArrayBuffer[Char] = new ArrayBuffer()
    var pos = 0
    var data_pos = 0
    data += '0'

    while (pos < s.size) {
      if (s(pos) == data(data_pos)) { data_pos -= 1 }
      else {
        data_pos += 1;
        if (data_pos == data.size)
          data += s(pos)
        else
          data(data_pos) = s(pos)
      }
      pos += 1
    }

    List.range(1, data_pos + 1).map(i => data(i)).mkString("")
  }

  def main(args: Array[String]): Unit = {
    println(plugin(readLine))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  var stack = List.empty[Char]
  str.foreach { ch =>
    if (stack.isEmpty || stack.head != ch)
      stack ::= ch
    else if (stack.nonEmpty) {
      stack = stack.tail
    }
  }
  println(stack.reverse.mkString)
}

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

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

  val input = sc.nextLine.toList

  def solve(): String = {

    @tailrec
    def loop(precedences: List[Char], remaining: List[Char]): List[Char] = {
      (precedences, remaining) match {
        case (xs, Nil)          => xs.reverse
        case (Nil, y :: ys)     => loop(y :: Nil, ys)
        case (x :: xs, y :: ys) => if (x == y) loop(xs, ys)
                                   else loop(y :: x :: xs, ys)
      }
    }

    loop(Nil, input).mkString
  }

  out.println(solve)
  out.close
}

object Main {
  def dedup(s: String): String =  {
    val stack = scala.collection.mutable.Stack[Char]()
    s.foreach{ c =>
      if (stack.headOption == Some(c)) stack.pop
      else stack.push(c)
    }
    stack.mkString.reverse
  }

  def main(args: Array[String]) = {
    var s = readLine()
    println(dedup(s))
  }
}

import scala.collection.mutable.Stack
object Main {
  def main(args: Array[String]):Unit = {
    val str = readLine()
    val stack = Stack[Char]()
    for (char <- str)
      if (stack.nonEmpty && stack.top == char)
        stack.pop()
      else
        stack.push(char);
    for (char <- stack.reverse)
      print(char)
    println()
  }
}

import scala.io.StdIn.readLine

object PlugIn {

  def processString(s: List[Char]) : List[Char] = {
    def process(c : List[Char], acc : List[Char]) : List[Char] = c match {
      case h1 :: h2 :: rest => if (h1 == h2)
                                    process(acc.head :: rest,acc.tail)
                          else process(h2 :: rest, h1 :: acc)
      case h1 :: rest => process(rest, h1:: acc)
      case Nil => acc.reverse.tail
    }
    val r = process(s, List('.'))
    //if (r == s.toList) r else processString(r)
    r

  }

  def main(args: Array[String]) {
    val s = readLine()
    println(processString(s.toList).mkString)
  }

}

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

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

  val input = sc.nextLine.toList

  def solve(): String = {

    @tailrec
    def innerLoop(acc: List[Char], cs: List[Char]): List[Char] = cs match {
        case x0 :: x1 :: xs if (x0 == x1) => innerLoop(acc, xs.dropWhile(_ == x0))
        case x :: xs                    => innerLoop(x :: acc, xs)
        case Nil => acc.reverse
      }

    @tailrec
    def outerLoop(acc: List[Char]): List[Char] = {
      val shortened = innerLoop(Nil, acc)
      if (acc == shortened) acc
      else outerLoop(shortened)
    }

    outerLoop(input).mkString
  }

  out.println(solve)
  out.close
}


The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.

The first line contains space-separated integers n and m  — the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n. It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.

Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on. If there are multiple correct orders, you are allowed to print any of them.

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

object D extends App {

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

  val Array(n, m) = readInts(2)
  val adj = Array.fill(n){ mutable.ArrayBuffer.empty[Int] }

  for (i <- 0 until m) {
    val Array(a, b) = readInts(2)
    adj(b - 1) += a - 1
  }

  val color = Array.fill(n)(0)
  var res = List[Int]()

  for (i <- adj.indices if (color(i) == 0)) dfsVisit(i)

  def dfsVisit(u: Int): Unit = {

    color(u) = 1
    for (v <- adj(u) if color(v) == 0) dfsVisit(v)

    res = (u + 1) :: res
  }

  println(res.mkString(" "))
}


Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.

The first line contains integer n (1 ≤ n ≤ 2000), number of GukiZ's students.  The second line contains n numbers a1, a2, ... an (1 ≤ ai ≤ 2000) where ai is the rating of i-th student (1 ≤ i ≤ n).

In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.

NoteIn the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position.

import java.util.Scanner

object CF551B extends App {
  var in = new Scanner(System.in)
  val n = in.nextInt()
  val a = (1 to n).map(i => in.nextInt())
  val b = a.map(i => a.count(j => j > i) + 1)
  println(b.mkString(" "))
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.InputStream
import java.io.PrintWriter
import scala.util.Sorting
object CF551A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

  def next():String = {
      while (!st.hasMoreTokens()){
        val currentLine = reader.readLine
            st=new StringTokenizer(currentLine)
      }
      return st.nextToken
  }

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

  def nextLong():Long = {
      return next.toLong
  }
  def nextDouble:Double = {
          return next.toDouble
      }
  }

  def main(args: Array[String]): Unit = {
    val in = new InputReader(System.in)
    val n = in.nextInt()
    val a = Array.fill(n) { in.nextInt()}
    val b = a.map { x => a.filter { y => y > x }.size + 1}
    println(b.mkString(" "))
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import java.io.InputStream
import java.io.PrintWriter
import scala.util.Sorting
object CF551A {

  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
  val reader=new BufferedReader(new InputStreamReader(stream), 32768);

  def next():String = {
      while (!st.hasMoreTokens()){
        val currentLine = reader.readLine
            st=new StringTokenizer(currentLine)
      }
      return st.nextToken
  }

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

  def nextLong():Long = {
      return next.toLong
  }
  def nextDouble:Double = {
          return next.toDouble
      }
  }

  def main(args: Array[String]): Unit = {
    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)
    val n = in.nextInt()
    var a: Array[Integer] = new Array[Integer](n)
    for(i <- 0 until n) {
      a(i) = in.nextInt()
    }
    val origin = a.clone()
    Sorting.quickSort(a)
    a = a.reverse

/*    for(i <- 0 until n) {
      out.print(a(i) + " ")
    }
    out.println

    for(i <- 0 until n) {
      out.print(origin(i) + " ")
    }
    out.println
*/
    for(i <- 0 to n-1) {
      var index = n-1
      for(j <- n-1 to 0 by -1) {
        if ( origin(i)==a(j)) {
          index = j+1
        }
      }
      out.print(index)
      if ( i == n-1)
        out.println()
      else out.print(" ")
    }

    out.flush
    out.close
  }
}

import java.util.StringTokenizer

object _551A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val b = a.map(i => a.filter(j => j > i).size + 1)
  println(b.mkString(" "))
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n).zipWithIndex.sortBy(_._1).reverse
    val ranks = new Array[Int](n)
    ranks(input(0)._2) = 1
    var curr = 1
    for(i <- 1 until n) {
      if(input(i)._1 == input(i-1)._1) {
        ranks(input(i)._2) = curr
      } else {
        ranks(input(i)._2) = i+1
        curr = i+1
      }
    }
    println(ranks.mkString(" "))
  }
}

/**
 * @author pvasilyev
 * @since 04 May 2016
 */
object A551 extends App {

  val n: Int = scala.io.StdIn.readInt()
  val a: Array[Int] = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val withIndex = a.zipWithIndex
  val sorted = withIndex.sortBy(_._1)(Ordering[Int].reverse)

  val result: Array[(Int, Int)] = Array.ofDim(n)
  for (i <- 0 until n) {
    if (i == 0) {
      result(0) = (1, sorted(0)._2)
    } else if (sorted(i)._1 < sorted(i - 1)._1) {
      result(i) = (i+1, sorted(i)._2)
    } else {
      result(i) = (result(i-1)._1, sorted(i)._2)
    }
  }
  println(result.sortBy(_._2).map(_._1).mkString(" "))

}

import scala.language.postfixOps
import java.io._

object CF_551A {
    def bin_search(arr: Array[Int], value: Int, b: Int, e: Int) : Int = {
        val mid : Int = (b+e)/2;
        if( b+1 >= e )
            b
        else if( arr(mid) <= value )
            bin_search(arr, value, mid, e)
        else
            bin_search(arr, value, b, mid)
    }

    def main(args: Array[String]) {
        val stdin = new BufferedReader(new InputStreamReader(System.in));
        val n = stdin.readLine.toInt;
        val list : Array[Int] = stdin.readLine.split(" ").toArray.map(_.toInt);
        val sorted : Array[Int] = list.sortBy( x => x );
        for( i <- 0 until list.length )
            print((list.length - bin_search(sorted, list(i), 0, list.length)).toString + " ");
        println("")
    }
}

object _551A extends CodeForcesApp {
  import scala.collection.mutable

  override type Input = List[Int]
  override type Output = List[Int]

  override def read(scanner: java.util.Scanner) = {
    import scanner._
    List.fill(nextInt)(nextInt)
  }

  override def solve(input: Input) = {
    input map {i => input.count(_ > i) + 1}
  }

  override def format(result: Output) = result mkString " "
}

/****************************** IGNORE BELOW *********************************/
abstract class CodeForcesApp extends App {
  /********************************[ I/O ]************************************/
  import java.util.Scanner
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(problem: String): String  = apply(new Scanner(problem))
  def apply(scanner: Scanner): String = format(solve(read(scanner)))
  println(apply(new Scanner(System.in)))
  /********************************[ lib ]************************************/
  import scala.collection.mutable
  case class Memo[I <% K, K, O](f: I => O) extends (I => O) {
    val cache = mutable.Map.empty[K, O]
    override def apply(x: I): O = cache.getOrElseUpdate(x, f(x))
  }
  type m_=>[I, O] = Memo[I, I, O]
  def when[A](condition: Boolean)(f: => A): Option[A] = if (condition) Some(f) else None
  /******************************[ solution ]*********************************/
  type Input
  type Output
  def read(scanner: Scanner): Input
  def solve(input: Input): Output
  def format(result: Output): String = result.toString
  def timeLimitSecond = 1
}

object A{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val a=Array.fill(n)(0)
    val r=Array.fill(n)(0)
    for(i<-0 until n){a(i)=nextInt}
    for(i<-0 until n){
      for(j<-0 until n){
        if(a(i)<a(j)){
          r(i)+=1
        }
      }
    }
    for(i<-0 until n){
      out.print(r(i)+1)
      out.print(" ")
    }
    out.println()
    //code ends here
    out.flush
    out.close
  }
}


Petya loves computer games. Finally a game that he's been waiting for so long came out!The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is calculated as the sum of the values of  for all i from 1 to n. The expression ⌊ x⌋ denotes the result of rounding the number x down to the nearest integer.At the beginning of the game Petya got k improvement units as a bonus that he can use to increase the skills of his character and his total rating. One improvement unit can increase any skill of Petya's character by exactly one. For example, if a4 = 46, after using one imporvement unit to this skill, it becomes equal to 47. A hero's skill cannot rise higher more than 100. Thus, it is permissible that some of the units will remain unused.Your task is to determine the optimal way of using the improvement units so as to maximize the overall rating of the character. It is not necessary to use all the improvement units.

The first line of the input contains two positive integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 107) — the number of skills of the character and the number of units of improvements at Petya's disposal. The second line of the input contains a sequence of n integers ai (0 ≤ ai ≤ 100), where ai characterizes the level of the i-th skill of the character.

The first line of the output should contain a single non-negative integer — the maximum total rating of the character that Petya can get using k or less improvement units.

NoteIn the first test case the optimal strategy is as follows. Petya has to improve the first skill to 10 by spending 3 improvement units, and the second skill to 10, by spending one improvement unit. Thus, Petya spends all his improvement units and the total rating of the character becomes equal to  lfloor frac{100}{10} rfloor +  lfloor frac{100}{10} rfloor = 10 + 10 =  20.In the second test the optimal strategy for Petya is to improve the first skill to 20 (by spending 3 improvement units) and to improve the third skill to 20 (in this case by spending 1 improvement units). Thus, Petya is left with 4 improvement units and he will be able to increase the second skill to 19 (which does not change the overall rating, so Petya does not necessarily have to do it). Therefore, the highest possible total rating in this example is .In the third test case the optimal strategy for Petya is to increase the first skill to 100 by spending 1 improvement unit. Thereafter, both skills of the character will be equal to 100, so Petya will not be able to spend the remaining improvement unit. So the answer is equal to .

/**
 * @author netman
 */

import java.io._
import scala._
import scala.Array._
import java.util.ArrayList
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  class InputReader(reader: BufferedReader) {

    var tokenizer: StringTokenizer = null;

    def this(stream: InputStream) = {
      this(new BufferedReader(new InputStreamReader(stream), (1 << 20)));
    }

    def this(f: File) = {
      this(new BufferedReader(new FileReader(f), (1 << 20)));
    }

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

    def nextInt(): Int = next().toInt

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

    def close() = reader.close();
  }

  class OutputWriter(writer: PrintWriter) {
    def this(stream: OutputStream) {
      this(new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream))));
    }

    def this(f: File) = {
      this(new PrintWriter(new BufferedWriter(new FileWriter(f))));
    }

    def print(x: Any) = writer.print(x);

    def println(x: Any) = writer.println(x);

    def close() = writer.close();
  }

  val in = new InputReader(System.in)
  val out = new OutputWriter(System.out)

  val maxDist = 10

  def main(args: Array[String]): Unit = {
    var v = Array.fill[ArrayList[Int]](maxDist + 1)(new ArrayList[Int])

    val n = in.nextInt
    val k = in.nextInt

    var a = new Array[Int](n)

    for (i <- 0 until n) {
      a(i) = in.nextInt
      if (a(i) != 100) {
        val y = a(i) / maxDist * maxDist + maxDist
        v(y - a(i)).add(i)
      }
    }

    var it = k
    var flag = true

    while (it > 0 && flag) {
      var i = 1
      var fnd = false
      while (i <= maxDist && !fnd) {
        if (!v(i).isEmpty) {
          fnd = true
        }
        else {
          i += 1
        }
      }
      if (i == maxDist + 1) {
        flag = false
      }
      else {
        a(v(i).get(v(i).size() - 1)) += 1
        if (a(v(i).get(v(i).size() - 1)) != 100) {
          val y = a(v(i).get(v(i).size() - 1)) / maxDist * maxDist + maxDist
          v(y - a(v(i).get(v(i).size() - 1))).add(v(i).get(v(i).size() - 1))
        }
        v(i).remove(v(i).size() - 1)
        it -= 1
      }
    }

    var res = 0L

    for (i <- 0 until n) {
      res += a(i) / 10
    }

    out.println(res)

    out.close
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val levelSoFar = data.map(_ / 10).sum
  val leftOvers = data.map(_ % 10).groupBy(x => x).map(x => x._1 -> x._2.length)
  val res = (9 to 1 by -1).foldLeft((0, k)) {
    case ((sum, 0), _) =>
      (sum, 0)
    case ((sum, left), i) =>
      val have = leftOvers.getOrElse(i, 0)
      val levelsMax = left / (10 - i)
      val levels = Math.min(levelsMax, have)
      (sum + levels, left - levels * (10 - i))
  }
  println(Math.min(res._1 + levelSoFar + res._2 / 10, n * 10))
}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {

    val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {
      accumulator
    } else {
      distributeSkills(accumulator)
    }

    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {
//    println("****")
//    println(accumulator)
    val sortedSkills: Seq[Int] = accumulator.skills.sortBy(x => ((x % 10, x)))
//    println(sortedSkills)
    val updatedSkills = sortedSkills
      .foldRight(accumulator.copy(skills = Seq.empty)) { (currentElement, result) =>

//      println(result)
      val gap = needTo10(currentElement)
//      println("need to 10: " + gap)
//      println("current: " + currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }

//    println("updated skills: " +updatedSkills)
    if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints >= needTo10(updatedSkills.skills.head)) {
      distributeSkills(updatedSkills.copy(skills = updatedSkills.skills))
    } else {
      updatedSkills
    }

  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)

    val currentSkills = readInts(numberOfSkills)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

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

import scala.collection.mutable

object C {

  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 n = nextInt
    var k = nextInt
    val ab = new Array[Int](n)
    val diff = new Array[(Int, Int)](n)
    for (i <- 0 until n) {
      ab(i) = nextInt
      diff(i) = ((ab(i) / 10 + 1) * 10 - ab(i), i)
    }
    val sorted = diff.sortBy(_._1).foreach(x => {
      if (k >= x._1 && ab(x._2) < 100) {
        ab(x._2) += x._1
        k -= x._1
      }
    })
    for (i <- 0 until n) {
      while (k >= 10 && ab(i) != 100) {
        ab(i) += 10
        k -= 10
      }
    }
    var rtg = 0
    for (i <- 0 until ab.length) {
      rtg += ab(i) / 10
    }
    out.println(rtg)
    return 0
  }
}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _581C extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, k) = (nextInt, nextInt)
  val skills = List.fill(n)(nextInt)
  if (k >= skills.map(100 - _).sum) {
    n*10
  } else {
    val upgrades = skills map {s => 10 - (s%10)} sorted
    var ans = skills.map(_/10).sum
    var left = k
    for {
      i <- upgrades if i <= left
    } {
      left -= i
      ans += 1
    }

    ans + (left/10)
  }
}) {
  override def format(result: Result) = super.format(result)
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

import java.util.Scanner

object Main extends App {

  val sc = new Scanner(System.in)
  val n = sc.nextInt
  var m = sc.nextInt

  val arr =
    Array
      .tabulate(n)(_ => sc.nextInt)
      .sortWith((a, b) => (a % 10) > (b % 10))

  var mx = 0
  var s1 = 0
  arr.indices.foreach(i => {
    val s = 10 - (arr(i) % 10)
    val t = if (s == 10) 0 else s
    if (m >= t) {
      arr(i) += t
      m -= t
    } else {
      m = 0
    }
    s1 += arr(i) / 10
    mx += 100 - arr(i)
  })

  println(s1 + (math.min(mx, m) / 10))
}

import scala.io.StdIn._

object C extends App {
  val input = readLine().split(" ").map(_.toLong)
  val k = input(1)

  val A = readLine().split(" ").map(_.toLong)

  def count(A: Array[Long], e: Long): (Array[Long], Long) = {
    var energy = e

    val B = A.zip(A).map { case (x: Long, y: Long) =>
      (x, if (y == 100) 0 else 10 - y % 10)
    }.sortWith(_._2 < _._2).map { case (x: Long, diff: Long) =>
      if (energy > 0) {
        val min = Math.min(energy, diff)
        energy -= min
        (x + min, 0)
      } else {
        (x, 0)
      }
    }
    (B.map(_._1), energy)
  }

  def count2(A: Array[Long], e: Long): Array[Long] = {
    var energy = e

    A.map { x =>
      if (energy > 0 && x < 100) {
        val min = Math.min(energy, 100 - x)
        energy -= min
        x + min
      } else {
        x
      }
    }
  }

  var answer = count(A, k)
  println(count2(answer._1, answer._2).map(_ / 10).sum)

}

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

//581C
object C_DevelopingSkills {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
    val n = Integer.parseInt(line1(0))
    val k = Integer.parseInt(line1(1))
    val skillsStr = br.readLine().split(" ")
    val skills = skillsStr.map { _.toInt}

//    val n = 1000
//    val k = 100000
//    val skills = Array.fill[Int](1000)(0)

    val start = System.nanoTime();

    val map = Map[Int, List[Int]](0->Nil,1->Nil,2->Nil,3->Nil,4->Nil,5->Nil,6->Nil,7->Nil,8->Nil,9->Nil)

    for(i <- skills) {
      val rest = i % 10
      val old = map.get(rest).get
      map.put(rest, i :: old)
    }

    var count = k
    var ind = 9

    while (count > 0 && ind >= 0 && (10 - ind) <= count) {
      val level = map.get(ind).get
      val levelRes = procLevel(level, (10 - ind))
      map.put(ind, levelRes._1) //replace current
      map.put(0, levelRes._2 ::: map.get(0).get) //update zero

      if (ind > 0) ind -= 1
      if (ind == 0) {
        procLevel0()
        count = 0
      }
    }

    println(calcPoints)

//    println("duration=" + (System.nanoTime() - start));

    def calcPoints(): Int = {
      var result = 0;
      for (level <- map) {
        for(i <- level._2) {
          if (i > 100) throw new RuntimeException("i > 100 " + i)
          result += (i/10).toInt
        }
      }
      result
    }

    def procLevel0() {
      var current = List[Int]()
      for (el <- map.get(0).get) {
        if (el < 100 && count >= 10) {
          val step = Math.min(100-el, count)
          current = el + step :: current
          count -= step
        } else {
          current = el :: current
        }
      }
      map.put(0, current)
    }

    def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {
      var current = List[Int]()
      var next = List[Int]()

      for (el <- level) {
        if (el < 100 && count >= step) {
          next = (el + step) :: next
          count -= step
        } else {
          current = el :: current
        }
      }
      (current, next)
    }
  }
}

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

//581C
object C_DevelopingSkills {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
    val n = Integer.parseInt(line1(0))
    val k = Integer.parseInt(line1(1))
    val skillsStr = br.readLine().split(" ")
    val skills = skillsStr.map { _.toInt}

//    val n = 100
//    val k = 10000
//    val skills = Array.fill[Int](100)(100)

    val emptyList = List[Int]()
    val map = Map[Int, List[Int]]()

    for(i <- skills) {
      val rest = i % 10
      val old = map.getOrElse(rest, emptyList)
      map.put(rest, i :: old)
    }

    var count = k
    var ind = 9
    var lastLevel0Count = count

    while (count > 0 && ind >= 0 && (10 - ind) <= count) {
      if (ind == 0) lastLevel0Count = count
      val level = map.getOrElse(ind, emptyList)
      if (level != Nil) {
        val levelRes = procLevel(level, (10 - ind))
        map.put(ind, levelRes._1) //replace current
        map.put(0, levelRes._2 ::: map.getOrElse(0, emptyList)) //update zero
      }

      if (ind > 0) ind -= 1
      else if (lastLevel0Count == count) count = 0
    }

    println(calcPoints)

    def calcPoints(): Int = {
      var result = 0;
      for (level <- map) {
        for(i <- level._2) {
          if (i > 100) throw new RuntimeException("i > 100 " + i)
          result += (i/10).toInt
        }
      }
      result
    }

    def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {
      var current = List[Int]()
      var next = List[Int]()

      for (el <- level) {
        if (el < 100 && count >= step) {
          next = (el + step) :: next
          count -= step
        } else {
          current = el :: current
        }
      }
      (current, next)
    }
  }
}

import java.io._
import scala.collection.mutable.Map
import java.util.LinkedList
import scala.collection.JavaConversions.asScalaIterator

//581C
object C_DevelopingSkills_fast {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
    val n = Integer.parseInt(line1(0))
    val k = Integer.parseInt(line1(1))
    val skillsStr = br.readLine().split(" ")
    val skills = skillsStr.map { _.toInt}

//    val n = 100000
//    val k = 10000000
//    val skills = Array.fill[Int](n)(1)

    val start = System.nanoTime();

    val map = Map[Int, LinkedList[Int]](0->new LinkedList,1->new LinkedList,
        2->new LinkedList,3->new LinkedList,4->new LinkedList,
        5->new LinkedList,6->new LinkedList,7->new LinkedList,8->new LinkedList,9->new LinkedList)

    for(i <- skills) {
      val rest = i % 10
      val old = map.get(rest).get
      old.add(i)
    }

    var count = k
    var ind = 9

    while (count > 0 && ind >= 0 && (10 - ind) <= count) {
      procLevel(ind)
      if (ind > 0) ind -= 1
      if (ind == 0) {
        procLevel0()
        count = 0
      }
    }

    println(calcPoints)

//    println("duration=" + (System.nanoTime() - start));

    def calcPoints(): Int = {
      var result = 0;
      for (level <- map) {
        val iter = level._2.iterator()
        while (iter.hasNext()) {
          val i = iter.next()
          if (i > 100) throw new RuntimeException("i > 100 " + i)
          result += (i/10).toInt
        }
      }
      result
    }

    def procLevel0() {
      val level = map.get(0).get
      val iter = level.listIterator(0)
      while (iter.hasNext()) {
        val el = iter.next()
        if (el < 100 && count >= 10) {
          val step = Math.min(100-el, count)
          iter.set(el + step)
          count -= step
        }
      }
    }

    def procLevel(ind: Int)= {
      val level = map.get(ind).get
      val next = map.get(0).get
      val step = 10 - ind
      val iter = level.iterator()
      for (el <- iter) {
        if (el < 100 && count >= step) {
          iter.remove()
          next.add(el + step)
          count -= step
        }
      }
    }
  }
}

import java.util.Scanner

import scala.collection.mutable
import scala.language.postfixOps

object TaskC extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  var k = sc.nextInt
  var res = 0
  var tens = 0

  val remainders = mutable.ListBuffer.empty[Int]

  0 until n foreach { _ =>
    val a = sc.nextInt

    val toMax = 100 - a
    val remainder = toMax % 10
    tens += toMax - remainder

    if (remainder != 0) remainders += remainder

    res += a / 10
  }

  remainders.sorted.foreach { r =>
    if (k >= r) {
      k -= r
      res += 1
    }
  }

  println(res + math.min(k, tens) / 10)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val levelSoFar = data.map(_ / 10).sum
  val leftOvers = data.map(_ % 10).groupBy(x => x).map(x => x._1 -> x._2.length)
  val res = (9 to 1 by -1).foldLeft((0, k)) {
    case ((sum, 0), _) =>
      (sum, 0)
    case ((sum, left), i) =>
      val have = leftOvers.getOrElse(i, 0)
      val levelsMax = left / (10 - i)
      val levels = Math.min(levelsMax, have)
      (sum + levels, left - levels * (10 - i))
  }
  println(Math.min(res._1 + levelSoFar, n * 10))
}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {

    val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {
      accumulator
    } else {
      distributeSkills(accumulator)
    }

    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {
    val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>
      val gap = needTo10(currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }

    if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {
      distributeSkills(Accumulator(updatedSkills.skills.sortBy(needTo10),updatedSkills.availablePoints))
    } else {
      updatedSkills
    }

  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)
    val currentSkills = readInts(numberOfSkills).sortBy(needTo10)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {

    val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {
      accumulator
    } else {
      distributeSkills(accumulator)
    }

    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {
    val updatedSkills = accumulator.skills.sortBy(x => x).sortBy(needTo10)
      .foldRight(accumulator.copy(skills = Seq.empty)) { (currentElement, result) =>

      val gap = needTo10(currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }

    if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {
      distributeSkills(updatedSkills.copy(skills = updatedSkills.skills))
    } else {
      updatedSkills
    }

  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)

    val currentSkills = readInts(numberOfSkills)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(skills: Seq[Int]) = skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {
    val skills = distributeSkills(accumulator).skills
    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {

    accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>
      val gap = needTo10(currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }
  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)
    val currentSkills = readInts(numberOfSkills).sortBy(needTo10)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {

    val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {
      accumulator
    } else {
      distributeSkills(accumulator)
    }

    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {
    val sortedSkills: Seq[Int] = accumulator.skills.sortBy(x => ((x % 10, x)))
    val updatedSkills = sortedSkills
      .foldRight(accumulator.copy(skills = Seq.empty)) { (currentElement, result) =>

      val gap = needTo10(currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }

    if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {
      distributeSkills(updatedSkills.copy(skills = updatedSkills.skills))
    } else {
      updatedSkills
    }

  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)

    val currentSkills = readInts(numberOfSkills)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {

    val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {
      accumulator
    } else {
      distributeSkills(accumulator)
    }

    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {

    val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>
      val gap = needTo10(currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }

    if (accumulator.skills.head < 100 && accumulator.availablePoints > needTo10(accumulator.skills.head)) {
      distributeSkills(updatedSkills)
    } else {
      updatedSkills
    }

  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)
    val currentSkills = readInts(numberOfSkills).sortBy(needTo10)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(accumulator: Accumulator) = accumulator.skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {

    val skills = if (accumulator.skills.isEmpty || accumulator.availablePoints == 0) {
      accumulator
    } else {
      distributeSkills(accumulator)
    }

    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {
    println("****")
    println(accumulator)
    val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>
      println(currentElement)
      println(result)
      val gap = needTo10(currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }

    if (updatedSkills.skills.head < 100 && updatedSkills.availablePoints > needTo10(updatedSkills.skills.head)) {
      distributeSkills(updatedSkills.copy(skills = updatedSkills.skills.sortBy(needTo10)))
    } else {
      updatedSkills
    }

  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)
    val currentSkills = readInts(numberOfSkills).sortBy(needTo10)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

object PetyaSkills {

  val in = io.Source.stdin.getLines()

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

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

  def floorSum(x: Int, res: Int) = res + x / 10

  def calculateRank(skills: Seq[Int]) = skills.foldRight(0)(floorSum)

  case class Accumulator(skills: Seq[Int], availablePoints: Int)

  def solve(accumulator: Accumulator): Int = {
    val skills = distributeSkills(accumulator).skills
    calculateRank(skills)
  }

  def distributeSkills(accumulator: Accumulator): Accumulator = {

    val updatedSkills = accumulator.skills.foldRight(Accumulator(Seq.empty, accumulator.availablePoints)) { (currentElement, result) =>
      println(result)
      val gap = needTo10(currentElement)
      if (result.availablePoints < gap || currentElement == 100) {
        val skillsWithUnchangedCurrentElement = result.skills.+:(currentElement)
        Accumulator(skillsWithUnchangedCurrentElement, result.availablePoints)
      } else {
        val updatedSkills = result.skills.+:(currentElement + gap)
        val availablePoints = result.availablePoints - gap
        Accumulator(updatedSkills, availablePoints)
      }
    }

    if (accumulator.skills.head < 100 && accumulator.availablePoints > needTo10(accumulator.skills.head)) {
      distributeSkills(updatedSkills)
    } else {
      updatedSkills
    }

  }

  def needTo10(element: Int): Int = {
    10 - element % 10
  }

  def main(args: Array[String]) {

    val Array(numberOfSkills, availablePoints) = readInts(2)
    val currentSkills = readInts(numberOfSkills).sortBy(needTo10)

    println(solve(Accumulator(currentSkills, availablePoints)))
  }

}

import annotation.tailrec, collection.mutable, util._, control.Breaks._, math.Ordering.Implicits._
import CodeForcesApp._
object _581C extends CodeForcesApp[Int]({scanner => import scanner._
  val (n, k) = (nextInt, nextInt)
  val skills = List.fill(n)(nextInt)
  if (k >= skills.map(100 - _).sum) {
    n*10
  } else {
    val potentials = for {
      skill <- skills
      target <- (((skill/10) + 1)*10) to 100 by 10
    } yield (target - skill, (target/10) - (skill/10))

    val strategy = potentials.sortBy {case (cost, points) => 1.0*points/cost} (desc)

    var ans = skills.map(_/10).sum
    var left = k
    for {
      (cost, points) <- strategy if left > 0
    } if (left >= cost) {
      //debug(left, ans, cost, points)
      left -= cost
      ans += points
    }
    ans
  }
}) {
  override def format(result: Result) = super.format(result)
}
/********************************************************************************************/
import java.util.Scanner
abstract class CodeForcesApp[A](solver: Scanner => A) {
  final type Result = A
  final def apply(problem: String): String = apply(new Scanner(problem))
  final def apply(scanner: Scanner): String = format(solver(scanner))
  def format(result: Result): String = result.toString
  final def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
object CodeForcesApp {
  final val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  final def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  final val modulus: Int = 1000000007
  final val eps: Double = 1e-9
  final def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  final def repeat[A](n: Int)(f: => A): Seq[A] = (1 to n).map(_ => f)
  final def desc[A: Ordering]: Ordering[A] = implicitly[Ordering[A]].reverse
  import scala.collection.mutable.{Map => Dict, Set => Bag}
  final def nil[A]: List[A] = List.empty[A]
  final def bag[A]: Bag[A] = Bag.empty[A]
  final def map[A] = new {
    def to[B](default: B): Dict[A, B] = Dict.empty[A, B] withDefaultValue default
  }
}

import scala.io.StdIn._

object C extends App {
  val input = readLine().split(" ").map(_.toLong)
  val n = input(0).toInt
  val k = input(1)

  val A = readLine().split(" ").map(_.toInt)

  var energy = k
  val B = A.zip(A).map { case (x: Int, y: Int) =>
    (x, if (y == 100) 0 else 10 - y % 10)
  }.sortWith(_._2 < _._2).map { case (x: Int, diff: Int) =>
    if (diff != 0 && energy >= diff) {
      energy -= diff
      (x + diff, 0)
    } else {
      (x, diff)
    }

  }

//  println("phase  1: " + B.mkString(" "))
//  println(energy)
  var idx = A.length - 1
  while (energy > 0 && idx >= 0) {
    if (B(idx)._1 < 100) {
      if (B(idx)._1 + energy <= 100) {
        B(idx) = (B(idx)._1 + energy.toInt, 0)
        energy = 0
      } else {
        B(idx) = (100, 0)
        energy -= (100 - B(idx)._1)
      }
    }

    idx -= 1
  }

//  println("phase  2: " + B.mkString(" "))
//  println(energy)
  println(B.map(_._1 / 10).sum)

}

import scala.io.StdIn._

object C extends App {
  val input = readLine().split(" ").map(_.toLong)
  val n = input(0).toInt
  val k = input(1)

  val A = readLine().split(" ").map(_.toLong)

  def count(A: Array[Long], e: Long): (Array[Long], Long) = {
    var energy = e

    val B = A.zip(A).map { case (x: Long, y: Long) =>
      (x, if (y == 100) 0 else 10 - y % 10)
    }.sortWith(_._2 < _._2).map { case (x: Long, diff: Long) =>
      val min = Math.min(energy, diff)
      energy -= min
      (x + min, 0)
    }

    (B.map(_._1), energy)
  }

  var answer = count(A, k)

//  println(answer._1.mkString(" "))
  if (answer._2 > 0) {
    answer = count(answer._1, answer._2)
  }
//  println(answer._1.mkString(" "))

  println(answer._1.map(_ / 10).sum)

}

import scala.io.StdIn._

object C extends App {
  val input = readLine().split(" ").map(_.toLong)
  val n = input(0).toInt
  val k = input(1)

  val A = readLine().split(" ").map(_.toInt)

  var energy = k
  val B = A.zip(A).map { case (x: Int, y: Int) =>
    (x, if (y == 100) 0 else 10 - y % 10)
  }.sortWith(_._2 < _._2).map { case (x: Int, diff: Int) =>
    if (x != 100 && energy >= diff.toLong) {
      energy -= diff
      (x + diff, 0)
    } else {
      val max = Math.max(energy, diff)
      (x, diff - max.toInt)
    }
  }

//  println(B.mkString(" "))

  val answer = B.map { case (x: Int, diff: Int) =>
    if (x != 100 && energy > 0 && energy >= diff.toLong) {
      energy -= diff
      (x + diff, 0)
    }
    (x, diff)
  }

//  println("phase  2: " + B.mkString(" "))
//  println(energy)
  println(answer.map(_._1 / 10).sum)

}

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

//581C
object C_DevelopingSkills {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
    val n = Integer.parseInt(line1(0))
    val k = Integer.parseInt(line1(1))
    val skillsStr = br.readLine().split(" ")
    val skills = skillsStr.map { _.toInt}

//    val n = 1000
//    val k = 100000
//    val skills = Array.fill[Int](1000)(0)

    val start = System.nanoTime();

    val map = Map[Int, List[Int]](0->Nil,1->Nil,2->Nil,3->Nil,4->Nil,5->Nil,6->Nil,7->Nil,8->Nil,9->Nil)

    for(i <- skills) {
      val rest = i % 10
      val old = map.get(rest).get
      map.put(rest, i :: old)
    }

    var count = k
    var ind = 9

    while (count > 0 && ind >= 0 && (10 - ind) <= count) {
      val level = map.get(ind).get
      val levelRes = procLevel(level, (10 - ind))
      map.put(ind, levelRes._1) //replace current
      map.put(0, levelRes._2 ::: map.get(0).get) //update zero

      if (ind > 0) ind -= 1
      if (ind == 0) {
        procLevel0()
        count = 0
      }
    }

    println(calcPoints)

    println("duration=" + (System.nanoTime() - start));

    def calcPoints(): Int = {
      var result = 0;
      for (level <- map) {
        for(i <- level._2) {
          if (i > 100) throw new RuntimeException("i > 100 " + i)
          result += (i/10).toInt
        }
      }
      result
    }

    def procLevel0() {
      var current = List[Int]()
      for (el <- map.get(0).get) {
        if (el < 100 && count >= 10) {
          val step = Math.min(100-el, count)
          current = el + step :: current
          count -= step
        } else {
          current = el :: current
        }
      }
      map.put(0, current)
    }

    def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {
      var current = List[Int]()
      var next = List[Int]()

      for (el <- level) {
        if (el < 100 && count >= step) {
          next = (el + step) :: next
          count -= step
        } else {
          current = el :: current
        }
      }
      (current, next)
    }
  }
}

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

//581C
object C_DevelopingSkills {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
    val n = Integer.parseInt(line1(0))
    val k = Integer.parseInt(line1(1))
//    println(s"input $n $k")
    val skillsStr = br.readLine().split(" ")
    val skills = skillsStr.map { _.toInt}
//    println("skills = " + skills.mkString(" "))

//    val n = 2
//    val k = 2
//    val skills = Array(99, 100)

    val emptyList = List[Int]()
    val map = Map[Int, List[Int]]()

    for(i <- skills) {
      val rest = i % 10
      val old = map.getOrElse(rest, emptyList)
      map.put(rest, i :: old)
    }

    var count = k
    var ind = 9

    while (count > 0 && ind > 0 && (10 - ind) <= count) {
      val level = map.getOrElse(ind, emptyList)
      if (level != Nil) {
        val levelRes = procLevel(level, (10 - ind))
        map.put(ind, levelRes._1) //replace current
        map.put(0, levelRes._2 ::: map.getOrElse(0, emptyList)) //update zero
      }

      if (ind > 0) ind -= 1
    }

    println(calcPoints)

    def calcPoints(): Int = {
      var result = 0;
      for (level <- map) {
        for(i <- level._2) {
          if (i > 100) throw new RuntimeException("i > 100 " + i)
          result += (i/10).toInt
        }
      }
      result
    }

    def procLevel(level: List[Int], step: Int): (List[Int], List[Int]) = {
      var current = List[Int]()
      var next = List[Int]()

      for (el <- level) {
        if (el < 100 && count >= step) {
          next = (el + step) :: next
          count -= step
        } else {
          current = el :: current
        }
      }
      (current, next)
    }
  }
}

import java.io._
import scala.collection.mutable.Map
import java.util.LinkedList
import scala.collection.JavaConversions.asScalaIterator

//581C
object C_DevelopingSkills_fast {

  def main(args: Array[String]): Unit = {
    val bis = new BufferedInputStream(System.in);
    val br = new BufferedReader(new InputStreamReader(bis));

    val line1 = br.readLine().split(" ")
    val n = Integer.parseInt(line1(0))
    val k = Integer.parseInt(line1(1))
    val skillsStr = br.readLine().split(" ")
    val skills = skillsStr.map { _.toInt}

//    val n = 1000
//    val k = 100000
//    val skills = Array.fill[Int](1000)(0)

    val start = System.nanoTime();

    val map = Map[Int, LinkedList[Int]](0->new LinkedList,1->new LinkedList,
        2->new LinkedList,3->new LinkedList,4->new LinkedList,
        5->new LinkedList,6->new LinkedList,7->new LinkedList,8->new LinkedList,9->new LinkedList)

    for(i <- skills) {
      val rest = i % 10
      val old = map.get(rest).get
      old.add(i)
    }

    var count = k
    var ind = 9

    while (count > 0 && ind >= 0 && (10 - ind) <= count) {
      procLevel(ind)
      if (ind > 0) ind -= 1
      if (ind == 0) {
        procLevel0()
        count = 0
      }
    }

    println(calcPoints)

//    println("duration=" + (System.nanoTime() - start));

    def calcPoints(): Int = {
      var result = 0;
      for (level <- map) {
        val iter = level._2.iterator()
        while (iter.hasNext()) {
          val i = iter.next()
          if (i > 100) throw new RuntimeException("i > 100 " + i)
          result += (i/10).toInt
        }
      }
      result
    }

    def procLevel0() {
      val level = map.get(0).get
      val iter = level.listIterator(0)
      while (iter.hasNext()) {
        val el = iter.next()
        if (el < 100 && count >= 10) {
          val step = Math.min(100-el, count)
          iter.set(el + step)
          count -= step
        }
      }
    }

    def procLevel(ind: Int)= {
      val level = map.get(ind).get
      val next = map.get(ind-1).get
      val step = 10 - ind
      val iter = level.iterator()
      for (el <- iter) {
        if (el < 100 && count >= step) {
          level.remove()
          next.add(el + step)
          count -= step
        }
      }
    }
  }
}