Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.After n - 1 steps there is only one number left. Can you make this number equal to 24?

The first line contains a single integer n (1 ≤ n ≤ 105).

If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes). If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  if (n <= 3) println("NO")
  else if (n % 2 == 0) {
    println("YES")
    println("1 * 2 = 2")
    println("2 * 3 = 6")
    println("6 * 4 = 24")
    (5 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
      println("24 * 1 = 24")
    }

  } else {
    println("YES")
    println("2 - 1 = 1")
    println("1 + 3 = 4")
    println("4 * 5 = 20")
    println("20 + 4 = 24")
    (6 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
      println("24 * 1 = 24")
    }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C268A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C268A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()

    val notPossible = Array(1, 2, 3)
    if(notPossible.contains(n)) {
      out.println("NO")
    } else if(n == 4) {
      out.println("YES")
      out.println("4 * 3 = 12")
      out.println("12 * 2 = 24")
      out.println("24 * 1 = 24")
    } else if(n==5) {
      out.println("YES")
      out.println("5 - 3 = 2")
      out.println("4 * 2 = 8")
      out.println("2 + 1 = 3")
      out.println("8 * 3 = 24")
    } else {
      out.println("YES")
      out.println("6 * 4 = 24")
      out.println("1 + 2 = 3")
      out.println("3 - 3 = 0")
      out.println("0 * 5 = 0")
      REP(n + 1) { i =>
        if(i > 6) {
          out.println(s"$i * 0 = 0")
        }
      }
      out.println("24 + 0 = 24")
    }
  }
}

import scala.annotation.tailrec

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)

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

  if (n < 4) println("NO")
  else {
    println("YES")
    solve(n)
  }

  Console.flush

  @tailrec
  def solve(n: Int): Unit = {
    if (n == 4) {
      println("1 * 2 = 2")
      println("2 * 3 = 6")
      println("6 * 4 = 24")
    } else if (n == 5) {
      println("5 - 3 = 2")
      println("2 + 1 = 3")
      println("3 * 2 = 6")
      println("6 * 4 = 24")
    } else {
      println(s"$n - ${n - 1} = 1")
      println("1 * 1 = 1")
      solve(n - 2)
    }
  }

}

object TwentyFour extends App {
  sealed trait Op {
    def apply(a: Int, b: Int): Int
  }
  case object Times extends Op {
    override def apply(a: Int, b: Int) = a * b
    override def toString = "*"
  }
  case object Plus extends Op {
    override def apply(a: Int, b: Int) = a + b
    override def toString = "+"
  }
  case object Minus extends Op {
    override def apply(a: Int, b: Int) = a - b
    override def toString = "-"
  }

  case class Equation(l: Int, op: Op, r: Int) {
    val res = op(l, r)
    override def toString = s"$l $op $r = $res"
  }

  object EquationBuilder {
    implicit def intToEquationBuilder(i: Int) = EquationBuilder(i)
  }
  case class EquationBuilder(i: Int) {
    def plus(j: Int) = Equation(i, Plus, j)
    def times(j: Int) = Equation(i, Times, j)
    def minus(j: Int) = Equation(i, Minus, j)
  }

  // The work
  val n = io.Source.stdin.getLines.next.toInt
  if(n < 4) println("NO")
  else {
    import EquationBuilder._
    val fourSolution = Vector(
      4 times 2, // = 8
      8 times 3, // = 24
      24 times 1)
    val fiveSolution = Vector(
      5 minus 2, // = 3
      3 plus 3, // = 6
      4 times 6, // = 24
      24 times 1)
    def incSolution(i: Int) = Vector(
      // assume we have collapsed all i-2 into a single 24
      i minus (i - 1), // = 1
      24 times 1)
    def solution(i: Int) = {
      if(i % 2 == 0) {
        fourSolution ++ ((3 to i/2) map (_ * 2) flatMap incSolution)
      } else {
        fiveSolution ++ ((3 to i/2) map (_ * 2 + 1) flatMap incSolution)
      }
    }
    println("YES")
    println(solution(n).mkString("\n"))
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  if (n <= 3) println("NO")
  else if (n % 2 == 0) {
    println("YES")
    println("1 * 2 = 2")
    println("2 * 3 == 6")
    println("6 * 4 = 24")
    (5 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
    }
    println("24 * 1 = 24")
  } else {
    println("YES")
    println("2 - 1 = 1")
    println("1 + 3 = 4")
    println("4 * 5 = 20")
    (6 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
    }
    println("24 * 1 = 24")
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  if (n <= 3) println("NO")
  else if (n % 2 == 0) {
    println("YES")
    println("1 * 2 = 2")
    println("2 * 3 = 6")
    println("6 * 4 = 24")
    (5 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
    }
    println("24 * 1 = 24")
  } else {
    println("YES")
    println("2 - 1 = 1")
    println("1 + 3 = 4")
    println("4 * 5 = 20")
    (6 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
    }
    println("24 * 1 = 24")
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  if (n <= 3) println("NO")
  else if (n % 2 == 0) {
    println("YES")
    println("1 * 2 = 2")
    println("2 * 3 = 6")
    println("6 * 4 = 24")
    (5 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
      println("24 * 1 = 24")
    }

  } else {
    println("YES")
    println("2 - 1 = 1")
    println("1 + 3 = 4")
    println("4 * 5 = 20")
    (6 to n by 2).foreach { i =>
      println(s"${i + 1} - $i = 1")
      println("24 * 1 = 24")
    }
  }
}

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

import scala.reflect.ClassTag

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("src/resource/problem.in"))),
            new PrintWriter(new File("src/resource/problem.out"))
          )
        }
      new C268A(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true

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

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

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

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

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

    def ns(n: Int): Array[Char] = ns().toCharArray

    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)

    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }

    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }

    def nal(n: Int): Array[Long] = map(n)(_ => nl())

    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n)(_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while (i < N) {
      f(i);
      i += 1
    }
  }

  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while (i >= offset) {
      f(i);
      i -= 1
    }
  }

  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

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

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

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

