Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer). There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.

The first line of the input contains two integers n and t (1 ≤ n ≤ 200 000, 1 ≤ t ≤ 109) — the length of Efim's grade and the number of seconds till the end of the break respectively. The second line contains the grade itself. It's guaranteed that the grade is a positive number, containing at least one digit after the decimal points, and it's representation doesn't finish with 0.

Print the maximum grade that Efim can get in t seconds. Do not print trailing zeroes.

NoteIn the first two samples Efim initially has grade 10.245. During the first second Efim can obtain grade 10.25, and then 10.3 during the next second. Note, that the answer 10.30 will be considered incorrect.In the third sample the optimal strategy is to not perform any rounding at all.

import java.math.BigInteger

import scala.io.StdIn._
import scala.util.Random

object _373C extends App {
  val Array(n, t) = readLine().split(" ") map (_.toInt)
  val Array(left, right) = readLine().split("\\.")

  val A = (left map (_.asDigit)).toArray
  val B = (right map (_.asDigit)).toArray

  def printNumber(left: Array[Int], right: Array[Int], rightSize: Int) = {
    println(left.mkString + "." + right.mkString.take(rightSize + 1))
  }

  def printNumber(left: Array[Int]) = {
    println(left.mkString)
  }

  var first4InSeq = -1
  var last4InSeq = -1

  def solve(): (Int, Int, Int) = {
    for (i <- B.indices) {
      if (B(i) == 4) {
        if (first4InSeq == -1) {
          first4InSeq = i
          last4InSeq = i
        } else {
          last4InSeq = i
        }
      } else if (first4InSeq > -1) {
        if (B(i) > 4) {
          return (first4InSeq, last4InSeq, last4InSeq + 1)
        } else {
          first4InSeq = -1
          last4InSeq = -1
        }
      } else if (B(i) > 4) {
        return (-1, -1, i)
      }
    }

    (-1, -1, -1)
  }

  def printNumberPlusOne() = {
    val digits = A.reverse
    var i = 0
    if (digits(i) < 9) {
      digits(i) += 1
      println(digits.reverse.mkString)
    } else {
      while (i < left.length && digits(i) == 9) {
        digits(i) = 0
        i += 1
      }
      if (i < left.length) {
        digits(i) += 1
        println(digits.reverse.mkString)
      } else {
        println("1" + digits.reverse.mkString)
      }
    }
  }
  def printNumberSubsPlusOne(last: Int) = {
    B(last) += 1
    printNumber(A, B, last)
  }

  def cut(a: Int, b: Int, c: Int) = {
    if (a > -1) {
      if (t >= c - a + 1) {
        if (a == 0) {
          printNumberPlusOne()
        } else {
          printNumberSubsPlusOne(a - 1)
        }
      } else {
        printNumberSubsPlusOne(c - t)
      }
    } else {
      if (c == 0) {
        printNumberPlusOne()
      } else {
        printNumberSubsPlusOne(c - 1)
      }
    }
  }