class C268A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val n = ni()

    val notPossible = Array(1, 2, 3, 5)
    if(notPossible.contains(n)) {
      out.println("NO")
    } else if(n == 4) {
      out.println("YES")
      out.println("4 * 3 = 12")
      out.println("12 * 2 = 24")
      out.println("24 * 1 = 24")
    } else {
      out.println("YES")
      out.println("6 * 4 = 24")
      out.println("1 + 2 = 3")
      out.println("3 - 3 = 0")
      out.println("0 * 5 = 0")
      REP(n + 1) { i =>
        if(i > 6) {
          out.println(s"$i * 0 = 0")
        }
      }
      out.println("24 + 0 = 24")
    }
  }
}

object TwentyFour extends App {
  sealed trait Op {
    def apply(a: Int, b: Int): Int
  }
  case object Times extends Op {
    override def apply(a: Int, b: Int) = a * b
    override def toString = "*"
  }
  case object Plus extends Op {
    override def apply(a: Int, b: Int) = a + b
    override def toString = "+"
  }
  case object Minus extends Op {
    override def apply(a: Int, b: Int) = a - b
    override def toString = "-"
  }

  case class Equation(l: Int, op: Op, r: Int) {
    val res = op(l, r)
    override def toString = s"$l $op $r = $res"
  }

  object EquationBuilder {
    implicit def intToEquationBuilder(i: Int) = EquationBuilder(i)
  }
  case class EquationBuilder(i: Int) {
    def plus(j: Int) = Equation(i, Plus, j)
    def times(j: Int) = Equation(i, Times, j)
    def minus(j: Int) = Equation(i, Minus, j)
  }

  // The work
  val n = io.Source.stdin.getLines.next.toInt
  if(n < 4) println("NO")
  else {
    import EquationBuilder._
    val fourSolution = Vector(
      4 times 2, // = 8
      8 times 3, // = 24
      24 times 1)
    val fiveSolution = Vector(
      5 minus 2, // = 3
      3 plus 3, // = 6
      4 times 6, // = 24
      24 times 1)
    def incSolution(i: Int) = Vector(
      // assume we have collapsed all i-2 into a single 24
      i minus (i - 1), // = 1
      24 times 1)
    def solution(i: Int) = {
      if(i % 2 == 0) {
        fourSolution ++ ((2 to i/2) map (_ * 2) flatMap incSolution)
      } else {
        fiveSolution ++ ((3 to i/2) map (_ * 2 + 1) flatMap incSolution)
      }
    }
    println("YES")
    println(solution(n).mkString("\n"))
  }
}


This problem differs from the next one only in the presence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$. Actually, this problem is a subtask of the problem D2 from the same contest and the solution of D2 solves this subtask too.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally,  if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$;  if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$. All numbers in this array are of equal length (that is, they consist of the same number of digits). Your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array. All numbers $$$a_1, a_2, \dots, a_n$$$ are of equal length (that is, they consist of the same number of digits).

Print the answer modulo $$$998\,244\,353$$$.

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

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

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

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

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

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

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

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

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

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

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

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

  /*
    * 10^18までのpowを配列で用意しておく
    */
  val pow10 = Array.ofDim[Long](30)
  pow10(0) = 1
  REP(pow10.length - 1)(i => pow10(i + 1) = pow10(i) * 10 % MOD)

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val MAX = 10
    val D = Array.ofDim[Int](MAX)
    REP(N) { i =>
      D(log10(A(i))) += 1
    }
    debug(D)

    var ans = 0L
    def contributeX(x: Int): Unit = {
      var a = x
      REP(MAX) { i =>
        val d = a % 10
        REP(MAX) { j =>
          val k = i + (min(i, j) + 1)
          ans += pow10(k) * d % MOD * D(j) % MOD
          debug(s"contributeX i:$i j:$j k:$k d:$d Dj:${D(j)} ans:$ans")
        }
        a /= 10
      }
      ans %= MOD
    }

    def contributeY(y: Int): Unit = {
      var a = y
      REP(MAX) { i =>
        val d = a % 10
        REP(MAX) { j =>
          val k = i + min(i - 1, j) + 1
          ans += pow10(k) * d % MOD * D(j) % MOD
          debug(s"contributeY i:$i j:$j k:$k d:$d Dj:${D(j)} ans:$ans")
        }
        a /= 10
      }
      ans %= MOD
    }

    REP(N) { i =>
      contributeX(A(i))
      contributeY(A(i))
    }

    out.println(ans)
  }

  /**
    * @return log10の整数値
    */
  def log10(x: Long): Int = {
    var a = x
    var i = 0
    while(a >= 10) {
      a /= 10
      i += 1
    }
    i
  }
}

import java.io.FileInputStream
import scala.collection.mutable.TreeSet

object HelloWorld {

    import scala.io.StdIn.{readInt, readLine}

    private val MOD = 998244353
    private val pow10: Array[Long] = new Array[Long](31)
    pow10(0) = 1
    for (i <- 1 until 31) {
        pow10(i) = mult(pow10(i - 1), 10)
    }

    def add(a: Long, b: Long): Long = {
        var tmp = a + b
        if (tmp >= MOD) tmp -= MOD
        if (tmp < 0) tmp += MOD
        tmp
    }

    def mult(a: Long, b: Long): Long = (a * b) % MOD

    def f(aOrig: Long): Long = {
        var deg = 0
        var ans: Long = 0
        var a = aOrig
        while (a > 0) {
            val digit = a % 10L
            ans = add(ans, mult(digit, pow10(deg)))
            ans = add(ans, mult(digit, pow10(deg + 1)))
            deg += 2
            a /= 10L
        }
        ans
    }

    def main(args: Array[String]): Unit = {
        val n = readInt()
        val arr: Array[Long] = readLine().split(" ").map(_.toLong)
        val result = arr.map(x => mult(n, f(x)))
            .reduceLeft((acc: Long, x:Long) => add(acc, x))
        println(result)
    }
}


There are n points on a straight line, and the i-th point among them is located at xi. All these coordinates are distinct.Determine the number m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

The first line contains a single integer n (3 ≤ n ≤ 100 000) — the number of points. The second line contains a sequence of integers x1, x2, ..., xn ( - 109 ≤ xi ≤ 109) — the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.

Print a single integer m — the smallest number of points you should add on the line to make the distances between all neighboring points equal.

NoteIn the first example you can add one point with coordinate 0.In the second example the distances between all neighboring points are already equal, so you shouldn't add anything.