  val (a, b, c) = solve()
  if (c == -1) {
    val max = B.zipWithIndex.maxBy(_._1)
    if (max._1 > 4) {
      if (max._2 == 0) {
        printNumberPlusOne()
      } else {
        val subs = right.substring(0, max._2)
        printNumberSubsPlusOne(max._2 - 1)
      }
    } else {
      printNumber(A, B, B.length - 1)
    }
  } else {
    cut(a, b, c)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, t) = in.next().split(' ').map(_.toInt)
  val line = in.next()
  if (!line.contains('.'))
    println(line)
  else {
    val Array(first, second) = line.split('.')
    second.indices.find(i => second(i) >= '5') match {
      case None => println(line)
      case Some(i) =>
//        println((i - 1 to Math.max(0, i - t + 1) by -1).map(i => second(i)))
//        println((i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').map(i => second(i)))
        val l = (i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').length
        if (l - i  == 0) {
          val nines = first.reverse.takeWhile(_ == '9').length
          if (nines == first.length) {
//            println("HERE")
            println("1" + "0" * nines)
          }
          else
            println(first.take(first.length - nines - 1) + (first(first.length - nines - 1) + 1).toChar + "0" * nines)
        }
        else {
//          println(l)
          val n = second.take(i - l - 1) + (second(i - l - 1) + 1).toChar
          println(s"$first.$n")
        }
    }
  }
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {

  def foo(s: List[Char], cnt: Int): (List[Char], Int, Boolean) = {
    if (s.isEmpty)
      (List(), 0, false)
    else {
      if (s.head < '4') {
        val (t, c, f) = foo(s.tail, cnt)
        (((if (f) (s.head.toByte + 1) else s.head.toByte).toChar) :: t, c, false)
      }
      else {
        if (s.head > '4')
          (List(), 1, true)
        else {
          val (t, c, f) = foo(s.tail, cnt)
          if (f && c < cnt)
            (t, c + 1, true)
          else
            ((if (f) '5' else '4') :: t, c, false)
        }
      }
    }
  }

  val sc = new Scanner(System.in)

  val _ = sc.nextInt()
  val t = sc.nextInt()
  val s = sc.next()
  val (res, _, f) = foo(s.toList.dropWhile({case '.' => false; case _ => true}).tail, t)
  if(f) {
    var flg = f
    val r = s.takeWhile({case '.' => false; case _ => true}).toArray
    for(i <- Range(r.length - 1, -1, -1))
      if (flg) {
        if (r(i) == '9')
          r(i) = '0'
        else {
          r(i) = (r(i).toByte + 1).toChar
          flg = false
        }
      }
    if (flg)
      print(1)
    println(new String(r))
  }
  else
    println(s.takeWhile({case '.' => false; case _ => true}) ++ "." ++ res)
}

import java.math.BigInteger

import scala.io.StdIn._

object _373C extends App {
  val Array(n, t) = readLine().split(" ") map (_.toInt)
  val Array(left, right) = readLine().split("\\.")
  val B = (right map (_.asDigit)).toList

  def printNumber(left: BigInteger, right: String) = {
    if (right == "0") println(left) else println(left + "." + right)
  }

  def printNumber(left: String, right: String) = {
    if (right == "0") println(left) else println(left + "." + right)
  }

  var first4InSeq = -1
  var last4InSeq = -1

  def solve(): (Int, Int, Int) = {
    for (i <- B.indices) {
      if (B(i) == 4) {
        if (first4InSeq == -1) {
          first4InSeq = i
          last4InSeq = i
        } else {
          last4InSeq = i
        }
      } else if (first4InSeq > -1) {
        if (B(i) > 4) {
          return (first4InSeq, last4InSeq, last4InSeq + 1)
        } else {
          first4InSeq = -1
          last4InSeq = -1
        }
      }
    }

    (-1, -1, -1)
  }

  def printNumberPlusOne() = printNumber(new BigInteger(left).add(BigInteger.ONE), "0")
  def printNumberSubsPlusOne(subs: String) = printNumber(left, subs.init + (subs.last.asDigit + 1))

  def cut(a: Int, b: Int, c: Int) = {
    if (t >= c - a + 1) {
      if (a == 0) {
        printNumberPlusOne()
      } else {
        val subs = right.substring(0, a)
        printNumberSubsPlusOne(subs)
      }
    } else {
      val subs = right.substring(0, c - t + 1)
      printNumberSubsPlusOne(subs)
    }
  }

  val (a, b, c) = solve()
  if (a == -1) {
    val max = B.zipWithIndex.maxBy(_._1)
    if (max._1 > 4) {
      if (max._2 == 0) {
        printNumberPlusOne()
      } else {
        val subs = right.substring(0, max._2)
        printNumberSubsPlusOne(subs)
      }
    } else {
      printNumber(left, right)
    }
  } else {
    cut(a, b, c)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, t) = in.next().split(' ').map(_.toInt)
  val line = in.next()
  if (!line.contains('.'))
    println(line)
  else {
    val Array(first, second) = line.split('.')
    second.indices.find(i => second(i) >= '5') match {
      case None => println(line)
      case Some(i) =>
//        println((i - 1 to Math.max(0, i - t + 1) by -1).map(i => second(i)))
//        println((i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').map(i => second(i)))
        val l = (i - 1 to Math.max(0, i - t + 1) by -1).takeWhile(i => second(i) == '4').length
        if (l - i  == 0) {
          val nines = first.reverse.takeWhile(_ == '9').length
          println(nines)
          if (nines == first.length) {
//            println("HERE")
            println("1" + "0" * nines)
          }
          else
            println(first.take(first.length - nines - 1) + (first(first.length - nines) + 1).toChar + "0" * nines)
        }
        else {
//          println(l)
          val n = second.take(second.length - l - 2) + (second(second.length - l - 2) + 1).toChar
          println(s"$first.$n")
        }
    }
  }
}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {

  def foo(s: List[Char], cnt: Int): (List[Char], Int, Boolean) = {
    if (s.isEmpty)
      (List(), 0, false)
    else {
      if (s.head < '4') {
        val (t, c, f) = foo(s.tail, cnt)
        (((if (f) (s.head.toByte + 1) else s.head.toByte).toChar) :: t, c, false)
      }
      else {
        if (s.head > '4')
          (List(), 1, true)
        else {
          val (t, c, f) = foo(s.tail, cnt)
          if (f && c < cnt)
            (t, c + 1, true)
          else
            ((if (f) '5' else '4') :: t, c, false)
        }
      }
    }
  }

  val sc = new Scanner(System.in)

  val _ = sc.nextInt()
  val t = sc.nextInt()
  val s = sc.next()
  val (res, _, f) = foo(s.toList.dropWhile({case '.' => false; case _ => true}).tail, t)
  if(f)
    println(Integer.decode(s.takeWhile({case '.' => false; case _ => true})) + 1)
  else
    println(s.takeWhile({case '.' => false; case _ => true}) ++ "." ++ res.reverse)

}

import java.util.Scanner
import scala.collection.immutable._
import scala.collection.mutable

/**
  * Created by Andrew on 11-Jul-16.
  */

object Main extends App {

  def foo(s: List[Char], cnt: Int): (List[Char], Int, Boolean) = {
    if (s.isEmpty)
      (List(), 0, false)
    else {
      if (s.head < '4') {
        val (t, c, f) = foo(s.tail, cnt)
        (((if (f) (s.head.toByte + 1) else s.head.toByte).toChar) :: t, c, false)
      }
      else {
        if (s.head > '4')
          (List(), 1, true)
        else {
          val (t, c, f) = foo(s.tail, cnt)
          if (f && c < cnt)
            (t, c + 1, true)
          else
            ((if (f) '5' else '4') :: t, c, false)
        }
      }
    }
  }

  val sc = new Scanner(System.in)

  val _ = sc.nextInt()
  val t = sc.nextInt()
  val s = sc.next()
  val (res, _, f) = foo(s.toList.dropWhile({case '.' => false; case _ => true}).tail, t)
  if(f) {
    var flg = f
    val r = s.takeWhile({case '.' => false; case _ => true}).toArray
    for(i <- Range(r.length - 1, -1, -1))
      if (flg) {
        if (r(i) == '9')
          r(i) = '0'
        else {
          r(i) = (r(i).toByte + 1).toChar
          flg = false
        }
      }
    println(new String(r))
  }
  else
    println(s.takeWhile({case '.' => false; case _ => true}) ++ "." ++ res)
}


One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one.The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (1 ≤ i ≤ n), someone can use the first portal to move from it to room number (i + 1), also someone can use the second portal to move from it to room number pi, where 1 ≤ pi ≤ i.In order not to get lost, Vasya decided to act as follows.   Each time Vasya enters some room, he paints a cross on its ceiling. Initially, Vasya paints a cross at the ceiling of room 1.  Let's assume that Vasya is in room i and has already painted a cross on its ceiling. Then, if the ceiling now contains an odd number of crosses, Vasya uses the second portal (it leads to room pi), otherwise Vasya uses the first portal. Help Vasya determine the number of times he needs to use portals to get to room (n + 1) in the end.

The first line contains integer n (1 ≤ n ≤ 103) — the number of rooms. The second line contains n integers pi (1 ≤ pi ≤ i). Each pi denotes the number of the room, that someone can reach, if he will use the second portal in the i-th room.

Print a single number — the number of portal moves the boy needs to go out of the maze. As the number can be rather large, print it modulo 1000000007 (109 + 7).

import java.util.StringTokenizer;
import Array._;

object LongPath {
  var st:StringTokenizer = new StringTokenizer("");
  def newst={st=new StringTokenizer(readLine);}
  def nextint:Int = {st.nextToken.toInt;}
  val MD=1000000007;
  def main(args:Array[String])={
    newst;
    val m=nextint;
    newst;
    //for (i<-1 to m) {println(m);}
    var p:Array[Int]=fill(m+1)(0);
    var n:Array[Long]=fill(m+1)(0);
    var x:Long=0;
    var ans:Long=2;
    for (i<-1 to m) {
      p(i)=nextint;
    }
    n(m)=2;
    for (i<-m-1 to 1 by (-1)) {
      x=(2*n(i+1))%MD;
      for (j<-i+1 to m) {
	if (p(j)==i+1) {x=(x-n(j)+MD)%MD;}
      }
      n(i)=x;
      ans=(ans+x)%MD;
    }
    println(ans);
  }
}

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

object B extends App {

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

  val n = readInt
  val ps = readInts(n)
  val MOD = 1000000007L

  val dp = Array.ofDim[Long](n + 1, 2)

  dp(0)(0) = 0
  dp(0)(1) = 1

  for (i <- 1 to n) {
    dp(i)(0) = (dp(i - 1)(1) + 1) % MOD
    if (i < n) dp(i)(1) = if (ps(i) - 1 < i) {
      var sum = (dp(i)(0) + 1) % MOD
      for (i <- ps(i) - 1 until i)
       sum = (MOD + sum + (dp(i)(1) - dp(i)(0)) + 1) % MOD
      sum
    } else (dp(i)(0) + 1) % MOD
  }
  //println(dp.map(a => a(0)).mkString(" "))
  //println(dp.map(a => a(1)).mkString(" "))
  println(dp(n)(0))
}


There was an electronic store heist last night.All keyboards which were in the store yesterday were numbered in ascending order from some integer number $$$x$$$. For example, if $$$x = 4$$$ and there were $$$3$$$ keyboards in the store, then the devices had indices $$$4$$$, $$$5$$$ and $$$6$$$, and if $$$x = 10$$$ and there were $$$7$$$ of them then the keyboards had indices $$$10$$$, $$$11$$$, $$$12$$$, $$$13$$$, $$$14$$$, $$$15$$$ and $$$16$$$.After the heist, only $$$n$$$ keyboards remain, and they have indices $$$a_1, a_2, \dots, a_n$$$. Calculate the minimum possible number of keyboards that have been stolen. The staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

The first line contains single integer $$$n$$$ $$$(1 \le n \le 1\,000)$$$ — the number of  keyboards in the store that remained after the heist. The second line contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^{9})$$$ — the indices of the remaining keyboards. The integers $$$a_i$$$ are given in arbitrary order and are pairwise distinct.

Print the minimum possible number of keyboards that have been stolen if the staff remember neither $$$x$$$ nor the number of keyboards in the store before the heist.

NoteIn the first example, if $$$x=8$$$ then minimum number of stolen keyboards is equal to $$$2$$$. The keyboards with indices $$$9$$$ and $$$11$$$ were stolen during the heist.In the second example, if $$$x=4$$$ then nothing was stolen during the heist.

object CodeForces extends App {
  val n = Console.in.readLine().toInt
  val xs = Console.in.readLine().split(" ", n).map(_.toLong).sorted

  var c: Long = 0

  for (i <- 0 until xs.length - 1) {
    c += xs(i + 1) - (xs(i) + 1)
  }

  println(c)
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    Sorting.quickSort(A)
    val ms = A(0)
    var ans = 0L
    rep(N - 1) { i =>
      ans += A(i + 1) - A(i) - 1
    }

    out.println(ans)
  }

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

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

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

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

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

object CodeForces extends App {
  val n = Console.in.readLine().toInt
  val xs = Console.in.readLine().split(" ", n).map(_.toInt).sorted

  var c = 0

  for (i <- 0 until xs.length - 2) {
    c += xs(i + 1) - (xs(i) + 1)
  }

  println(c)
}


Volodya likes listening to heavy metal and (occasionally) reading. No wonder Volodya is especially interested in texts concerning his favourite music style.Volodya calls a string powerful if it starts with "heavy" and ends with "metal". Finding all powerful substrings (by substring Volodya means a subsequence of consecutive characters in a string) in a given text makes our hero especially joyful. Recently he felt an enormous fit of energy while reading a certain text. So Volodya decided to count all powerful substrings in this text and brag about it all day long. Help him in this difficult task. Two substrings are considered different if they appear at the different positions in the text.For simplicity, let us assume that Volodya's text can be represented as a single string.

Input contains a single non-empty string consisting of the lowercase Latin alphabet letters. Length of this string will not be greater than 106 characters.

Print exactly one number — the number of powerful substrings of the given string. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample the string "heavymetalisheavymetal" contains powerful substring "heavymetal" twice, also the whole string "heavymetalisheavymetal" is certainly powerful.In the second sample the string "heavymetalismetal" contains two powerful substrings: "heavymetal" and "heavymetalismetal".

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Long = {
    val S = sc.nextLine
    val N = S.length

    @tailrec
    def loop(acc: Long, i: Int, j: Int, k: Int, n: Int): Long = {
      val i_ = if (0 <= i && i < n) S.indexOf("heavy", n)
               else i
      val j_ = if (0 <= j && j < n) S.indexOf("metal", n)
               else j

      n match {
        case N    => acc
        case `i_` => loop(acc, i_, j_, k + 1, n + 5)
        case `j_` => loop(acc + k, i_, j_, k, n + 5)
        case _    => loop(acc, i_, j_, k, n + 1)
      }
    }

    loop(0, S.indexOf("heavy"), S.indexOf("metal"), 0, 0)
  }

  out.println(solve)
  out.close
}

import scala.io.StdIn._
object main extends App{
  var metal = new Array[Int](1000005)
  val s = readLine()
  var count = 0
  for(i <- 0 until s.length - 4){
    if(s(i) == 'm'){
      if(s.slice(i,i+5) == "metal"){
        count += 1
      }
    }
    metal(i) = count
  }
  var ans : BigInt = 0
  for(i <- 0 until s.length - 4){
    if(s(i) == 'h'){
      if(s.slice(i,i+5) == "heavy"){
        ans += count - metal(i)
      }
    }
  }
  print(ans)
}

import scala.io.StdIn._
object main extends App{
  var metal = new Array[Int](1000005)
  val s = readLine()
  var count = 0
  for(i <- 0 until s.length - 4){
    if(s(i) == 'm'){
      if(s.slice(i,i+5) == "metal"){
        count += 1
      }
    }
    metal(i) = count
  }
  var ans : Long = 0
  for(i <- 0 until s.length - 4){
    if(s(i) == 'h'){
      if(s.slice(i,i+5) == "heavy"){
        ans += count - metal(i)
      }
    }
  }
  print(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.foldLeft((0l, 0l, "")) {
    case((count, starts, ""), 'h') => (count, starts, "h")
    case((count, starts, ""), 'm') => (count, starts, "m")
    case((count, starts, ""), el) => (count, starts, "")
    case((count, starts, "heav"), 'y') => (count, starts + 1, "")
    case((count, starts, "meta"), 'l') => (count + starts, starts, "")
    case((count, starts, str1), el) if str1.head == 'h' && "heavy"(str1.length) == el => (count, starts, str1 + el)
    case((count, starts, str1), el) if str1.head == 'm' && "metal"(str1.length) == el => (count, starts, str1 + el)
    case((count, starts, str1), 'h') => (count, starts, "h")
    case((count, starts, str1), 'm') => (count, starts, "m")
    case((count, starts, str1), el) => (count, starts, "")
  }
  println(res._1)
}
//fpgzbvhheavymheheavyzmheavyavyebknkhheavyhsbqmmetheavyalmetalheavyyomtua

object B extends App {

  def loc(s: String, sub: String) = {

	  var lastIndex = 0
	  val res = new scala.collection.mutable.ArrayBuffer[Int]()

	  while (lastIndex != -1) {

    		lastIndex = s.indexOf(sub, lastIndex);

    		if (lastIndex != -1) {
    			res += lastIndex
    			lastIndex += sub.length();
    		}
    	}

	  res
  }

  def solve(s: String): Long = {

    val hs = loc(s, "heavy")
    var ms = loc(s, "metal")

    var count = 0L
    var mLeft = ms.length
    var mi = 0

    for (h <- hs) {
      while (mi < ms.length && ms(mi) < h) {
        mLeft -= 1
        mi += 1
      }
      count += mLeft
    }

    count
  }

  def readString = Console.readLine

  val s = readString

  println(solve(s))
}

import scala.annotation.tailrec
object B {
    def getSlice(s: String, h: String, idx: Int = 0, res: List[Int] = Nil): List[Int] = {
        s.indexOf(h, idx) match {
            case -1 => res
            case x => getSlice(s, h, x + h.length, x :: res)
        }
    }

    @tailrec
    def solve(l: List[Int], r: List[Int], llen: Long, rlen: Long, res: Long = 0): Long = {
        l match {
            case x :: xs => {
                r match {
                    case y :: ys => {
                        if(x > y) solve(l, ys, llen, rlen-1, res)
                        else solve(xs, r, llen-1, rlen, res + rlen)
                    }
                    case Nil => res
                }
            }
            case Nil => res
        }
    }

    def main(args: Array[String]) {
        val ll = readLine
        val heavy = getSlice(ll, "heavy").sortWith(_ < _)
        val metal = getSlice(ll, "metal").sortWith(_ < _)
        println(solve(heavy, metal, heavy.length, metal.length))
    }
}

object Second{
  def readString() : String = {
    var yo = scala.io.StdIn.readLine()
    yo
  }
  def readInt() : Int = {
    var yo = scala.io.StdIn.readInt();
    yo
  }
  def loc(s: String, sub: String) = {

	  var lastIndex = 0
	  val res = new scala.collection.mutable.ArrayBuffer[Int]() // yeh ek hissab se vector ko declare krna h

	  while (lastIndex != -1) {

    		lastIndex = s.indexOf(sub, lastIndex);

    		if (lastIndex != -1) {
    			res += lastIndex
    			lastIndex += sub.length();
    		}
    	}

	  res
  }