object B {
   def gcd(a:Int, b:Int) : Int = {
      if (b == 0) {
         return a
      }
      return gcd(b, a%b)
   }
   def main(args: Array[String]) {
      val N = scala.io.StdIn.readLine().toInt
      val A = scala.io.StdIn.readLine().split(' ').map(_.toInt).sorted
      var divisor = 0
      for (i <- 1 to A.length-1) {
         val gap = Math.abs(A(i) - A(i-1))
         divisor = gcd(divisor, gap)
      }
      var res = 0
      for (i <- 1 to A.length-1) {
         val gap = Math.abs(A(i) - A(i-1))
         res += gap / divisor - 1
      }
      println(res)
   }
}


There are n servers in a laboratory, each of them can perform tasks. Each server has a unique id — integer from 1 to n.It is known that during the day q tasks will come, the i-th of them is characterized with three integers: ti — the moment in seconds in which the task will come, ki — the number of servers needed to perform it, and di — the time needed to perform this task in seconds. All ti are distinct.To perform the i-th task you need ki servers which are unoccupied in the second ti. After the servers begin to perform the task, each of them will be busy over the next di seconds. Thus, they will be busy in seconds ti, ti + 1, ..., ti + di - 1. For performing the task, ki servers with the smallest ids will be chosen from all the unoccupied servers. If in the second ti there are not enough unoccupied servers, the task is ignored.Write the program that determines which tasks will be performed and which will be ignored.

The first line contains two positive integers n and q (1 ≤ n ≤ 100, 1 ≤ q ≤ 105) — the number of servers and the number of tasks.  Next q lines contains three integers each, the i-th line contains integers ti, ki and di (1 ≤ ti ≤ 106, 1 ≤ ki ≤ n, 1 ≤ di ≤ 1000) — the moment in seconds in which the i-th task will come, the number of servers needed to perform it, and the time needed to perform this task in seconds. The tasks are given in a chronological order and they will come in distinct seconds.

Print q lines. If the i-th task will be performed by the servers, print in the i-th line the sum of servers' ids on which this task will be performed. Otherwise, print -1.

NoteIn the first example in the second 1 the first task will come, it will be performed on the servers with ids 1, 2 and 3 (the sum of the ids equals 6) during two seconds. In the second 2 the second task will come, it will be ignored, because only the server 4 will be unoccupied at that second. In the second 3 the third task will come. By this time, servers with the ids 1, 2 and 3 will be unoccupied again, so the third task will be done on all the servers with the ids 1, 2, 3 and 4 (the sum of the ids is 10).In the second example in the second 3 the first task will come, it will be performed on the servers with ids 1 and 2 (the sum of the ids is 3) during three seconds. In the second 5 the second task will come, it will be performed on the server 3, because the first two servers will be busy performing the first task.

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