  def solve(s : String) = {
    val hs = loc(s, "heavy")
    var ms = loc(s, "metal")
    var count = 0L
    var mLeft = ms.length
    var mi = 0

    for (h <- hs) {
      while (mi < ms.length && ms(mi) < h) {
        mLeft -= 1
        mi += 1
      }
      count += mLeft
    }

    count
  }
   def main(args : Array[String]){
    var s = readString()
    print(solve(s))
   }
}

import scala.io.StdIn._
object main extends App{
  var metal = new Array[Int](1000005)
  val s = readLine()
  var count = 0
  for(i <- 0 until s.length - 4){
    if(s(i) == 'm'){
      if(s.slice(i,i+5) == "metal"){
        count += 1
      }
    }
    metal(i) = count
  }
  var ans = 0
  for(i <- 0 until s.length - 4){
    if(s(i) == 'h'){
      if(s.slice(i,i+5) == "heavy"){
        ans += count - metal(i)
      }
    }
  }
  print(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val res = str.foldLeft((0l, 0l, "")) {
    case((count, starts, ""), 'h') => (count, starts, "h")
    case((count, starts, ""), 'm') => (count, starts, "m")
    case((count, starts, ""), el) => (count, starts, "")
    case((count, starts, "heav"), 'y') => (count, starts + 1, "")
    case((count, starts, "meta"), 'l') => (count + starts, starts, "")
    case((count, starts, str), el) if str.head == 'h' && "heavy"(str.length) == el => (count, starts, str + el)
    case((count, starts, str), el) if "metal"(str.length) == el => (count, starts, str + el)
    case((count, starts, str), el) => (count, starts, "")
  }
  println(res._1)
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

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

  def solve(): Long = {
    val S = sc.nextLine
    val N = S.length

    @tailrec
    def loop(acc: Int, i: Int, j: Int, k: Int, n: Int): Int = {
      val i_ = if (0 <= i && i < n) S.indexOf("heavy", n)
               else i
      val j_ = if (0 <= j && j < n) S.indexOf("metal", n)
               else j

      n match {
        case N    => acc
        case `i_` => loop(acc, i_, j_, k + 1, n + 5)
        case `j_` => loop(acc + k, i_, j_, k, n + 5)
        case _    => loop(acc, i_, j_, k, n + 1)
      }
    }

    loop(0, S.indexOf("heavy"), S.indexOf("metal"), 0, 0)
  }

  out.println(solve)
  out.close
}

import scala.annotation.tailrec
object B {
    def getSlice(s: String, h: String, idx: Int = 0, res: List[Int] = Nil): List[Int] = {
        //println(s)
        s.indexOf(h, idx) match {
            case -1 => res
            case x => getSlice(s, h, x + h.length, x :: res)
        }
    }

    @tailrec
    def solve(l: List[Int], r: List[Int], llen: Long, rlen: Long, res: Long = 0): Long = {
        l match {
            case x :: xs => {
                r match {
                    case y :: ys => {
                        if(x > y) solve(l, ys, res, llen, rlen-1)
                        else solve(xs, r, res + rlen, llen-1, rlen)
                    }
                    case Nil => res
                }
            }
            case Nil => res
        }
    }

    def main(args: Array[String]) {
        val ll = readLine
        val heavy = getSlice(ll, "heavy").sortWith(_ < _)
        val metal = getSlice(ll, "metal").sortWith(_ < _)
        println(solve(heavy, metal, heavy.length, metal.length))
    }
}


Boboniu likes bit operations. He wants to play a game with you.Boboniu gives you two sequences of non-negative integers $$$a_1,a_2,\ldots,a_n$$$ and $$$b_1,b_2,\ldots,b_m$$$.For each $$$i$$$ ($$$1\le i\le n$$$), you're asked to choose a $$$j$$$ ($$$1\le j\le m$$$) and let $$$c_i=a_i\& b_j$$$, where $$$\&$$$ denotes the bitwise AND operation. Note that you can pick the same $$$j$$$ for different $$$i$$$'s.Find the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$, where $$$|$$$ denotes the bitwise OR operation.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1\le n,m\le 200$$$). The next line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$0\le a_i < 2^9$$$). The next line contains $$$m$$$ integers $$$b_1,b_2,\ldots,b_m$$$ ($$$0\le b_i < 2^9$$$).

Print one integer: the minimum possible $$$c_1 | c_2 | \ldots | c_n$$$.

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

  val Array(n, m) = readLine().split(" ").map(_.toInt)
  val an          = readLine().split(" ").map(_.toInt)
  val bm          = readLine().split(" ").map(_.toInt)

  val ans = an
    .foldLeft(1 +: Array.fill(511)(0)) { (xs, a) =>
      xs.zipWithIndex.foldLeft(Array.fill(512)(0)) {
        case (ys, (0, _)) => ys
        case (ys, (1, i)) =>
          bm.foreach(b => ys(i | a & b) = 1) // (i | a & b) >= i
          ys
      }
    }
    .indexWhere(_ == 1)

  println(ans)
}


You are given two arrays $$$a$$$ and $$$b$$$ of $$$n$$$ positive integers each. You can apply the following operation to them any number of times:  Select an index $$$i$$$ ($$$1\leq i\leq n$$$) and swap $$$a_i$$$ with $$$b_i$$$ (i. e. $$$a_i$$$ becomes $$$b_i$$$ and vice versa). Find the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times (possibly zero).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1\le n\le 100$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10\,000$$$) where $$$a_i$$$ is the $$$i$$$-th element of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 10\,000$$$) where $$$b_i$$$ is the $$$i$$$-th element of the array $$$b$$$.

For each test case, print a single integer, the minimum possible value of $$$\max(a_1, a_2, \ldots, a_n) \cdot \max(b_1, b_2, \ldots, b_n)$$$ you can get after applying such operation any number of times.

NoteIn the first test, you can apply the operations at indices $$$2$$$ and $$$6$$$, then $$$a = [1, 4, 6, 5, 1, 5]$$$ and $$$b = [3, 2, 3, 2, 2, 2]$$$, $$$\max(1, 4, 6, 5, 1, 5) \cdot \max(3, 2, 3, 2, 2, 2) = 6 \cdot 3 = 18$$$.In the second test, no matter how you apply the operations, $$$a = [3, 3, 3]$$$ and $$$b = [3, 3, 3]$$$ will always hold, so the answer is $$$\max(3, 3, 3) \cdot \max(3, 3, 3) = 3 \cdot 3 = 9$$$.In the third test, you can apply the operation at index $$$1$$$, then $$$a = [2, 2]$$$, $$$b = [1, 1]$$$, so the answer is $$$\max(2, 2) \cdot \max(1, 1) = 2 \cdot 1 = 2$$$.

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val b = readInts()
    val (min, max) = a.zip(b).map {case (a, b) => (Math.min(a, b), Math.max(a, b))}.unzip

    println(min.max * max.max)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import scala.io.StdIn.readInt;
import scala.io.StdIn.readLine;

object Hello {
    def main(args: Array[String]) = {
        val t = readInt();
        for(s <- 1 to t){
          val n = readInt();
            val A: Array[Int] = readLine().split(' ').map(_.toInt);
            val B: Array[Int] = readLine().split(' ').map(_.toInt);
            val CMax : Array[Int] = A.zip(B).map({case(x , y)=>math.max(x,y)});
            val CMin : Array[Int] = A.zip(B).map({case(x , y)=>math.min(x,y)});
            val C: Int = CMax.reduceLeft(_ max _)*CMin.reduceLeft(_ max _);
            println(C);
            }
    }
}

object Solution{
  def main(args: Array[String]):Unit=
  {
    val T = scala.io.StdIn.readLine().toInt
    val len = new Array[Int](T)
    var as = new Array[List[Int]](T)
    var bs = new Array[List[Int]](T)
    for(k <- 0 until T)
    {
      len(k) = scala.io.StdIn.readLine().toInt
      as(k) = ((scala.io.StdIn.readLine().split(" ")).map(_.toInt)).toList
      bs(k) = ((scala.io.StdIn.readLine().split(" ")).map(_.toInt)).toList
    }

    def solve(a: List[Int], b: List[Int], l: Int): Int =
    {
      var M = -1
      var maxIndex = -1
      var aMax = a.max
      var bMax = b.max
      var aMaxInd = a.indexOf(aMax)
      var bMaxInd = b.indexOf(bMax)
      if(aMax >= bMax)
      {
        M = aMax
        maxIndex = aMaxInd
      }
      if(aMax < bMax)
      {
        M = bMax
        maxIndex = bMaxInd
      }
      var list = List.empty[Int]
      for (i <- 0 until l)
      {
        if(i != maxIndex) list = list:+ a(i).min(b(i))
        else list = list:+ (if (aMax >= bMax) b(maxIndex) else a(maxIndex))
      }
      return M * list.max
    }
    for(k <- 0 until T)
    {
      println(solve(as(k),bs(k), len(k)))
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    readInt()
    val a = readInts()
    val b = readInts()
    val c = (a ++ b).sorted

    println(c.last * c(a.length - 1))
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}


Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points.Polycarp does not remember how many points the participant had before this k marks were given, but he remembers that among the scores announced after each of the k judges rated the participant there were n (n ≤ k) values b1, b2, ..., bn (it is guaranteed that all values bj are distinct). It is possible that Polycarp remembers not all of the scores announced, i. e. n < k. Note that the initial score wasn't announced.Your task is to determine the number of options for the score the participant could have before the judges rated the participant.

The first line contains two integers k and n (1 ≤ n ≤ k ≤ 2 000) — the number of jury members and the number of scores Polycarp remembers. The second line contains k integers a1, a2, ..., ak ( - 2 000 ≤ ai ≤ 2 000) — jury's marks in chronological order. The third line contains n distinct integers b1, b2, ..., bn ( - 4 000 000 ≤ bj ≤ 4 000 000) — the values of points Polycarp remembers. Note that these values are not necessarily given in chronological order.

Print the number of options for the score the participant could have before the judges rated the participant. If Polycarp messes something up and there is no options, print "0" (without quotes).

NoteThe answer for the first example is 3 because initially the participant could have  - 10, 10 or 15 points.In the second example there is only one correct initial score equaling to 4 002 000.

import scala.collection.mutable

object C extends App {

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

  val Array(k, n) = readInts(2)
  val as = readInts(k)
  val bs = readInts(n)

  val aRunning = as.scan(0)(_ + _).drop(1)
  val bMax = bs.max
  val res = mutable.Set.empty[Int]

  for (i <- 0 until k) {

    val aSum = aRunning(i)
    val score0 = bMax - aSum
    var score = score0
    val availableBs = mutable.Set.empty[Int] ++ bs

    var j = 0
    while (j < k && availableBs.nonEmpty) {
      score += as(j)
      availableBs -= score
      j += 1
    }

    if (availableBs.isEmpty) res += score0
  }

  println(res.size)
}

import scala.collection.mutable

object C 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(k, n) = readInts(2)
  val as = readInts(k)
  val bs = readInts(n)
  //val as = mutable.Set.empty[Int]
  val cnts = Array.fill(10000){ 0 }
  for (a <- as) cnts(2000 + a) += 1

  def has(d: Int): Boolean = {
    d >= 0 && d < cnts.length && cnts(d) > 0
  }

  val used = new mutable.BitSet(n)

  for (i <- 0 until n) if (!used(i)) {
    var j = 0
    while (j < n) {
      if (i != j && !used(j)) {
        val d = bs(i) - bs(j)
        if (has(2000 + d)) {
          //println(i, j, d)
          cnts(2000 + d) -= 1
          used += j
        }
      }
      j += 1
    }
  }

  val res = if (used.size == n - 1) as.size - 1 else 0

  println(res)
}

import scala.collection.mutable

object C 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(k, n) = readInts(2)
  val as = readInts(k)
  val bs = readInts(n)
  //val as = mutable.Set.empty[Int]
  val cnts = Array.fill(10000){ 0 }
  for (a <- as) cnts(2000 + a) += 1

  def has(d: Int): Boolean = {
    d >= 0 && d < cnts.length && cnts(d) > 0
  }

  val used = new mutable.BitSet(n)

  for (i <- 0 until n) if (!used(i)) {
    var j = 0
    while (j < n) {
      if (i != j && !used(j)) {
        val d = bs(i) - bs(j)
        if (has(2000 + d)) {
          //println(i, j, d)
          cnts(2000 + d) -= 1
          used += j
        }
      }
      j += 1
    }
  }

  val res = if (used.size == n - 1) as.count(_ != 0) - n + 1 else 0

  println(res)
}

import scala.collection.mutable

object C 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(k, n) = readInts(2)
  val as = readInts(k)
  val bs = readInts(n)
  //val as = mutable.Set.empty[Int]
  val cnts = Array.fill(10000){ 0 }
  for (a <- as) cnts(2000 + a) += 1

  def has(d: Int): Boolean = {
    d >= 0 && d < cnts.length && cnts(d) > 0
  }

  val used = new mutable.BitSet(n)

  for (i <- 0 until n) if (!used(i)) {
    var j = 0
    while (j < n) {
      if (i != j && !used(j)) {
        val d = bs(i) - bs(j)
        if (has(2000 + d)) {
          println(i, j, d)
          cnts(2000 + d) -= 1
          used += j
        }
      }
      j += 1
    }
  }

  val res = if (used.size == n - 1) as.size - 1 else 0

  println(res)
}


Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k.Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them.

The single line contains two integers, n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000).

Print any beautiful table. Levko doesn't like too big numbers, so all elements of the table mustn't exceed 1000 in their absolute value. If there are multiple suitable tables, you are allowed to print any of them.

NoteIn the first sample the sum in the first row is 1 + 3 = 4, in the second row — 3 + 1 = 4, in the first column — 1 + 3 = 4 and in the second column — 3 + 1 = 4. There are other beautiful tables for this sample.In the second sample the sum of elements in each row and each column equals 7. Besides, there are other tables that meet the statement requirements.

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val res = (0 until n).map { i =>
    "0 " * i + k + " " + "0 " * (n - i - 1)
  }.mkString("\n")
  println(res)
}

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

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

  val N, K = sc.nextInt

  def solve(): Unit = {
    0 until N foreach { i =>
      val row = List.fill(i)(0) ::: List(K) ::: List.fill(N - 1 - i)(0)
      out.println(row.mkString(" "))
    }
  }

  solve
  out.close
}

object Main {
  def main(args: Array[String]) {
    val nk = readLine().split(" ").map(_.toInt)
    val n = nk(0)
    val k = nk(1)

    val m = k / n
    val d = k - m * n + m

    val a = Array.fill[Int](n)(m)
    for (i <- 1 to n) {
      a(i - 1) = d
      println(a.mkString(" "))
      a(i - 1) = m
    }
  }
}


After getting kicked out of her reporting job for not knowing the alphabet, Bessie has decided to attend school at the Fillet and Eggs Eater Academy. She has been making good progress with her studies and now knows the first k English letters.Each morning, Bessie travels to school along a sidewalk consisting of m + n tiles. In order to help Bessie review, Mr. Moozing has labeled each of the first m sidewalk tiles with one of the first k lowercase English letters, spelling out a string t. Mr. Moozing, impressed by Bessie's extensive knowledge of farm animals, plans to let her finish labeling the last n tiles of the sidewalk by herself.Consider the resulting string s (|s| = m + n) consisting of letters labeled on tiles in order from home to school. For any sequence of indices p1 < p2 < ... < pq we can define subsequence of the string s as string sp1sp2... spq. Two subsequences are considered to be distinct if they differ as strings. Bessie wants to label the remaining part of the sidewalk such that the number of distinct subsequences of tiles is maximum possible. However, since Bessie hasn't even finished learning the alphabet, she needs your help!Note that empty subsequence also counts.

The first line of the input contains two integers n and k (0 ≤ n ≤ 1 000 000, 1 ≤ k ≤ 26). The second line contains a string t (|t| = m, 1 ≤ m ≤ 1 000 000) consisting of only first k lowercase English letters.

Determine the maximum number of distinct subsequences Bessie can form after labeling the last n sidewalk tiles each with one of the first k lowercase English letters. Since this number can be rather large, you should print it modulo 109 + 7. Please note, that you are not asked to maximize the remainder modulo 109 + 7! The goal is to maximize the initial value and then print the remainder.

NoteIn the first sample, the optimal labeling gives 8 different subsequences: "" (the empty string), "a", "c", "b", "ac", "ab", "cb", and "acb".  In the second sample, the entire sidewalk is already labeled. The are 10 possible different subsequences: "" (the empty string), "a", "b", "aa", "ab", "ba", "aaa", "aab", "aba", and "aaba". Note that some strings, including "aa", can be obtained with multiple sequences of tiles, but are only counted once.

import scala.collection._