object _747C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, q = read[Int]
    val expiry = Array.ofDim[Int](n)

    repeat(q) {
      val t, k, d = read[Int]

      val available = expiry.indices.filter(i => expiry(i) < t)

      val ans = if (available.length < k) {
        -1
      } else {
        var acc = 0
        available.take(k) foreach {i =>
          acc += i + 1
          expiry(i) = t + d - 1
        }
        acc
      }
      writeLine(ans)
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

object _747C extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll, writeLine}
    val n, q = read[Int]
    val expiry = Array.ofDim[Int](n)

    repeat(q) {
      val t, k, d = read[Int]
      val available = expiry.zipWithIndex.collect {
        case (e, i) if e < t => (e, i)
      }
      val ans = if (available.length < k) {
        -1
      } else {
        var acc = 0
        available.sorted.take(k) foreach {
          case (_, i) =>
            acc += i + 1
            expiry(i) = t + d - 1
        }
        acc
      }
      writeLine(ans)
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


In this problem you will have to deal with a real algorithm that is used in the VK social network.As in any other company that creates high-loaded websites, the VK developers have to deal with request statistics regularly. An important indicator reflecting the load of the site is the mean number of requests for a certain period of time of T seconds (for example, T = 60 seconds = 1 min and T = 86400 seconds = 1 day). For example, if this value drops dramatically, that shows that the site has access problem. If this value grows, that may be a reason to analyze the cause for the growth and add more servers to the website if it is really needed.However, even such a natural problem as counting the mean number of queries for some period of time can be a challenge when you process the amount of data of a huge social network. That's why the developers have to use original techniques to solve problems approximately, but more effectively at the same time.Let's consider the following formal model. We have a service that works for n seconds. We know the number of queries to this resource at at each moment of time t (1 ≤ t ≤ n). Let's formulate the following algorithm of calculating the mean with exponential decay. Let c be some real number, strictly larger than one.// setting this constant value correctly can adjust   // the time range for which statistics will be calculateddouble c = some constant value; // as the result of the algorithm's performance this variable will contain // the mean number of queries for the last // T seconds by the current moment of timedouble mean = 0.0; for t = 1..n: // at each second, we do the following:    // at is the number of queries that came at the last second;    mean = (mean + at / T) / c;Thus, the mean variable is recalculated each second using the number of queries that came at that second. We can make some mathematical calculations and prove that choosing the value of constant c correctly will make the value of mean not very different from the real mean value ax at t - T + 1 ≤ x ≤ t. The advantage of such approach is that it only uses the number of requests at the current moment of time and doesn't require storing the history of requests for a large time range. Also, it considers the recent values with the weight larger than the weight of the old ones, which helps to react to dramatic change in values quicker.However before using the new theoretical approach in industrial programming, there is an obligatory step to make, that is, to test its credibility practically on given test data sets. Your task is to compare the data obtained as a result of the work of an approximate algorithm to the real data. You are given n values at, integer T and real number c. Also, you are given m moments pj (1 ≤ j ≤ m), where we are interested in the mean value of the number of queries for the last T seconds. Implement two algorithms. The first one should calculate the required value by definition, i.e. by the formula . The second algorithm should calculate the mean value as is described above. Print both values and calculate the relative error of the second algorithm by the formula , where approx is the approximate value, obtained by the second algorithm, and real is the exact value obtained by the first algorithm.

The first line contains integer n (1 ≤ n ≤ 2·105), integer T (1 ≤ T ≤ n) and real number c (1 < c ≤ 100) — the time range when the resource should work, the length of the time range during which we need the mean number of requests and the coefficient c of the work of approximate algorithm. Number c is given with exactly six digits after the decimal point. The next line contains n integers at (1 ≤ at ≤ 106) — the number of queries to the service at each moment of time. The next line contains integer m (1 ≤ m ≤ n) — the number of moments of time when we are interested in the mean number of queries for the last T seconds. The next line contains m integers pj (T ≤ pj ≤ n), representing another moment of time for which we need statistics. Moments pj are strictly increasing.

Print m lines. The j-th line must contain three numbers real, approx and error, where:    is the real mean number of queries for the last T seconds;  approx is calculated by the given algorithm and equals mean at the moment of time t = pj (that is, after implementing the pj-th iteration of the cycle);   is the relative error of the approximate algorithm.  The numbers you printed will be compared to the correct numbers with the relative or absolute error 10 - 4. It is recommended to print the numbers with at least five digits after the decimal point.

object Main extends App {
import java.awt.Point
import java.io._
import java.math.BigInteger
import java.util._
import java.lang.Math._
import scala.collection.JavaConversions._

new Thread(null, new B(), "", 256 * (1L << 20)).start()

class B extends Runnable {

  var in: BufferedReader = _

  var out: PrintWriter = _

  var tok: StringTokenizer = new StringTokenizer("")

  def run() {
    try {
      val t1 = System.currentTimeMillis()
      in = new BufferedReader(new InputStreamReader(System.in))
      out = new PrintWriter(System.out)
      Locale.setDefault(Locale.US)
      solve()
      in.close()
      out.close()
    } catch {
      case t: Throwable => {
        t.printStackTrace(System.err)
        System.exit(-1)
      }
    }
  }

  private def readString(): String = {
    while (!tok.hasMoreTokens()) {
      tok = new StringTokenizer(in.readLine())
    }
    tok.nextToken()
  }

  private def readInt(): Int = {
    java.lang.Integer.parseInt(readString())
  }

  private def readLong(): Long = java.lang.Long.parseLong(readString())

  private def readDouble(): Double = {
    java.lang.Double.parseDouble(readString())
  }

  private def solve() {
    val n = readInt()
    val T = readInt()
    val c = readDouble()
    val a = Array.ofDim[Long](n)
    val sum = Array.ofDim[Long](n)
    val true_average = Array.ofDim[Double](n)
    val approximate_average = Array.ofDim[Double](n)
    for (i <- 0 until n) {
      a(i) = readLong()
      sum(i) = a(i) + (if (i > 0) sum(i - 1) else 0)
      approximate_average(i) = ((if (i > 0) approximate_average(i - 1) else 0) + a(i).toDouble / T) /
        c
      true_average(i) = ((sum(i) - (if (i - T >= 0) sum(i - T) else 0)).toDouble /
        T)
    }
    val m = readInt()
    for (i <- 0 until m) {
      val q = readInt() - 1
      out.println(true_average(q) + " " + approximate_average(q) + " " +
        Math.abs(approximate_average(q) - true_average(q)) / true_average(q))
    }
  }

}
}


Petya has n positive integers a1, a2, ..., an. His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different digits Vasya used distinct letters from 'a' to 'j'.Your task is to restore Petya's numbers. The restored numbers should be positive integers without leading zeros. Since there can be multiple ways to do it, determine the minimum possible sum of all Petya's numbers after the restoration. It is guaranteed that before Vasya's joke all Petya's numbers did not have leading zeros.

The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of Petya's numbers. Each of the following lines contains non-empty string si consisting of lowercase Latin letters from 'a' to 'j' — the Petya's numbers after Vasya's joke. The length of each string does not exceed six characters.

Determine the minimum sum of all Petya's numbers after the restoration. The restored numbers should be positive integers without leading zeros. It is guaranteed that the correct restore (without leading zeros) exists for all given tests.

NoteIn the first example, you need to replace the letter 'a' with the digit 1, the letter 'b' with the digit 0, the letter 'd' with the digit 2, the letter 'e' with the digit 3, and the letter 'j' with the digit 4. So after the restoration numbers will look like [10, 23, 14]. The sum of them is equal to 47, which is the minimum possible sum of the numbers after the correct restoration.In the second example the numbers after the restoration can look like: [120468, 3579, 2468, 10024, 3]. In the second example the numbers after the restoration can look like: [11, 22, 11].

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

object MinimumSum extends App {
  val cantBeZero: mutable.Set[Char] = mutable.Set.empty
  val counts: mutable.ArrayBuffer[(Char, Int)] = mutable.ArrayBuffer()
  for (c <- 'a' to 'j') counts.append((c, 0))
  (for (_ <- 0 until StdIn.readLine().toInt) yield StdIn.readLine())
    .foreach(str => {
      cantBeZero += str.charAt(0)
      for (
        offset <- str.length - 1 to(0, -1)
      ) {
        val char: Char = str.charAt(offset)
        val sum = math.pow(10, str.length - 1 - offset).toInt
        counts(char - 'a') = (char, counts(char - 'a')._2 + sum)
      }
    })
  val availableChars: mutable.ListBuffer[Int] = mutable.ListBuffer()
  availableChars.appendAll(0 to 9)
  var totalSum = 0
  counts.sortBy(-_._2).foreach { case (char, sum) =>
    var digit = availableChars.head
    if (digit == 0 && cantBeZero.contains(char)) {
      digit = availableChars.remove(1)
    } else {
      availableChars.remove(0)
    }
    totalSum = totalSum + digit * sum
  }
  println(totalSum)
}

object Main extends App {

  import io.StdIn

  val n = StdIn.readInt

  val cnt = new Array[Int](10)
  val notZero = new Array[Boolean](10)

  for (i <- 0 until n) {
    val s = StdIn.readLine()
    val l = s.length
    notZero(s.charAt(0) - 'a') = true
    var d = 1
    for (i <- 0 to l-1) {
      val ch = s(l - i - 1)
      cnt(ch - 'a') += d
      d *= 10
    }
  }

  var cur = 1
  var usedZero = false
  var ans = 0

  for (i <- 0 to 9) {

    var mx = 0
    for (j <- 0 to 9)
      if (cnt(j) > cnt(mx)) mx = j
    if (!usedZero && !notZero(mx)) {
      usedZero = true
    }
    else {
      ans += cnt(mx) * cur
      cur += 1
    }

    cnt(mx) = 0
  }

  println(ans)

}

object Main extends App {

  import io.StdIn

  val n = StdIn.readInt

  val cnt = new Array[Int](10)
  val notZero = new Array[Boolean](10)

  for (i <- 0 until n) {
    val s = StdIn.readLine()
    val l = s.length
    if (l > 1) notZero(s.charAt(0) - 'a') = true
    var d = 1
    for (i <- 0 to l-1) {
      val ch = s(l - i - 1)
      cnt(ch - 'a') += d
      d *= 10
    }
  }

  var cur = 1
  var usedZero = false
  var ans = 0

  for (i <- 0 to 9) {

    var mx = 0
    for (j <- 0 to 9)
      if (cnt(j) > cnt(mx)) mx = j
    if (!usedZero && !notZero(mx)) {
      usedZero = true
    }
    else {
      ans += cnt(mx) * cur
      cur += 1
    }

    cnt(mx) = 0
  }

  println(ans)

}


Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which may consist of even a million digits!Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should be positive integers that have no leading zeros. Polycarpus knows values a and b.Help Polycarpus and find any suitable method to cut the public key.

The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is in range from 1 to 106 digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 108).