object E 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, k) = readInts(2)
  val t = readLine.map(_ - 'a')
  val MOD = 1000000007L

  var res = 1L

  val lastPos = Array.fill(k){ -1 }
  var dp = Array.fill(k){ 0L }

  var pos = 0

  for (c <- t) {
    lastPos(c) = pos
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
    pos += 1
  }

  val pq = mutable.PriorityQueue.empty(Ordering.by(lastPos).reverse)
  pq ++= 0 until k

  var i = 0
  var prev = -1
  while (i < n) {
    i += 1
    val c = pq.dequeue()
    lastPos(c) = pos
    pq += c
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
    prev = c
    pos += 1
  }

  println(res % MOD)
}

import scala.collection._

object E 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, k) = readInts(2)
  val t = readLine.map(_ - 'a')
  val MOD = 1000000007L

  var res = 1L

  val cnt = Array.fill(k){ 0 }
  var dp = Array.fill(k){ 0L }

  for (c <- t) {
    cnt(c) += 1
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
  }

  val pq = mutable.TreeSet.empty[Int](Ordering.by(cnt))
  (0 until k).foreach(i => pq.add(i))

  var i = 0
  while (i < n) {
    i += 1
    val c = pq.head
    pq.remove(c)
    cnt(c) -= 1
    pq += c
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
  }

  println(res % MOD)
}

import scala.collection._

object E 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, k) = readInts(2)
  val t = readLine.map(_ - 'a')
  val MOD = 1000000007L

  var res = 1L

  val cnts = Array.fill(k){ 0 }
  var dp = Array.fill(k){ 0L }

  for (c <- t) {
    cnts(c) += 1
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
  }

  val pq = mutable.PriorityQueue.empty(Ordering.by(cnts).reverse)
  pq ++= 0 until k

  var i = 0
  var prev = -1
  while (i < n) {
    i += 1
    val c = {
      val _c = pq.dequeue()
      if (_c == prev && pq.nonEmpty && cnts(pq.head) == cnts(_c)) {
        val c2 = pq.dequeue()
        pq += _c
        c2
      } else _c
    }
    cnts(c) -= 1
    pq += c
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
    prev = c
  }

  println(res % MOD)
}

import scala.collection._

object E 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, k) = readInts(2)
  val t = readLine.map(_ - 'a')
  val MOD = 1000000007L

  var res = 1L

  val cnt = Array.fill(k){ 0 }
  var dp = Array.fill(k){ 0L }

  for (c <- t) {
    cnt(c) += 1
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
  }

  val pq = mutable.PriorityQueue.empty(Ordering.by(cnt).reverse)
  pq ++= 0 until k

  var i = 0
  while (i < n) {
    i += 1
    val c = pq.dequeue()
    cnt(c) -= 1
    pq += c
    val x = (MOD + res - dp(c)) % MOD
    dp(c) = (dp(c) + x) % MOD
    res = (res + x) % MOD
  }

  println(res % MOD)
}


You are given a positive integer $$$n$$$. In one move, you can increase $$$n$$$ by one (i.e. make $$$n := n + 1$$$). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 10^{18}$$$; $$$1 \le s \le 162$$$).

For each test case, print the answer: the minimum number of moves you need to perform in order to make the sum of digits of $$$n$$$ be less than or equal to $$$s$$$.

//package codeforces.contests._1409

object DecreaseTheSumOfDigits {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {

      val Array(n, g) = io.StdIn.readLine.split(" ").map(_.toLong)

      val digits = n.toString.map(_ - '0')

      @scala.annotation.tailrec
      def loop(i: Int = digits.indices.last, carry: Int = 0, s: Int = digits.sum): Long = {
        if (i < 0) ("1" + "0" * digits.length).toLong - n
        else if (s <= g) ((digits.slice(0, i + 1).mkString("").toLong + carry).toString + "0" * (digits.length - 1 - i)).toLong - n
        else loop(i - 1, if (carry == 0) 1 else 1, s - digits(i) + (if (carry == 0) 1 else 0))
      }

      println(loop())
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine.toInt
    for (_ <- 0 until t) {
      val arr = StdIn.readLine.split(" ").map(_.toLong)
      val (n, s) = (arr(0), arr(1))
      var d = -1
      var acc = 0
      for (c <- n.toString if (acc < s)) {
        acc += c - '0'; d += 1
      }
      val res = if (n.toString.toCharArray.map(_ - '0').sum <= s) 0
      else if (d == 0) {
        ("1" + "0" * n.toString.length).toLong - n
      } else {
        ((n.toString.take(d).toLong + 1).toString + "0" * (n.toString.length - d)).toLong - n
      }
      println(res)
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine.toInt
    for (_ <- 0 until t) {
      val arr = StdIn.readLine.split(" ").map(_.toLong)
      val (n, s) = (arr(0), arr(1))
      var d = -1
      var acc = 0
      for (c <- n.toString if (acc < s)) {
        acc += c - '0'; d += 1
      }
      val res = if (d == 0) {
        ("1" + "0" * n.toString.length).toLong - n
      } else {
        ((n.toString.take(d).toLong + 1).toString + "0" * (n.toString.length - d)).toLong - n
      }
      println(res)
    }
  }
}


Bimokh is Mashmokh's boss. For the following n days he decided to pay to his workers in a new way. At the beginning of each day he will give each worker a certain amount of tokens. Then at the end of each day each worker can give some of his tokens back to get a certain amount of money. The worker can save the rest of tokens but he can't use it in any other day to get more money. If a worker gives back w tokens then he'll get  dollars. Mashmokh likes the tokens however he likes money more. That's why he wants to save as many tokens as possible so that the amount of money he gets is maximal possible each day. He has n numbers x1, x2, ..., xn. Number xi is the number of tokens given to each worker on the i-th day. Help him calculate for each of n days the number of tokens he can save.

The first line of input contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The second line of input contains n space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 109).

Output n space-separated integers. The i-th of them is the number of tokens Mashmokh can save on the i-th day.

object Main {
  def main(args: Array[String]) {
    val Array(n, a, b) = readLine().split(' ').map(_.toInt)
    val in = readLine().split(' ').map(_.toLong)
    val ans = in.map(x => x - ((x * a) / b) * b / a - (if (((x * a) / b * b) % a != 0) 1 else 0))
    for (i <- 0 until n - 1) {
      print(ans(i) + " ")
    }
    println(ans.last)
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a else gcd(b, a % b)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, a, b) = readLine().split(' ').map(_.toInt)
    val in = readLine().split(' ').map(_.toLong)
    val ans = in.map(x => x - ((x * a) / b) * b / a)
    for (i <- 0 until n - 1) {
      print(ans(i) + " ")
    }
    println(ans.last)
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a else gcd(b, a % b)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, a, b) = readLine().split(' ').map(_.toInt)
    val in = readLine().split(' ').map(_.toLong)
    val ans = in.map(x => x % (b / gcd(a, b)))
    for (i <- 0 until n - 1) {
      print(ans(i) + " ")
    }
    println(ans.last)
  }

  def gcd(a: Long, b: Long): Long = {
    if (b == 0) a else gcd(b, a % b)
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, a, b) = readLine().split(' ').map(_.toInt)
    val in = readLine().split(' ').map(_.toLong)
    val ans = in.map(x => (x * a) % b)
    for (i <- 0 until n - 1) {
      print(ans(i) + " ")
    }
    println(ans.last)
  }
}


Haha, try to solve this, SelectorUnlimited!— antontrygubO_oYour friends Alice and Bob practice fortune telling.Fortune telling is performed as follows. There is a well-known array $$$a$$$ of $$$n$$$ non-negative integers indexed from $$$1$$$ to $$$n$$$. The tellee starts with some non-negative number $$$d$$$ and performs one of the two operations for each $$$i = 1, 2, \ldots, n$$$, in the increasing order of $$$i$$$. The possible operations are: replace their current number $$$d$$$ with $$$d + a_i$$$ replace their current number $$$d$$$ with $$$d \oplus a_i$$$ (hereinafter $$$\oplus$$$ denotes the bitwise XOR operation)Notice that the chosen operation may be different for different $$$i$$$ and for different tellees.One time, Alice decided to start with $$$d = x$$$ and Bob started with $$$d = x + 3$$$. Each of them performed fortune telling and got a particular number in the end. Notice that the friends chose operations independently of each other, that is, they could apply different operations for the same $$$i$$$.You learnt that either Alice or Bob ended up with number $$$y$$$ in the end, but you don't know whose of the two it was. Given the numbers Alice and Bob started with and $$$y$$$, find out who (Alice or Bob) could get the number $$$y$$$ after performing the operations. It is guaranteed that on the jury tests, exactly one of your friends could have actually gotten that number.HacksYou cannot make hacks in this problem.

On the first line of the input, you are given one number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The following $$$2 \cdot t$$$ lines contain test cases. The first line of each test case contains three numbers $$$n$$$, $$$x$$$, $$$y$$$ ($$$1 \le n \le 10^5$$$, $$$0 \le x \le 10^9$$$, $$$0 \le y \le 10^{15}$$$) — the length of array $$$a$$$, Alice's initial number (Bob's initial number is therefore $$$x+3$$$), and the number that one of the two friends got in the end. The second line of each test case contains $$$n$$$ numbers — the array $$$a$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print the name of the friend who could get the number $$$y$$$: "Alice" or "Bob".

NoteIn the first test case, Alice could get $$$9$$$ using the following operations: $$$7 + 2 = 9$$$.In the second test case, Alice could get $$$2$$$ using this operations: $$$(0 + 1) \oplus 3 = 2$$$.In the third test case, Bob started with $$$x+3 = 0+3=3$$$ and could get $$$1$$$ this way: $$$(((3 + 1) + 2) \oplus 3) \oplus 4 = 1$$$.

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val Array(_, x, y) = readLongs()
    val numbers = readLongs()
    val lastBit = (numbers.reduce(_ ^ _) ^ y) % 2
    val answer = if ( (x % 2) == lastBit ) "Alice" else "Bob"
    println(answer)
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

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

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

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

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

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        val x = readLong()
        val y = readLong()
        var ans = x % 4L
        val k = y % 4L
        var a = 0
        for (i <- 1 to n) {
            a = readInt()
            ans = (ans + a) % 4
        }
        if (ans % 2 == k % 2) {
            writer.println("Alice")
        } else {
            writer.println("Bob")
        }

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


Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: An 'L' indicates he should move one unit left.  An 'R' indicates he should move one unit right.  A 'U' indicates he should move one unit up.  A 'D' indicates he should move one unit down.But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.

The first and only line contains the string s (1 ≤ |s| ≤ 100 000) — the instructions Memory is given.

If there is a string satisfying the conditions, output a single integer — the minimum number of edits required. In case it's not possible to change the sequence in such a way that it will bring Memory to to the origin, output -1.

NoteIn the first sample test, Memory is told to walk right, then right, then up. It is easy to see that it is impossible to edit these instructions to form a valid walk.In the second sample test, Memory is told to walk up, then down, then up, then right. One possible solution is to change s to "LDUR". This string uses 1 edit, which is the minimum possible. It also ends at the origin.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val str = in.next()
  if (str.length % 2 == 1)
    println(-1)
  else {
    val xDiff = Math.abs(str.count(_ == 'R') - str.count(_ == 'L'))
    val yDiff = Math.abs(str.count(_ == 'U') - str.count(_ == 'D'))
    println((xDiff + yDiff) / 2)
  }
}

object B712 {

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

  def main(args: Array[String]): Unit = {
    val in = read
    var u, d, r, l = 0
    for(c <- in) {
      if(c == 'U') u += 1
      else if(c == 'D') u -= 1
      else if(c == 'R') r += 1
      else if(c == 'L') r -= 1
    }
    if(in.length%2 == 0) {
      println((math.abs(u) + math.abs(r))/2)
    } else {
      println("-1")
    }
  }

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

}

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

object _712B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val instr = read[String]
    var x, y = 0

    instr foreach {
      case 'L' => x -= 1
      case 'R' => x += 1
      case 'U' => y += 1
      case 'D' => y -= 1
    }

    x = x.abs
    y = y.abs

    val ans = (x%2, y%2) match {
      case (0, 0) => x/2 + y/2
      case (0, 1) => -1
      case (1, 0) => -1
      case (1, 1) => x/2 + y/2 + 1
    }

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
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 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, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)

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

object B712 {

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

  def main(args: Array[String]): Unit = {
    val in = read
    var u, d, r, l = 0
    for(c <- in) {
      if(c == 'U') u += 1
      else if(c == 'D') d += 1
      else if(c == 'R') r += 1
      else if(c == 'L') l += 1
    }
    if(in.length%4 == 0) {
      val res = Array(u,d,r,l)
        .filter(in.length/4 > _)
        .map{x => in.length/4 - x}.sum
      println(res)
    } else {
      println("-1")
    }
  }

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

}


Kuroni has $$$n$$$ daughters. As gifts for them, he bought $$$n$$$ necklaces and $$$n$$$ bracelets:  the $$$i$$$-th necklace has a brightness $$$a_i$$$, where all the $$$a_i$$$ are pairwise distinct (i.e. all $$$a_i$$$ are different),  the $$$i$$$-th bracelet has a brightness $$$b_i$$$, where all the $$$b_i$$$ are pairwise distinct (i.e. all $$$b_i$$$ are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$ and a bracelet with brightness $$$y_i$$$, then the sums $$$x_i + y_i$$$ should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are $$$a = [1, 7, 5]$$$ and $$$b = [6, 1, 2]$$$, then we may distribute the gifts as follows:  Give the third necklace and the first bracelet to the first daughter, for a total brightness of $$$a_3 + b_1 = 11$$$. Give the first necklace and the third bracelet to the second daughter, for a total brightness of $$$a_1 + b_3 = 3$$$. Give the second necklace and the second bracelet to the third daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Here is an example of an invalid distribution:   Give the first necklace and the first bracelet to the first daughter, for a total brightness of $$$a_1 + b_1 = 7$$$. Give the second necklace and the second bracelet to the second daughter, for a total brightness of $$$a_2 + b_2 = 8$$$. Give the third necklace and the third bracelet to the third daughter, for a total brightness of $$$a_3 + b_3 = 7$$$. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$)  — the number of daughters, necklaces and bracelets. The second line of each test case contains $$$n$$$ distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 1000$$$)  — the brightnesses of the necklaces. The third line of each test case contains $$$n$$$ distinct integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 1000$$$)  — the brightnesses of the bracelets.

For each test case, print a line containing $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$, representing that the $$$i$$$-th daughter receives a necklace with brightness $$$x_i$$$. In the next line print $$$n$$$ integers $$$y_1, y_2, \dots, y_n$$$, representing that the $$$i$$$-th daughter receives a bracelet with brightness $$$y_i$$$. The sums $$$x_1 + y_1, x_2 + y_2, \dots, x_n + y_n$$$ should all be distinct. The numbers $$$x_1, \dots, x_n$$$ should be equal to the numbers $$$a_1, \dots, a_n$$$ in some order, and the numbers $$$y_1, \dots, y_n$$$ should be equal to the numbers $$$b_1, \dots, b_n$$$ in some order.  It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.

NoteIn the first test case, it is enough to give the $$$i$$$-th necklace and the $$$i$$$-th bracelet to the $$$i$$$-th daughter. The corresponding sums are $$$1 + 8 = 9$$$, $$$8 + 4 = 12$$$, and $$$5 + 5 = 10$$$.The second test case is described in the statement.

import java.io.PrintWriter

import scala.collection.mutable
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readString(): String = reader.readLine()

    def multiTest(f: () => Unit): Unit = {
        var t = readInt()
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        val n = readInt()
        val a = readArrayInt().sortWith(_ > _)
        val b = readArrayInt().sortWith(_ > _)

        a.map(p => print(s"$p "))
        println()
        b.map(p => print(s"$p "))
        println()
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
    }
}