In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two parts must be positive integers having no leading zeros. If there are several answers, print any of them. If there is no answer, print in a single line "NO" (without the quotes).

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next().map(_.asDigit)
  val Array(a, b) = in.next().split(' ').map(_.toInt)
  val first = Array.ofDim[Boolean](line.length)
  line.indices.foldLeft(0) {
    case (current, index) =>
      val nCurrent = (current * 10 + line(index)) % a
      if (nCurrent == 0)
        first(index) = true
      nCurrent
  }
  val resIndex = line.indices.tail.reverse.foldLeft(-1, 0, 1) {
    case ((-1, current, l), index) =>
      val nL = (l * 10) % b
      val nCurrent = (line(index) * l + current) % b
      if (nCurrent == 0 && line(index) != 0 && first(index - 1))
        (index - 1, nCurrent, nL)
      else
        (-1, nCurrent, nL)
    case (acc, index) => acc
  }._1

  resIndex match {
    case -1 => println("NO")
    case index =>
      println("YES")
      println(line.take(index + 1).mkString)
      println(line.drop(index + 1).mkString)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val line = in.next().map(_.asDigit)
  val Array(a, b) = in.next().split(' ').map(_.toInt)
  val firstindices = line.indices.foldLeft(List.empty[Int], 0) {
    case ((result, current), index) =>
      val nCurrent = (current * 10 + line(index)) % a
      if (nCurrent == 0)
        (index :: result, nCurrent)
      else
        (result, nCurrent)
  }._1.toSet
  val lastindices = line.indices.reverse.foldLeft(List.empty[Int], 0, 1) {
    case ((result, current, l), index) =>
      val nL = (l * 10) % b
      val nCurrent = (line(index) * l + current) % b
      if (nCurrent == 0 && line(index) != 0)
        (index :: result, nCurrent, nL)
      else
        (result, nCurrent, nL)
  }._1.toSet

  firstindices.intersect(lastindices).headOption match {
    case None => println("NO")
    case Some(index) =>
      println("YES")
      println(line.take(index + 1).mkString)
      println(line.drop(index + 1).mkString)
  }
}


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

welcome to the
Codeforces
Beta
Round 5

and
good luck

object Main {
  def repeat(n: Int)(char: Char): String = (0 until n).map(_=>char).mkString
  def main(args: Array[String]) = {
    val strings = io.Source.stdin.getLines.toVector
    val lengths = strings map (s => s.length)
    val maxLens = lengths.max
    lazy val leftOrRight = lengths.map(l => (maxLens - l) % 2 != 0)
      .foldLeft((true, Vector.empty[Boolean])){case (accu, bool) => if(!bool) (accu._1, accu._2 :+ bool)
                                                                    else (accu._1 ^ bool, accu._2 :+ (accu._1 ^ bool))}._2

    lazy val outputs = for ( i <- 0 until strings.length ) yield {
      val left = if(leftOrRight(i)) (maxLens - lengths(i)) / 2 + 1
                 else (maxLens - lengths(i)) / 2
      val right = maxLens - lengths(i) - left
      "*" + repeat(left)(' ') + strings(i) + repeat(right)(' ') + "*"
    }
    println(repeat(maxLens+2)('*'))
    for (str <- outputs) println(str)
    println(repeat(maxLens+2)('*'))
  }
}

import java.util.Scanner

object BCentering extends App {

  val scanner = new Scanner(System.in)

  val input = scala.collection.mutable.ArrayBuffer.empty[String]

  //(0 until 12) foreach {
    //i =>
    while (scanner.hasNextLine) {
      input += scanner.nextLine()
  }

  val max = input.maxBy(_.length).length

  def solve(marginLeft: Boolean, rest: List[String]): List[String] = {
    rest match {
      case Nil => Nil
      case x :: xs =>
        if (same(x)) normalize(x) :: solve(marginLeft, xs)
        else if (marginLeft) normalize(" " + x) :: solve(!marginLeft, xs)
        else normalize(x + " ") :: solve(!marginLeft, xs)
    }
  }

  println("*" * (max + 2))
  println(solve(false, input.toList).mkString("\n"))
  println("*" * (max + 2))

  def same(s: String): Boolean = max % 2 == s.length % 2

  def normalize(s: String): String = {
    val diff = (max - s.length) / 2
    "*" + " " * diff + s + " " * diff + "*"
  }

}

object B5 {

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

  def main(args: Array[String]): Unit = {
    var arr = cu.ArrayBuffer.empty[String]
    var in = read
    while(in != null) {
      arr.append(in)
      in = read
    }
    val len = arr.map(_.length).max
    val res = Array.fill(arr.length+2)(Array.fill(len+2)(' '))
    for(j <- 0 until len+2) {
      res(0)(j) = '*'
      res.last(j) = '*'
    }
    for(i <- res.indices) {
      res(i)(0) = '*'
      res(i)(len+1) = '*'
    }
    var d = 0
    for(i <- arr.indices) {
      val frontPadding = 1 + (len-arr(i).length+d)/2
      for(j <- frontPadding until frontPadding+arr(i).length)
        res(i+1)(j) = arr(i)(j-frontPadding)
      if(arr(i).length%2 != len%2)
        d = 1-d
    }
    println(res.map(_.mkString("")).mkString("\n"))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
//    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF5B extends App {
  import scala.collection.mutable.ArrayBuffer
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val lines = ArrayBuffer[String]()
    var maxLength = 0
    while (in.hasNextLine) {
      val s = nextLine
      lines += s
      maxLength = if (s.length > maxLength) s.length else maxLength
    }

    val startAndEnd = (1 to (maxLength + 2)).map(x => "*").mkString("")
    out.println(startAndEnd)

    var isLeft = true
    lines.foreach { line =>
      if (line.length > 0) {
        var leftLen = (maxLength - line.length) / 2
        var rightLen = maxLength - line.length - leftLen

        if (leftLen != rightLen) {
          if (!isLeft) {
            val temp = leftLen
            leftLen = rightLen
            rightLen = temp
          }

          isLeft = !isLeft
        }
        val left = (1 to leftLen).map(x => " ").mkString("")
        val right = (1 to rightLen).map(x => " ").mkString("")
        out.println(s"*${left}${line}${right}*")
      } else {
        out.println(s"*${(1 to maxLength).map(x => " ").mkString("")}*")
      }
    }

    out.println(startAndEnd)
  }

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

object main extends App with fastIO {

  var num = 0

  def writestr(str: String, n: Int) {
    var need = n - str.length
    var add =
    if ((need & 1) == 1 && num == 1)
      need - (need >> 1); else
      need >> 1

    num ^= need & 1

    print("*")
    for (i <- 1 to add) print(" ")
    print(str)
    for (i <- 1 to need - add) print(" ")
    println("*");
  }

  var lines = Stream.continually(readLine).takeWhile(_ != null)
  val maxLen = lines.reduceLeft((x, y) => if (x.length > y.length) x else y).length

  var str = ""
  for (i <- 1 to maxLen + 2)
    str += "*"

  println(str)
  for (line <- lines) writestr(line, maxLen)
  println(str)

  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object main extends App with fastIO {

  var num = 0

  def writestr(str: String, n: Int) {
    var need = n - str.length
    var add =
    if ((need & 1) == 1 && num == 1)
      need - (need >> 1); else
      need >> 1

    num ^= need & 1

    println("*" + " " * add + str + " " * (need - add) + "*")
  }

  var lines = Stream.continually(readLine).takeWhile(_ != null)
  val maxLen = lines.map(_.length).max

  val str = "*" * (maxLen + 2)

  println(str)
  for (line <- lines) writestr(line, maxLen)
  println(str)

  flush
}

trait fastIO {
  import java.io._

  val isFile = false
  val input = "io.in"
  val output = "io.out"

  val bf = new BufferedReader(if(isFile) new FileReader(input) else new InputStreamReader(System.in))
  val in = new StreamTokenizer(bf)
  val out = new PrintWriter(if(isFile)new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

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

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()
  def println(o:Any) = out.println(o)
  def print(o:Any) = out.print(o)
  def printf(s:String,o:Any*) = out.printf(s,o)
  def flush() = out.flush()
}

object P5B {
    def main(args: Array[String]) {
        val b = io.Source.stdin.getLines.toBuffer
        val w = b.map{_.size}.max
        println("*" * (w + 2))
        var alt = 0
        for (i <- b) {
            val s = w - i.size
            val s0 = s >> 1
            val s1 = s - s0
            def print(sLeft : Int, sRight : Int) {
                println("*" + " " * sLeft + i + " " * sRight + "*")
            }
            alt match {
                case _ if s0 == s1 => print(s0, s0)
                case 0 => {alt = 1; print(s0, s1)}
                case 1 => {alt = 0; print(s1, s0)}
            }
        }
        println("*" * (w + 2))
    }
}

object Main {
  def repeat(n: Int)(char: Char): String = (0 until n).map(_=>char).mkString
  def main(args: Array[String]) = {
    val strings = io.Source.stdin.getLines.toVector
    val lengths = strings map (s => s.length)
    val maxLens = lengths.max
    val leftOrRight = lengths.map(l => (maxLens - l) % 2 != 0)
      .foldLeft((true, Vector.empty[Boolean])){case (accu, bool) => if(!bool) (accu._1, accu._2 :+ bool)
                                                                    else (accu._1 ^ bool, accu._2 :+ (accu._1 ^ bool))}._2

    val outputs = for ( i <- 0 until strings.length ) yield {
      val left = if(leftOrRight(i)) (maxLens - lengths(i)) / 2 + 1
                 else (maxLens - lengths(i)) / 2
      val right = maxLens - lengths(i) - left
      "*" + repeat(left)(' ') + strings(i) + repeat(right)(' ') + "*"
    }
    for (b <- leftOrRight) println(b)
    println(repeat(maxLens+2)('*'))
    for (str <- outputs) println(str)
    println(repeat(maxLens+2)('*'))
  }
}

import java.util.Scanner

object BCentering extends App {

  val scanner = new Scanner(System.in)

  val input = scala.collection.mutable.ArrayBuffer.empty[String]

  while (scanner.hasNext) {
    input += scanner.nextLine()
  }

  val max = input.maxBy(_.length).length

  def solve(marginLeft: Boolean, rest: List[String]): List[String] = {
    rest match {
      case Nil => Nil
      case x :: xs =>
        if (same(x)) normalize(x) :: solve(marginLeft, xs)
        else if (marginLeft) normalize(" " + x) :: solve(!marginLeft, xs)
        else normalize(x + " ") :: solve(!marginLeft, xs)
    }
  }

  println("*" * (max + 2))
  println(solve(false, input.toList).mkString("\n"))
  println("*" * (max + 2))

  def same(s: String): Boolean = max % 2 == s.length % 2

  def normalize(s: String): String = {
    val diff = (max - s.length) / 2
    "*" + " " * diff + s + " " * diff + "*"
  }

}

object B5 {

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