You are given a sequence $$$s$$$ consisting of $$$n$$$ digits from $$$1$$$ to $$$9$$$.You have to divide it into at least two segments (segment — is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the resulting division will be represented as an integer numbers sequence then each next element of this sequence will be strictly greater than the previous one.More formally: if the resulting division of the sequence is $$$t_1, t_2, \dots, t_k$$$, where $$$k$$$ is the number of element in a division, then for each $$$i$$$ from $$$1$$$ to $$$k-1$$$ the condition $$$t_{i} < t_{i + 1}$$$ (using numerical comparing, it means that the integer representations of strings are compared) should be satisfied.For example, if $$$s=654$$$ then you can divide it into parts $$$[6, 54]$$$ and it will be suitable division. But if you will divide it into parts $$$[65, 4]$$$ then it will be bad division because $$$65 > 4$$$. If $$$s=123$$$ then you can divide it into parts $$$[1, 23]$$$, $$$[1, 2, 3]$$$ but not into parts $$$[12, 3]$$$.Your task is to find any suitable division for each of the $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 300$$$) — the number of queries. The first line of the $$$i$$$-th query contains one integer number $$$n_i$$$ ($$$2 \le n_i \le 300$$$) — the number of digits in the $$$i$$$-th query. The second line of the $$$i$$$-th query contains one string $$$s_i$$$ of length $$$n_i$$$ consisting only of digits from $$$1$$$ to $$$9$$$.

If the sequence of digits in the $$$i$$$-th query cannot be divided into at least two parts in a way described in the problem statement, print the single line "NO" for this query. Otherwise in the first line of the answer to this query print "YES", on the second line print $$$k_i$$$ — the number of parts in your division of the $$$i$$$-th query sequence and in the third line print $$$k_i$$$ strings $$$t_{i, 1}, t_{i, 2}, \dots, t_{i, k_i}$$$ — your division. Parts should be printed in order of the initial string digits. It means that if you write the parts one after another without changing their order then you'll get the string $$$s_i$$$. See examples for better understanding.

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val N = ni()
      val A = ns(N)
      if (A.length == 2 && A(0) >= A(1)) {
        out.println("NO")
      } else {
        out.println("YES")
        out.println("2")
        out.println(s"${A(0)} ${A.drop(1).mkString}")
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

object Main {

  def compareStrings(lValue: String, rValue: String) = {

    if (lValue.length < rValue.length) {
      true
    }
    else if (lValue.length > rValue.length) {
      false
    }
    else {
      val index = lValue.zip(rValue).indexWhere(x => x._1 != x._2)
      if (index == -1) {
        false
      }
      else if (lValue(index).toInt < rValue(index).toInt) {
        true
      }
      else {
        false
      }
    }
  }

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val t = std.readLine().toInt

    for (_ <- 0 until t) {
      val value = std.readLine().toInt
      val seq = std.readLine()

      val index = seq.tail.indexWhere(x => x != '0')
      if (index != -1) {
        val first = seq.take(index + 1)
        val second = seq.drop(index + 1)
        if (compareStrings(first, second)) {
          println("YES")
          println(2)
          println(first + " " + second)
        }
        else {
          println("NO")
        }
      }
      else {
        println("NO")
      }
    }
  }
}

import java.util
import java.util.regex.Pattern

import scala.io.StdIn
import scala.util.Sorting

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val _ = readInt()
    val str = readLine()

    if (str.length == 2 && Integer.valueOf(str.substring(1)) <= Integer.valueOf(str.substring(0, 1))) {
      println("NO")
      return
    }

    println("YES")
    println(2)
    println(s"${str.charAt(0)} ${str.substring(1)}")
  }

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

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

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

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

object Main {

  def compareStrings(lValue: String, rValue: String) = {

    if (lValue.length < rValue.length) {
      true
    }
    else if (lValue.length > rValue.length) {
      false
    }
    else {
      val index = lValue.zip(rValue).indexWhere(x => x._1 != x._2)
      if (index == -1) {
        false
      }
      else if (lValue(index).toInt < rValue(index).toInt) {
        true
      }
      else {
        false
      }
    }
  }

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val t = std.readLine().toInt

    for (_ <- 0 until t) {
      val value = std.readLine().toInt
      val seq = std.readLine()

      val index = seq.tail.indexWhere(x => x != '0')
      if (index != -1) {
        val first = seq.take(index + 1)
        val second = seq.drop(index + 1)
        if (compareStrings(first, second)) {
          println("YES")
          println(2)
          println(first, second)
        }
        else {
          println("NO")
        }
      }
      else {
        println("NO")
      }
    }
  }
}

object Main {

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val t = std.readLine().toInt

    for (_ <- 0 until t) {
      val value = std.readLine().toInt
      val seq = std.readLine().map(_.toInt)

      if (seq.length < 2) {
        println("NO")
      }
      else if (seq.length == 2 && seq(0) >= seq(1)) {
        println("NO")
      }
      else {
        println("YES")
        println(2)
        println(seq.head.toChar, seq.tail.map(_.toChar).foldLeft("")((x, y) => x + y))
      }
    }
  }
}

import java.util
import java.util.regex.Pattern

import scala.io.StdIn
import scala.util.Sorting

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val _ = readInt()
    val str = readLine()

    if (str.length == 2 && Integer.valueOf(str.substring(1)) <= Integer.valueOf(str.substring(0, 1))) {
      println("NO")
      return
    }

    println(2)
    println(s"${str.charAt(0)}, ${str.substring(1)}")
  }

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

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

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

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

import java.util
import java.util.regex.Pattern

import scala.io.StdIn
import scala.util.Sorting

object Solution {
  //Console.setIn(new FileReader(new java.io.File("in")))
  //Console.setOut(new PrintStream(new java.io.File("output")))

  val magicMod = 1000000007

  def doCase(caseNo: Int): Unit = {
    val _ = readInt()
    val str = readLine()

    if (str.length == 2 && Integer.valueOf(str.substring(1)) <= Integer.valueOf(str.substring(0, 1))) {
      println("NO")
      return
    }

    println("YES")
    println(2)
    println(s"${str.charAt(0)}, ${str.substring(1)}")
  }

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

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

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

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


Find out if it is possible to partition the first $$$n$$$ positive integers into two non-empty disjoint sets $$$S_1$$$ and $$$S_2$$$ such that:$$$\mathrm{gcd}(\mathrm{sum}(S_1), \mathrm{sum}(S_2)) > 1$$$ Here $$$\mathrm{sum}(S)$$$ denotes the sum of all elements present in set $$$S$$$ and $$$\mathrm{gcd}$$$ means thegreatest common divisor.Every integer number from $$$1$$$ to $$$n$$$ should be present in exactly one of $$$S_1$$$ or $$$S_2$$$.

The only line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 45\,000$$$)

If such partition doesn't exist, print "No" (quotes for clarity). Otherwise, print "Yes" (quotes for clarity), followed by two lines, describing $$$S_1$$$ and $$$S_2$$$ respectively. Each set description starts with the set size, followed by the elements of the set in any order. Each set must be non-empty. If there are multiple possible partitions — print any of them.

NoteIn the first example, there is no way to partition a single number into two non-empty sets, hence the answer is "No".In the second example, the sums of the sets are $$$2$$$ and $$$4$$$ respectively. The $$$\mathrm{gcd}(2, 4) = 2 > 1$$$, hence that is one of the possible answers.

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = N.toLong * (N + 1) / 2

    def find: Option[Int] = {
      rep(N - 1, 2) { m =>
        if (S % m == 0) return Some(m)
      }
      None
    }

    find match {
      case None =>
        out.println("No")

      case Some(m) =>
        out.println("Yes")
        out.println(s"1 $m")

        out.print(s"${N - 1} ")
        out.println(map(N)(identity).map(_+1).filterNot(_ == m).mkString(" "))
    }
  }

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

  def gcd(a: Int, b: Int): Int = {
    val r = a % b
    if (r == 0) b
    else gcd(b, r)
  }

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

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

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

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