  def main(args: Array[String]): Unit = {
    var arr = cu.ArrayBuffer.empty[String]
    var in = read
    while(in != null) {
      arr.append(in)
      in = read
    }
    val len = arr.map(_.length).max
    val res = Array.fill(arr.length+2)(Array.fill(len+2)(' '))
    for(j <- 0 until len+2) {
      res(0)(j) = '*'
      res.last(j) = '*'
    }
    for(i <- res.indices) {
      res(i)(0) = '*'
      res(i)(len+1) = '*'
    }
    var d = 0
    for(i <- arr.indices) {
      val frontPadding = 1 + (len-arr(i).length+d)/2
      for(j <- frontPadding until frontPadding+arr(i).length)
        res(i+1)(j) = arr(i)(j-frontPadding)
      d = 1-d
    }
    println(res.map(_.mkString("")).mkString("\n"))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF5B extends App {
  import scala.collection.mutable.ArrayBuffer
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val lines = ArrayBuffer[String]()
    var maxLength = 0
    while (in.hasNext) {
      val s = nextLine
      lines += s
      maxLength = if (s.length > maxLength) s.length else maxLength
    }

    val startAndEnd = (1 to (maxLength + 2)).map(x => "*").mkString("")
    out.println(startAndEnd)
    lines.foreach { line =>
      if (line.length > 0) {
        val leftLen = (maxLength - line.length) / 2
        val rightLen = maxLength - line.length - leftLen
        val left = (1 to leftLen).map(x => " ").mkString("")
        val right = (1 to rightLen).map(x => " ").mkString("")
        out.println(s"*${left}${line}${right}*")
      } else {
        out.println(s"*${(1 to maxLength).map(x => " ").mkString("")}*")
      }
    }

    out.println(startAndEnd)
  }

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

}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF5B extends App {
  import scala.collection.mutable.ArrayBuffer
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val lines = ArrayBuffer[String]()
    var maxLength = 0
    while (in.hasNext) {
      val s = nextLine
      lines += s
      maxLength = if (s.length > maxLength) s.length else maxLength
    }

    val startAndEnd = (1 to (maxLength + 2)).map(x => "*").mkString("")
    out.println(startAndEnd)
    lines.foreach { line =>
      val supp = if (line.length > 0) {
        (1 to (maxLength - line.length) / 2).map(x => " ")
      } else {
        (1 to maxLength).map(x => " ")
      }
      out.println(s"*${supp}${line}${supp}*")
    }

    out.println(startAndEnd)
  }

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

}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF5B extends App {
  import scala.collection.mutable.ArrayBuffer
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val lines = ArrayBuffer[String]()
    var maxLength = 0
    while (in.hasNext) {
      val s = nextLine
      lines += s
      maxLength = if (s.length > maxLength) s.length else maxLength
    }

    val startAndEnd = (1 to (maxLength + 2)).map(x => "*").mkString("")
    out.println(startAndEnd)
    lines.foreach { line =>
      val supp = if (line.length > 0) {
        (1 to (maxLength - line.length) / 2).map(x => " ").mkString("")
      } else {
        (1 to maxLength).map(x => " ").mkString("")
      }
      out.println(s"*${supp}${line}${supp}*")
    }

    out.println(startAndEnd)
  }

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

}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF5B extends App {
  import scala.collection.mutable.ArrayBuffer
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val lines = ArrayBuffer[String]()
    var maxLength = 0
    while (in.hasNext) {
      val s = nextLine
      lines += s
      maxLength = if (s.length > maxLength) s.length else maxLength
    }

    val startAndEnd = (1 to (maxLength + 2)).map(x => "*").mkString("")
    out.println(startAndEnd)
    lines.foreach { line =>
      if (line.length > 0) {
        val leftLen = (maxLength - line.length) / 2
        val rightLen = maxLength - leftLen
        val left = (1 to leftLen).map(x => " ").mkString("")
        val right = (1 to rightLen).map(x => " ").mkString("")
        out.println(s"*${left}${line}${right}*")
      } else {
        out.println(s"*${(1 to maxLength).map(x => " ").mkString("")}*")
      }
    }

    out.println(startAndEnd)
  }

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

}

/**
 * Created by yangchaozhong on 3/10/15.
 */
object CF5B extends App {
  import scala.collection.mutable.ArrayBuffer
  import java.util.{Scanner}
  import java.io.{PrintWriter}

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

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

  def solve = {
    val lines = ArrayBuffer[String]()
    var maxLength = 0
    while (in.hasNext) {
      val s = nextLine
      lines += s
      maxLength = if (s.length > maxLength) s.length else maxLength
    }

    val startAndEnd = (1 to (maxLength + 2)).map(x => "*").mkString("")
    out.println(startAndEnd)

    var isLeft = true
    lines.foreach { line =>
      if (line.length > 0) {
        var leftLen = (maxLength - line.length) / 2
        var rightLen = maxLength - line.length - leftLen

        if (leftLen != rightLen) {
          if (!isLeft) {
            val temp = leftLen
            leftLen = rightLen
            rightLen = temp
          }

          isLeft = !isLeft
        }
        val left = (1 to leftLen).map(x => " ").mkString("")
        val right = (1 to rightLen).map(x => " ").mkString("")
        out.println(s"*${left}${line}${right}*")
      } else {
        out.println(s"*${(1 to maxLength).map(x => " ").mkString("")}*")
      }
    }

    out.println(startAndEnd)
  }

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


Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.

The first line contains two space-separated integers n, s (1 ≤ n, s ≤ 100). The i-th of the next n lines contains two integers xi, yi (1 ≤ xi ≤ 100; 0 ≤ yi < 100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.

Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.

NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.

object Codeforces extends App {
  val in = new java.util.Scanner(System.in)
  var n = in.nextInt()
  var s = in.nextInt() * 100
  var res = -1
  for (i <- 1 to n) {
    var cur = in.nextInt() * 100 + in.nextInt()
    if (s >= cur)
      res = math.max(res, (s - cur) % 100)
  }
  println(res)
}

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

/**
 * Created by arseny on 30.08.14.
 */
object A extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

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

  def solve() = {
    val n = nextInt
    val s = nextInt
    var max = -1
    for(i <- 0 until n) {
      val x = nextInt
      val y = nextInt
      if(y == 0) {
        if(s >= x) {
          max = math.max(max, 0)
        }
      } else {
        if(s >= x + 1) {
          max = math.max(max, 100 - y)
        }
      }
    }
    out.print(max)
  }

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

import java.util.StringTokenizer

object _463A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val s = next.toInt
  val ans = for {
    i <- 1 to n
    val a = next.toInt
    val b = next.toInt
    if (a < s || (a == s && b == 0))
  } yield (100 - b) % 100
  if (ans.length == 0) println(-1)
  else println(ans.max)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, s) = in.next().split(" ").map(_.toInt)
  val r = Range(0, n).map{_ =>
    val d = in.next().split(" ").map(_.toInt)
    s * 100 - (d(0) * 100 + d(1))
  }.filter(_ >= 0).map(_ % 100)
  if (r.isEmpty)
    println(-1)
  else
    println(r.max)
}

object A463 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, s) = readInts(2)
    s *= 100
    val in = Array.fill(n)(readInts(2)).map{
      arr => s"${arr(0)}${if(arr(1)<10)"0" else ""}${arr(1)}".toInt
    }
    var res = 0
    for(i <- 0 until n) {
      if(s >= in(i)) {
        res = math.max(res, (s - in(i))%100)
      }
    }
    if(in.forall(_ > s)) {
      println("-1")
    } else {
      println(res)
    }
  }

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

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

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

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

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

}

object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val s = cin.nextInt()
    def solve(n: Int, mx: Int): Int =
      if (n == 0) mx
      else {
        val x = cin.nextInt()
        val y = cin.nextInt()
        if (x < s && y > 0) solve(n - 1, Math.max(mx, 100 - y))
        else if (x <= s && y == 0) solve(n - 1, Math.max(mx, 0))
        else solve(n - 1, mx)
      }
    println(solve(n, -1))
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-28.
 */
object A463 extends App {
  val sc = new Scanner(System.in)
  val n, s = sc.nextInt()
  val allMoney = new Money(s, 0)
  var i = 0
  var maxSweets = -1

  while (i < n) {
    val m = new Money(sc.nextInt(), sc.nextInt())
    var j = 1

    while (m * j <= allMoney) {
      val spend = m * j
      val restMoney = allMoney - spend
      maxSweets = Math.max(restMoney.cent, maxSweets)
      j += 1
    }

    i += 1
  }

  print(maxSweets)
}

class Money(val dollar: Int, val cent: Int) {
  def * (that: Int): Money = {
    var up = 0
    var newCent = 0
    var newDollar = 0

    if (cent * that < 100) {
      newCent = cent
    } else {
      up = cent / 100
      newCent = cent % 100
    }

    newDollar = dollar * that + up
    new Money(newDollar, newCent)
  }

  def <= (that: Money): Boolean = {
    if (this.dollar < that.dollar) {
      true
    } else if (this.dollar == that.dollar){
      if (this.cent <= that.cent) {
        true
      } else {
        false
      }
    } else {
      false
    }
  }

  def - (that: Money): Money = {
    var newCent = 0
    var down = 0

    if (this.cent >= that.cent) {
      newCent = this.cent - that.cent
    } else {
      down = 1
      newCent = this.cent + 100 - that.cent
    }

    new Money(this.dollar - down - that.dollar, newCent)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, s) = in.next().split(" ").map(_.toInt)
  val r = Range(0, n).map{_ =>
    val d = in.next().split(" ").map(_.toInt)
    d(0) * 100 + d(1)
  }.filter(_ < s).map(_ % 100)
  if (r.isEmpty)
    println(-1)
  else
    println(r.max)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, s) = in.next().split(" ").map(_.toInt)
  val r = Range(0, n).map{_ =>
    val d = in.next().split(" ").map(_.toInt)
    d(0) * 100 + d(1)
  }.filter(_ < s).map(99 - _ % 100)
  if (r.isEmpty)
    println(-1)
  else
    println(r.max)
}

object A463 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, s) = readInts(2)
    s *= 100
    val in = Array.fill(n)(readInts(2)).map{
      arr => (s"${arr(0)}.${arr(1)}".toDouble * 100).toInt
    }
    var res = 0
    for(i <- 0 until n) {
      if(s >= in(i) && in(i)%100 != 0) {
        res = math.max(res, 100 - (in(i)%100))
      }
    }
    if(in.forall(_ > s)) {
      println("-1")
    } else {
      println(res)
    }
  }

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

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

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

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

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

}

object A463 {

  import IO._

  def main(args: Array[String]): Unit = {
    var Array(n, s) = readInts(2)
    s *= 100
    val in = Array.fill(n)(readInts(2)).map{
      arr => (s"${arr(0)}.${if(arr(1)<10)"0" else ""}${arr(1)}".toDouble * 100).toInt
    }
    var res = 0
    for(i <- 0 until n) {
      if(s >= in(i)) {
        res = math.max(res, (s - in(i))%100)
      }
    }
    if(in.forall(_ > s)) {
      println("-1")
    } else {
      println(res)
    }
  }

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

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

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

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

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

}

object Main {
  def main(args: Array[String]) = {
    val cin = new java.util.Scanner(System.in)
    val n = cin.nextInt()
    val s = cin.nextInt()
    def solve(n: Int, mx: Int): Int =
      if (n == 0) mx
      else {
        val x = cin.nextInt()
        val y = cin.nextInt()
        if (x < s && y > 0) solve(n - 1, Math.max(mx, 100 - y))
        else if (x == s && y == 0) solve(n - 1, Math.max(mx, 0))
        else solve(n - 1, mx)
      }
    println(solve(n, -1))
  }
}

import java.util.Scanner

/**
 * Created by Kuang.Ru on 14-9-28.
 */
object A463 extends App {
  val sc = new Scanner(System.in)
  val n, s = sc.nextInt()
  var i = 0
  var maxSweets: Double = -1

  while (i < n) {
    val x, y = sc.nextInt()
    val d = x + y / 100.0
    var j = 1

    while (d * j <= s) {
      maxSweets = Math.max(((s - d * j) % 1) * 100, maxSweets)
      j += 1
    }

    i += 1
  }

  print(maxSweets.toInt)
}