Ashish has a binary string $$$s$$$ of length $$$n$$$ that he wants to sort in non-decreasing order.He can perform the following operation:   Choose a subsequence of any length such that its elements are in non-increasing order. Formally, choose any $$$k$$$ such that $$$1 \leq k \leq n$$$ and any sequence of $$$k$$$ indices $$$1 \le i_1 \lt i_2 \lt \ldots \lt i_k \le n$$$ such that $$$s_{i_1} \ge s_{i_2} \ge \ldots \ge s_{i_k}$$$.  Reverse this subsequence in-place. Formally, swap $$$s_{i_1}$$$ with $$$s_{i_k}$$$, swap $$$s_{i_2}$$$ with $$$s_{i_{k-1}}$$$, $$$\ldots$$$ and swap $$$s_{i_{\lfloor k/2 \rfloor}}$$$ with $$$s_{i_{\lceil k/2 \rceil + 1}}$$$ (Here $$$\lfloor x \rfloor$$$ denotes the largest integer not exceeding $$$x$$$, and $$$\lceil x \rceil$$$ denotes the smallest integer not less than $$$x$$$) Find the minimum number of operations required to sort the string in non-decreasing order. It can be proven that it is always possible to sort the given binary string in at most $$$n$$$ operations.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ $$$(1 \le n \le 1000)$$$  — the length of the binary string $$$s$$$. The second line of each test case contains a binary string $$$s$$$ of length $$$n$$$ containing only $$$0$$$s and $$$1$$$s. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case output the following:   The minimum number of operations $$$m$$$ in the first line ($$$0 \le m \le n$$$).  Each of the following $$$m$$$ lines should be of the form: $$$k$$$ $$$i_1$$$ $$$i_2$$$ ... $$$i_{k}$$$, where $$$k$$$ is the length and $$$i_1 \lt i_2 \lt ... \lt i_{k}$$$ are the indices of the chosen subsequence. For them the conditions from the statement must hold.

NoteIn the first test case, the binary string is already sorted in non-decreasing order.In the second test case, we can perform the following operation:   $$$k = 4:$$$ choose the indices $$$\{1, 3, 4, 5\}$$$$$$\underline{1}$$$ $$$0$$$ $$$\underline{1}$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$ $$$\underline{1}$$$ In the third test case, we can perform the following operation:  $$$k = 3:$$$ choose the indices $$$\{3, 5, 6\}$$$$$$0$$$ $$$0$$$ $$$\underline{1}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{0}$$$ $$$\rightarrow $$$ $$$0$$$ $$$0$$$ $$$\underline{0}$$$ $$$0$$$ $$$\underline{0}$$$ $$$\underline{1}$$$

object _1605B extends CodeForcesApp {
  import Utils._, annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int]
    val s = io.read[String].map(c => c - '0').toArray

    @tailrec
    def solve(l: Int, r: Int): Seq[Int] = {
      if (l < r) {
        if (s(r) == 1) solve(l, r-1)
        else if (s(l) == 0) solve(l+1, r)
        else {
          val t = s.slice(l, r+1)
          val ts = t.sorted
          for {
            i <- l to r if t(i - l) != ts(i - l)
          } yield i
        }
      } else {
        Nil
      }
    }

    val ans = solve(0, n-1).map(_ + 1)

    if (ans.isEmpty) {
      io.write(0)
    } else {
      io.writeLine(1).write(ans.length, ans.mkString(" "))
    }
  }

  implicit class IntegralExtensions[A](x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
  }
}
/****************************[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 solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  val charToInt: Char => Int = Character.getNumericValue
  val intToChar: Int => Char = Character.forDigit(_, 10)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet(withDefaultZero: Boolean): Map[A, Int] = {
      val freqTable = t.groupBy(identity).mapValues(_.size)
      if (withDefaultZero) freqTable.withDefaultValue(0) else freqTable
    }
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    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 {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[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
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]
  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  def repeat(f: => Unit): Unit = Utils.repeat(read[Int]){f; writeLine()}

  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: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

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

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

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

    case class pair(val a: Int, val b:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return 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 mp = mutable.Map[Char, Int]()

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        var s = readString()
        var ans = Vector[Int]()
        var cnt = 0
        for (c <- s) {
            if (c == '0')
                cnt += 1
        }
        for (i <- 1 to s.length) {
            if (i <= cnt && s(i-1) == '1')
                ans :+= i
            if (i > cnt && s(i-1) == '0')
                ans :+= i
        }
        if (ans.nonEmpty) {
            writer.println(1)
            writer.print(ans.length)
            for (idx <- ans)
                writer.print(" " + idx)
            writer.println()
        } else {
            writer.println(0)
        }
    }
    writer.flush()
}


A string $$$s$$$ of length $$$n$$$, consisting of lowercase letters of the English alphabet, is given.You must choose some number $$$k$$$ between $$$0$$$ and $$$n$$$. Then, you select $$$k$$$ characters of $$$s$$$ and permute them however you want. In this process, the positions of the other $$$n-k$$$ characters remain unchanged. You have to perform this operation exactly once.For example, if $$$s=\texttt{"andrea"}$$$, you can choose the $$$k=4$$$ characters $$$\texttt{"a_d_ea"}$$$ and permute them into $$$\texttt{"d_e_aa"}$$$ so that after the operation the string becomes $$$\texttt{"dneraa"}$$$.Determine the minimum $$$k$$$ so that it is possible to sort $$$s$$$ alphabetically (that is, after the operation its characters appear in alphabetical order).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 40$$$) — the length of the string. The second line of each test case contains the string $$$s$$$. It is guaranteed that $$$s$$$ contains only lowercase letters of the English alphabet.

For each test case, output the minimum $$$k$$$ that allows you to obtain a string sorted alphabetically, through the operation described above.

NoteIn the first test case, we can choose the $$$k=2$$$ characters $$$\texttt{"_ol"}$$$ and rearrange them as $$$\texttt{"_lo"}$$$ (so the resulting string is $$$\texttt{"llo"}$$$). It is not possible to sort the string choosing strictly less than $$$2$$$ characters.In the second test case, one possible way to sort $$$s$$$ is to consider the $$$k=6$$$ characters $$$\texttt{"_o__force_"}$$$ and rearrange them as $$$\texttt{"_c__efoor_"}$$$ (so the resulting string is $$$\texttt{"ccdeefoors"}$$$). One can show that it is not possible to sort the string choosing strictly less than $$$6$$$ characters.In the third test case, string $$$s$$$ is already sorted (so we can choose $$$k=0$$$ characters).In the fourth test case, we can choose all $$$k=4$$$ characters $$$\texttt{"dcba"}$$$ and reverse the whole string (so the resulting string is $$$\texttt{"abcd"}$$$).

import scala.io.StdIn._;

object Main extends App {

//  def a(ignored: Int, z: Array[Long]): Long = z.zip(z.slice(1, z.length)).map(l => l._1 * l._2).max
//  for (_ <- 0 until readInt()) println(a(readInt(), readLine().split(" ").map(_.toLong)))
//  def b(l: Long): Long = (l + 1)/10

  def b(i: Int, s: String): Int = s.zip(s.sorted).map(k => if (k._1 == k._2) 0 else 1).sum

  for (_ <- 0 until readInt()) println(b(readInt(), readLine()))
}

//package global15

object A {

  /** TODO: Check! */
  private val multipleTests: Boolean = true

  def run(testNum: Int): Unit = {
    val n = int()
    val s = string()
    println(s.zip(s.sorted).count { case (a, b) => a != b })
  }

  /** Template. */

  private val onlineJudge = System.getProperty("ONLINE_JUDGE") != null

  def main(args: Array[String]): Unit = {
    val t = if (multipleTests) reader.int() else 1
    (1 to t).foreach(run)
  }

  /** I/O */

  import java.io._
  import java.nio.file._

  private val inputFileName = "input.txt"
  private val reader = if (onlineJudge) FastReader.fromConsole() else FastReader.fromFile(inputFileName)

  private def string(): String = reader.string()
  private def int(): Int = reader.int()
  private def long(): Long = reader.long()
  private def double(): Double = reader.double()

  final case class FastReader(delegate: BufferedReader) extends Iterator[String] with AutoCloseable {
    import java.util.StringTokenizer

    def string(): String = next()
    def line(): String = tokenizer().get.nextToken("\n\r")
    def boolean(): Boolean = next().toBoolean
    def byte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
    def short(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
    def int(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
    def long(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
    def bigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
    def float(): Float = next().toFloat
    def double(): Double = next().toDouble
    def bigDecimal(): BigDecimal = BigDecimal(next())
    def lineNumber(): Int = linedDelegate.getLineNumber

    @inline def nextLine(): String = {
      current = None // reset the rest of current line
      delegate.readLine()
    }

    override def hasNext: Boolean = tokenizer().nonEmpty
    override def next(): String = tokenizer().getOrElse(throw new RuntimeException("End of input")).nextToken()
    override def close(): Unit = delegate.close()

    private lazy val linedDelegate = new LineNumberReader(delegate)
    private val tokenizers = Iterator.continually(delegate.readLine())
      .takeWhile(_ != null)
      .map(new StringTokenizer(_))
      .filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

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

  object FastReader {
    import scala.io.Codec

    def fromConsole()(implicit codec: Codec): FastReader = fromStream(System.in)
    def fromFile(fileName: String)(implicit codec: Codec): FastReader = FastReader {
      Files.newBufferedReader(Paths.get(fileName), codec.charSet)
    }
    def fromString(string: String): FastReader = FastReader(new BufferedReader(new StringReader(string)))
    def fromStream(inputStream: InputStream)(implicit codec: Codec): FastReader = FastReader {
      new BufferedReader(new InputStreamReader(inputStream, codec.charSet))
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n = readInt()
    val s = readLine()

    val k = (s zip s.sorted).count { case (a, b) => a != b }

    println(k)
  }
}

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val s = nextLine
      val ss = s.sorted
      var res = 0
      for (i <- 0 until s.length) {
        if (s(i) != ss(i)) res += 1
      }

      out.println(res)
    }

    out.flush()
  }

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


Now Serval is a junior high school student in Japari Middle School, and he is still thrilled on math as before. As a talented boy in mathematics, he likes to play with numbers. This time, he wants to play with numbers on a rooted tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a node $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all nodes for which $$$v$$$ is the parent. A vertex is a leaf if it has no children.The rooted tree Serval owns has $$$n$$$ nodes, node $$$1$$$ is the root. Serval will write some numbers into all nodes of the tree. However, there are some restrictions. Each of the nodes except leaves has an operation $$$\max$$$ or $$$\min$$$ written in it, indicating that the number in this node should be equal to the maximum or minimum of all the numbers in its sons, respectively. Assume that there are $$$k$$$ leaves in the tree. Serval wants to put integers $$$1, 2, \ldots, k$$$ to the $$$k$$$ leaves (each number should be used exactly once). He loves large numbers, so he wants to maximize the number in the root. As his best friend, can you help him?

The first line contains an integer $$$n$$$ ($$$2 \leq n \leq 3\cdot 10^5$$$), the size of the tree. The second line contains $$$n$$$ integers, the $$$i$$$-th of them represents the operation in the node $$$i$$$. $$$0$$$ represents $$$\min$$$ and $$$1$$$ represents $$$\max$$$. If the node is a leaf, there is still a number of $$$0$$$ or $$$1$$$, but you can ignore it. The third line contains $$$n-1$$$ integers $$$f_2, f_3, \ldots, f_n$$$ ($$$1 \leq f_i \leq i-1$$$), where $$$f_i$$$ represents the parent of the node $$$i$$$.

Output one integer — the maximum possible number in the root of the tree.

NotePictures below explain the examples. The numbers written in the middle of the nodes are their indices, and the numbers written on the top are the numbers written in the nodes.In the first example, no matter how you arrange the numbers, the answer is $$$1$$$.  In the second example, no matter how you arrange the numbers, the answer is $$$4$$$.  In the third example, one of the best solution to achieve $$$4$$$ is to arrange $$$4$$$ and $$$5$$$ to nodes $$$4$$$ and $$$5$$$.  In the fourth example, the best solution is to arrange $$$5$$$ to node $$$5$$$.

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

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

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

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

  def solve(): Unit = {
    val n = ni()
    val f = na(n)
    val from, to = Array.ofDim[Int](n - 1)
    REP(n - 1) { i =>
      val p = ni() - 1
      from(i) = i + 1
      to(i) = p
    }
    val g = packUGraph(n, from, to)
    val (_, p, q) = traceBfs(g)
    val leafCnt = Array.ofDim[Int](n)
    val leafCnt2 = Array.ofDim[Int](n)
    val isLeaf = Array.ofDim[Boolean](n)
    REP_r(n) { i =>
      val v = q(i)
      if (leafCnt(v) == 0) {
        leafCnt(v) = 1
        leafCnt2(v) = 1
        isLeaf(v) = true
      }
      if (v != 0) leafCnt(p(v)) += leafCnt(v)
      if (!isLeaf(v)) {
        var cnt = 0
        var ms = 1e9.toInt
        REP(g(v).length) { j =>
          val u = g(v)(j)
          if (u != p(v)) {
            cnt += leafCnt2(u)
            ms = min(ms, leafCnt2(u))
          }
        }
        leafCnt2(v) = if (f(v) == 0) cnt else ms
      }
    }
    debug(leafCnt)
    debug(leafCnt2)
    val allmax = Array.ofDim[Boolean](n) // このノードからルートまでが全部max
    REP(n) { i =>
      val v = q(i)
      allmax(v) = (v == 0 || allmax(p(v))) && f(v) == 1
    }
    debug(allmax)

    val dp = Array.fill[Int](n)(1)
    REP(n) { i =>
      val v = q(i)
      // 親までがmax
      if (v == 0 || allmax(p(v))) {
        // leafでない かつ min | leaf
        if (!isLeaf(v) && f(v) == 0 || isLeaf(v)) dp(v) = leafCnt(0) - leafCnt2(v) + 1
      }
    }

    debug(dp)

    out.println(dp.max)
  }
}

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

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

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

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

  def solve(): Unit = {
    val n = ni()
    val f = na(n)
    val from, to = Array.ofDim[Int](n - 1)
    REP(n - 1) { i =>
      val p = ni() - 1
      from(i) = i + 1
      to(i) = p
    }
    val g = packUGraph(n, from, to)
    val (_, p, q) = traceBfs(g)
    val leafCnt = Array.ofDim[Int](n)
    val isLeaf = Array.ofDim[Boolean](n)
    REP_r(n) { i =>
      val v = q(i)
      if (leafCnt(v) == 0) {
        leafCnt(v) = 1
        isLeaf(v) = true
      }
      if (v != 0) leafCnt(p(v)) += leafCnt(v)
    }
    debug(leafCnt)
    val allmax = Array.ofDim[Boolean](n) // このノードからルートまでが全部max
    REP(n) { i =>
      val v = q(i)
      allmax(v) = (v == 0 || allmax(p(v))) && f(v) == 1
    }
    debug(allmax)

    var ans = 0
    REP(n) { i =>
      val v = q(i)
      // 親までがmaxで、自身がmin
      if ((v == 0 || allmax(p(v))) && f(v) == 0) {
        ans = max(ans, leafCnt(0) - leafCnt(v) + 1)
      }

      // leafまでmaxでつながっている
      if (isLeaf(v) && allmax(p(v))) {
        ans = leafCnt(0)
      }
    }
    out.println(ans)
  }
}

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._

  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

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

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

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

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

  def solve(): Unit = {
    val n = ni()
    val f = na(n)
    val from, to = Array.ofDim[Int](n - 1)
    REP(n - 1) { i =>
      val p = ni() - 1
      from(i) = i + 1
      to(i) = p
    }
    val g = packUGraph(n, from, to)
    val (_, p, q) = traceBfs(g)
    val leafCnt = Array.ofDim[Int](n)
    val isLeaf = Array.ofDim[Boolean](n)
    REP_r(n) { i =>
      val v = q(i)
      if (leafCnt(v) == 0) {
        leafCnt(v) = 1
        isLeaf(v) = true
      }
      if (v != 0) leafCnt(p(v)) += leafCnt(v)
    }
    debug(leafCnt)
    val allmax = Array.ofDim[Boolean](n) // このノードからルートまでが全部max
    REP(n) { i =>
      val v = q(i)
      allmax(v) = (v == 0 || allmax(p(v))) && f(v) == 1
    }
    debug(allmax)

    val dp = Array.fill[Int](n)(1)
    REP(n) { i =>
      val v = q(i)
      // 親までがmax
      if (v == 0 || allmax(p(v))) {
        // leafでない かつ min | leaf
        if (!isLeaf(v) && f(v) == 0 || isLeaf(v)) dp(v) = leafCnt(0) - leafCnt(v) + 1
      }
    }

    debug(dp)

    out.println(dp.max)
  }
}


There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs. Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.

The first line contains one integer number n (2 ≤ n ≤ 2·105). The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct.

Print two integer numbers — the minimal distance and the quantity of pairs with this distance.

NoteIn the first example the distance between the first city and the fourth city is |4 - 6| = 2, and it is the only pair with this distance.

import io.StdIn.readLine

object A extends App {
  readLine()
  val cities = readLine().split("\\s+").map(_.toInt).sorted
  val (minDist, count) = cities.zip(cities.tail).map { case (a, b) ⇒ b - a }.foldLeft((Int.MaxValue, 0)) {
    case ((mdist, _), dist) if dist < mdist ⇒ (dist, 1)
    case ((mdist, count), dist) if dist == mdist ⇒ (dist, count + 1)
    case (prev, _) ⇒ prev
  }
  println(s"$minDist $count")
}

object Main extends App {
  scala.io.StdIn.readInt()
  val arr = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
  val d = arr.zip(arr.tail).map(t => Math.abs(t._2 - t._1))
  val min = d.min
  println(min + " " + d.count(_ == min))
}

object Main extends App {
  scala.io.StdIn.readInt()
  val arr = scala.io.StdIn.readLine().split(" ").map(_.toInt)
  val d = arr.zip(arr.tail).map(t => Math.abs(t._2 - t._1))
  println(d.min + " " + d.count(_ == d.min))
}


Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points.Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy — as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points.The sweepstake has the following prizes (the prizes are sorted by increasing of their cost):   a mug (costs a points),  a towel (costs b points),  a bag (costs c points),  a bicycle (costs d points),  a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed.

The first line contains a single integer n (1 ≤ n ≤ 50) — the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ 109). The third line contains 5 integers a, b, c, d, e (1 ≤ a < b < c < d < e ≤ 109) — the prizes' costs.

Print on the first line 5 integers, separated by a space — the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer — the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next()
  val data = in.next().split(' ').map(_.toInt)
  val prices = in.next().split(' ').map(_.toInt)
  val count = Array.ofDim[Long](5)

  val l = data.foldLeft(0l) {
    case(balance, ball) =>
      var left = ball + balance
      (4 to 0 by -1).foreach {
        i => count(i) += left / prices(i)
          left %= prices(i)
      }
      left
  }

  println(count.mkString(" "))
  print(l)

}

import BigInt._
object Main {
  def main(args: Array[String]) {
  def readArray = readLine.split(' ').map(x => BigInt(x.toInt))
  val n = readInt
  val a = readArray.toList
  val p = readArray
  var acc:Array[BigInt] = Array(0,0,0,0,0)

  def solve(a: List[BigInt], money: BigInt): BigInt = {
    if (a == List()) {
      println(acc.mkString(" "))
      return money
    }
    var m = money + a.head
    for (i <- 4 to 0 by -1) {
      val k = BigInt((m / p(i)).toInt)
      acc(i) += k
      m -= k * p(i)
    }
    solve(a.tail, m)
  }

  val answer = solve(a, 0)
  println(answer)
  }
}

import scala.collection.mutable
object Main {
  def main(args: Array[String]) {
  def readArray = readLine.split(' ').map(x => BigInt(x))
  val n = readInt
  val a = readArray.toList
  val p = readArray
  var acc = mutable.ArrayBuffer[BigInt](0,0,0,0,0)

  def solve(a: List[BigInt], money: BigInt): BigInt = {
    if (a == List()) {
      println(acc.mkString(" "))
      return money
    }
    var m = money + a.head
    for (i <- 4 to 0 by -1) {
      val k = BigInt((m / p(i)).toInt)
      acc(i) += k
      m -= k * p(i)
    }
    solve(a.tail, m)
  }

  val answer = solve(a, 0)
  println(answer)
  }
}

import io.Source
import java.util.StringTokenizer

/**
 * User: eireksten
 * Date: 7/28/12
 * Time: 10:20 AM
 */

object Runner extends App {

  val input = Source.fromInputStream(System.in).bufferedReader()
  var token: StringTokenizer = null

  def TOKEN() = {
    while (token == null || !token.hasMoreTokens)
      token = new StringTokenizer(input.readLine())
    token.nextToken()
  }

  def LONG() = TOKEN().toLong
  def INT() = TOKEN().toInt

  val n = INT()
  val wrappings = for (i <- 1 to n) yield LONG()
  val prizeCosts = for (i <- 1 to 5) yield LONG()

  new Solution().go(wrappings, prizeCosts)

}

class Solution {

  def go(wrappings : IndexedSeq[Long], prizeCosts : IndexedSeq[Long]) = {

    var sum = 0L
    val prizes = new Array[Long](5)
    for(wrap <- wrappings) {
      sum += wrap
      for (i <- prizeCosts.length-1 to 0 by -1) {
        val count = sum / prizeCosts(i);
        prizes(i) += count
        sum -= count * prizeCosts(i);
      }
    }
    println(prizes.mkString(" "))
    println(sum)
  }

}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val ls = readLine().split(" ").map(_.toLong)
    val prices = readLine().split(" ").map(_.toLong).zipWithIndex
    var count = Array.fill(5)(0L)
    var sum = 0L
    ls.foreach { e =>
      sum += e
      while(prices.count(_._1 <= sum) != 0) {
        val t = prices.filter(_._1 <= sum).last
        val div = (sum / t._1)
        sum -= div * t._1
        count(t._2) += div
      }
    }
    println(count.mkString(" "))
    println(sum)
  }
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val n = in.next()
  val data = in.next().split(' ').map(_.toInt)
  val prices = in.next().split(' ').map(_.toInt)
  val count = Array.ofDim[Int](5)

  val l = data.foldLeft(0) {
    case(balance, ball) =>
      var left = ball + balance
      (4 to 0 by -1).foreach {
        i => count(i) += left / prices(i)
          left %= prices(i)
      }
      left
  }

  println(count.mkString(" "))
  print(l)

}

object Main {
  def main(args: Array[String]) {
  def readArray = readLine.split(' ').map(x => x.toLong)
  val n = readInt
  val a = readArray.toList
  val p = readArray
  var acc = Array(0,0,0,0,0)

  def solve(a: List[Long], money: Long): Long = {
    if (a == List()) {
      println(acc.mkString(" "))
      return money
    }
    var m = money + a.head
    for (i <- 4 to 0 by -1) {
      val k = m / p(i)
      acc(i) += k.toInt
      m -= k * p(i)
    }
    solve(a.tail, m)
  }

  val answer = solve(a, 0)
  println(answer)
  }
}

object Main {
  def main(args: Array[String]) {
  val n = readInt
  val a = readLine.split(' ').map(x => x.toInt).toList
  val p = readLine.split(' ').map(x => x.toInt).reverse
  var acc = Array(0,0,0,0,0)
  def solve(a: List[Int], money: Int): Int = {
    if (a == List()) {
      println(acc.reverse.mkString(" "))
      return money
    }
    var m = money + a.head
    for (i <- 0 to 4) {
      val k = m / p(i)
      acc(i) += k
      m -= k * p(i)
    }
    solve(a.tail, m)
  }
  val answer = solve(a, 0)
  println(answer)
  }
}

import io.Source
import java.util.StringTokenizer

/**
 * User: eireksten
 * Date: 7/28/12
 * Time: 10:20 AM
 */

object Runner extends App {

  val input = Source.fromInputStream(System.in).bufferedReader()
  var token: StringTokenizer = null

  def TOKEN() = {
    while (token == null || !token.hasMoreTokens)
      token = new StringTokenizer(input.readLine())
    token.nextToken()
  }

  def INT() = TOKEN().toInt

  val n = INT()
  val wrappings = for (i <- 1 to n) yield INT()
  val prizeCosts = for (i <- 1 to 5) yield INT()

  new Solution().go(wrappings, prizeCosts)

}

class Solution {

  def go(wrappings : IndexedSeq[Int], prizeCosts : IndexedSeq[Int]) = {

    var sum = 0
    val prizes = new Array[Int](5)
    for(wrap <- wrappings) {
      sum += wrap
      val prize = findPrize(sum, prizeCosts)
      if (prize >= 0) {
        prizes(prize) += 1
        sum -= prizeCosts(prize);
      }
    }
    println(prizes.mkString(" "))
    println(sum)
  }

  def findPrize(sum: Int, prizeCosts : IndexedSeq[Int]) = {
    var best = -1
    for(i <- 0 until prizeCosts.length) {
      if(sum >= prizeCosts(i) && (best == -1 || prizeCosts(i) > prizeCosts(best)))
        best = i
    }
    best
  }

}


NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles:  It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar picture himself.He managed to calculate the number of outer circles $$$n$$$ and the radius of the inner circle $$$r$$$. NN thinks that, using this information, you can exactly determine the radius of the outer circles $$$R$$$ so that the inner circle touches all of the outer ones externally and each pair of neighboring outer circles also touches each other. While NN tried very hard to guess the required radius, he didn't manage to do that. Help NN find the required radius for building the required picture.

The first and the only line of the input file contains two numbers $$$n$$$ and $$$r$$$ ($$$3 \leq n \leq 100$$$, $$$1 \leq r \leq 100$$$) — the number of the outer circles and the radius of the inner circle respectively.

Output a single number $$$R$$$ — the radius of the outer circle required for building the required picture.  Your answer will be accepted if its relative or absolute error does not exceed $$$10^{-6}$$$. Formally, if your answer is $$$a$$$ and the jury's answer is $$$b$$$. Your answer is accepted if and only when $$$\frac{|a-b|}{max(1, |b|)} \le 10^{-6}$$$.

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, r = ni()
    val S = math.sin(Math.PI / n)
    val r2 = r * S / (1 - S)
    out.println(f"$r2%.7f")
  }

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

import scala.io.StdIn

object Codeforces1100C {

  def getOuterCircleRadius(n: Int, r: Double): Double = {
    val totalAngle = 2 * math.Pi
    val eachAngle = totalAngle / n
    val cosAngle = math.cos(eachAngle)
    val k = 2 / (1 - cosAngle)

    val a = 1 - k
    val b = 2 * r
    val c = r * r

    val d = b * b - 4 * a * c

    val x1 = (-b + math.sqrt(d)) / (2 * a)
    val x2 = (-b - math.sqrt(d)) / (2 * a)

    math.max(x1, x2)
  }

  def main(args: Array[String]): Unit = {
    val Array(n, r) = StdIn.readLine().trim.split(" ")
    val R = getOuterCircleRadius(n.toInt, r.toDouble)
    println(R)
  }
}


The Little Elephant loves to play with color cards.He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks that a set of cards on the table is funny if at least half of the cards have the same color (for each card the color of the upper side is considered).Help the Little Elephant to find the minimum number of moves needed to make the set of n cards funny.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of the cards. The following n lines contain the description of all cards, one card per line. The cards are described by a pair of positive integers not exceeding 109 — colors of both sides. The first number in a line is the color of the front of the card, the second one — of the back. The color of the front of the card may coincide with the color of the back of the card. The numbers in the lines are separated by single spaces.

On a single line print a single integer — the sought minimum number of moves. If it is impossible to make the set funny, print -1.

NoteIn the first sample there initially are three cards lying with colors 4, 4, 7. Since two of the three cards are of the same color 4, you do not need to change anything, so the answer is 0.In the second sample, you can turn the first and the fourth cards. After that three of the five cards will be of color 7.

object Main extends App {
  import scala.collection.mutable
  import scala.io.{Source, StdIn}
  override def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val mapHeads = mutable.Map[Int, Int]()
    val mapTails = mutable.Map[Int, Int]()
    for (_ <- 1 to n) {
      val str = StdIn.readLine().split(" ").map(_.toInt)
      val (a, b) = str.head -> str.last
      mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)
      if(a!=b)mapTails.put(b, mapTails.getOrElse(b, 0) + 1)
    }
    var minRes = n
    var flag = false
    for ((num, count) <- mapHeads) {
      val numTails = mapTails.getOrElse(num, 0)
      if (count + numTails >= (n + 1) / 2) {
        minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)
        flag = true
      }
    }
    for ((num, count) <- mapTails) {
      val numHeads = mapHeads.getOrElse(num, 0)
      if (count + numHeads >= (n + 1) / 2) {
        minRes = Math.max(Math.min(minRes, (n+1)/2 - numHeads), 0)
        flag = true
      }
    }
    println(if(flag) minRes else -1)
  }
}

object Main extends App {
  import scala.collection.mutable
  import scala.io.{Source, StdIn}
  override def main(args: Array[String]): Unit = {
    //WebSocketRunner.runClient(s"http://$url/codenjoy-contest/board/player/$secret?code=$code", new MySolver, new MyBoard)
    val n = StdIn.readInt()
    val mapHeads = mutable.Map[Int, Int]()
    val mapTails = mutable.Map[Int, Int]()
    for (_ <- 1 to n) {
      val str = StdIn.readLine().split(" ").map(_.toInt)
      val (a, b) = str.head -> str.last
      mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)
      mapTails.put(b, mapTails.getOrElse(b, 0) + 1)
    }
    var minRes = n
    var flag = false
    for ((num, count) <- mapHeads) {
      val numTails = mapTails.getOrElse(num, 0)
      if (num + numTails >= (n + 1) / 2) {
        minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)
        flag = true
      }
    }
    println(if(flag) minRes else -1)
  }
}

object Main extends App {
  import scala.collection.mutable
  import scala.io.{Source, StdIn}
  override def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val mapHeads = mutable.Map[Int, Int]()
    val mapTails = mutable.Map[Int, Int]()
    for (_ <- 1 to n) {
      val str = StdIn.readLine().split(" ").map(_.toInt)
      val (a, b) = str.head -> str.last
      mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)
      mapTails.put(b, mapTails.getOrElse(b, 0) + 1)
    }
    var minRes = n
    var flag = false
    for ((num, count) <- mapHeads) {
      val numTails = mapTails.getOrElse(num, 0)
      if (count + numTails >= (n + 1) / 2) {
        minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)
        flag = true
      }
    }
    for ((num, count) <- mapTails) {
      val numHeads = mapHeads.getOrElse(num, 0)
      if (count + numHeads >= (n + 1) / 2) {
        minRes = Math.max(Math.min(minRes, (n+1)/2 - numHeads), 0)
        flag = true
      }
    }
    println(if(flag) minRes else -1)
  }
}

object Main extends App {
  import scala.collection.mutable
  import scala.io.{Source, StdIn}
  override def main(args: Array[String]): Unit = {
    //WebSocketRunner.runClient(s"http://$url/codenjoy-contest/board/player/$secret?code=$code", new MySolver, new MyBoard)
    val n = StdIn.readInt()
    val mapHeads = mutable.Map[Int, Int]()
    val mapTails = mutable.Map[Int, Int]()
    for (_ <- 1 to n) {
      val str = StdIn.readLine().split(" ").map(_.toInt)
      val (a, b) = str.head -> str.last
      mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)
      mapTails.put(b, mapTails.getOrElse(b, 0) + 1)
    }
    var minRes = n
    var flag = false
    for ((num, count) <- mapHeads) {
      val numTails = mapTails.getOrElse(num, 0)
      if (count + numTails >= (n + 1) / 2) {
        minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)
        flag = true
      }
    }
    for ((num, count) <- mapTails) {
      val numHeads = mapHeads.getOrElse(num, 0)
      if (count + numHeads >= (n + 1) / 2) {
        minRes = Math.max(Math.min(minRes, (n+1)/2 - count), 0)
        flag = true
      }
    }
    println(if(flag) minRes else -1)
  }
}

object Main extends App {
    import scala.collection.mutable
    import scala.io.{Source, StdIn}
    override def main(args: Array[String]): Unit = {
    //WebSocketRunner.runClient(s"http://$url/codenjoy-contest/board/player/$secret?code=$code", new MySolver, new MyBoard)
    val n = StdIn.readInt()
    val mapHeads = mutable.Map[Int, Int]()
    val mapTails = mutable.Map[Int, Int]()
    for (_ <- 1 to n) {
      val str = StdIn.readLine().split(" ").map(_.toInt)
      val (a, b) = str.head -> str.last
      mapHeads.put(a, mapHeads.getOrElse(a, 0) + 1)
      mapTails.put(b, mapTails.getOrElse(b, 0) + 1)
    }
    var minRes = n
    var flag = false
    for ((num, count) <- mapHeads) {
      val numTails = mapTails.getOrElse(num, 0)
      if (num + numTails >= (n + 1) / 2) {
        minRes = Math.min(minRes, (n+1)/2 - count)
        flag = true
      }
    }
    println(if(flag) minRes else -1)
  }
}


Once upon a time, when the world was more beautiful, the sun shone brighter, the grass was greener and the sausages tasted better Arlandia was the most powerful country. And its capital was the place where our hero DravDe worked. He couldn’t program or make up problems (in fact, few people saw a computer those days) but he was nevertheless happy. He worked in a warehouse where a magical but non-alcoholic drink Ogudar-Olok was kept. We won’t describe his work in detail and take a better look at a simplified version of the warehouse.The warehouse has one set of shelving. It has n shelves, each of which is divided into m sections. The shelves are numbered from top to bottom starting from 1 and the sections of each shelf are numbered from left to right also starting from 1. Each section can contain exactly one box of the drink, and try as he might, DravDe can never put a box in a section that already has one. In the course of his work DravDe frequently notices that he has to put a box in a filled section. In that case his solution is simple. DravDe ignores that section and looks at the next one to the right. If it is empty, he puts the box there. Otherwise he keeps looking for the first empty section to the right. If no empty section is found by the end of the shelf, he looks at the shelf which is under it, then the next one, etc. Also each time he looks at a new shelf he starts from the shelf’s beginning. If DravDe still can’t find an empty section for the box, he immediately drinks it all up and throws the empty bottles away not to be caught.After one great party with a lot of Ogudar-Olok drunk DravDe asked you to help him. Unlike him, you can program and therefore modeling the process of counting the boxes in the warehouse will be easy work for you.The process of counting contains two types of query messages:   «+1 x y id» (where x, y are integers, 1 ≤ x ≤ n, 1 ≤ y ≤ m, and id is a string of lower case Latin letters — from 1 to 10 characters long). That query means that the warehouse got a box identified as id, which should be put in the section y on the shelf x. If the section is full, use the rules described above. It is guaranteed that every moment of the process the identifiers of all the boxes in the warehouse are different. You don’t have to answer this query.  «-1 id» (where id is a string of lower case Latin letters — from 1 to 10 characters long). That query means that a box identified as id is removed from the warehouse. You have to answer this query (see output format).

The first input line contains integers n, m and k (1 ≤ n, m ≤ 30, 1 ≤ k ≤ 2000) — the height, the width of shelving and the amount of the operations in the warehouse that you need to analyze. In the following k lines the queries are given in the order of appearance in the format described above.

For each query of the «-1 id» type output two numbers in a separate line — index of the shelf and index of the section where the box with this identifier lay. If there was no such box in the warehouse when the query was made, output «-1 -1» without quotes.

2 2 9
+1 1 1 cola
+1 1 1 fanta
+1 1 1 sevenup
+1 1 1 whitekey
-1 cola
-1 fanta
-1 sevenup
-1 whitekey
-1 cola

2 2 8
+1 1 1 cola
-1 cola
+1 1 1 fanta
-1 fanta
+1 1 1 sevenup
-1 sevenup
+1 1 1 whitekey
-1 whitekey

import scala.io._
import scala.collection.mutable._
import java.io.FileWriter
import java.io.PrintWriter

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var reader = Source.fromFile("input.txt").bufferedReader();
    var writer = new PrintWriter(new FileWriter("output.txt"));
    var Array(n, m, k) = reader.readLine().split(" ").toArray.map(_.toInt);
    var a = Array.fill(n, m)("");
    var list = List[String]();
    for (i <- 0 until k) {
      var l = reader.readLine.split(" ");
      var pref = l(0);
      if (pref == "+1") {
	      var x = l(1).toInt - 1;
	      var y = l(2).toInt - 1;
	      var id = l(3);
	      if (a(x)(y) == "") {
		    a(x)(y) = id;
	      } else {
	        var done = false;
	        for (j <- x until n) {
		        for (d <- 0 until m) {
		          if (!done && ((j == x && d > y) || (j > x)) && a(j)(d) == "") {
		            a(j)(d) = id;
		            done = true;
		          }
		        }
		    }
	      }
	      println(a.deep.mkString("\n"));
	      println
      } else {
        var id = l(1);
        println(a.deep.mkString("\n"));
        println
        var x = a.indexWhere(p => p.contains(id));
        if (x == -1) {
          writer.println("-1 -1");
        } else {
          var y = a(x).indexWhere(p => p.equals(id));
          a(x)(y) = "";
          writer.println((x + 1) + " " + (y + 1));
        }
      }
    }
    writer.close();
  }
}


Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 — to a2 billion, ..., and in the current (2000 + n)-th year — an billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year — 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers ai can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers ai from the sequence and leave only some subsequence that has perfect growth.Thus Petya has to choose a sequence of years y1, y2, ..., yk,so that in the year y1 the company income amounted to 1 billion bourles, in the year y2 — 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence.

The first line contains an integer n (1 ≤ n ≤ 100). The next line contains n integers ai ( - 100 ≤ ai ≤ 100). The number ai determines the income of BerSoft company in the (2000 + i)-th year. The numbers in the line are separated by spaces.

Output k — the maximum possible length of a perfect sequence. In the next line output the sequence of years y1, y2, ..., yk. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0.

object P039B extends App {
  val n = readInt
  val a = readLine.split(' ').map(_.toInt)
  var curr = 0
  var resultBuilder = new collection.mutable.ArrayBuilder.ofInt()
  for (i <- 0 to n-1) {
    if (a(i) == curr + 1) {
      resultBuilder += 2001 + i
      curr += 1
    }
  }
  if (curr == 0) {
    println(0)
  }
  else {
    val result = resultBuilder.result()
    println(result size)
    println(result.deep.mkString(" "))
  }
}


Let $$$n$$$ be an integer. Consider all permutations on integers $$$1$$$ to $$$n$$$ in lexicographic order, and concatenate them into one big sequence $$$p$$$. For example, if $$$n = 3$$$, then $$$p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]$$$. The length of this sequence will be $$$n \cdot n!$$$.Let $$$1 \leq i \leq j \leq n \cdot n!$$$ be a pair of indices. We call the sequence $$$(p_i, p_{i+1}, \dots, p_{j-1}, p_j)$$$ a subarray of $$$p$$$. Its length is defined as the number of its elements, i.e., $$$j - i + 1$$$. Its sum is the sum of all its elements, i.e., $$$\sum_{k=i}^j p_k$$$. You are given $$$n$$$. Find the number of subarrays of $$$p$$$ of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$. Since this number may be large, output it modulo $$$998244353$$$ (a prime number).

The only line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$), as described in the problem statement.

Output a single integer — the number of subarrays of length $$$n$$$ having sum $$$\frac{n(n+1)}{2}$$$, modulo $$$998244353$$$.

object D extends App {

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

  val Array(n) = readInts(1)
  val MOD = 998244353L

  var prev = 1L
  var fac = 1L
  for (i <- 1 to n) {
    fac = (fac * i) % MOD
    prev = (fac + (MOD + prev - 1L) * i) % MOD
  }

  println(prev)
}

object Main extends App {
  val MOD: Int = 998244353
  val n: Int = scala.io.StdIn.readInt()
  def solve: Long = {
    def calc(k: Int = n, pr: Long = 1, acc: Long = 0): Long = {
      if (k == 1) (acc + n * pr) % MOD
      else {
        val npr = (pr * k) % MOD
        calc(k - 1, npr, (acc - npr + MOD) % MOD)
      }
    }
    calc()
  }
  println(solve)
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import scala.annotation.tailrec

object Main extends App {
  val MOD: Int = 998244353
  val st = new StringTokenizer(new BufferedReader(new InputStreamReader(System.in)).readLine())
  val n: Int = Integer.parseInt(st.nextToken())
  def solve: Long = {
    @tailrec
    def calc(k: Int = n, pr: Long = 1, acc: Long = 0): Long = {
      if (k == 1) (acc + n * pr) % MOD
      else {
        val npr = (pr * k) % MOD
        calc(k - 1, npr, (acc - npr + MOD) % MOD)
      }
    }
    calc()
  }
  System.out.print(solve)
}

import scala.annotation.tailrec

object Main extends App {
  val MOD: Int = 998244353
  val n: Int = scala.io.StdIn.readInt()
  def solve: Long = {
    @tailrec
    def calc(k: Int = n, pr: Long = 1, acc: Long = 0): Long = {
      if (k == 1) (acc + n * pr) % MOD
      else {
        val npr = (pr * k) % MOD
        calc(k - 1, npr, (acc - npr + MOD) % MOD)
      }
    }
    calc()
  }
  println(solve)
}


A tourist hiked along the mountain range. The hike lasted for n days, during each day the tourist noted height above the sea level. On the i-th day height was equal to some integer hi. The tourist pick smooth enough route for his hike, meaning that the between any two consecutive days height changes by at most 1, i.e. for all i's from 1 to n - 1 the inequality |hi - hi + 1| ≤ 1 holds.At the end of the route the tourist rafted down a mountain river and some notes in the journal were washed away. Moreover, the numbers in the notes could have been distorted. Now the tourist wonders what could be the maximum height during his hike. Help him restore the maximum possible value of the maximum height throughout the hike or determine that the notes were so much distorted that they do not represent any possible height values that meet limits |hi - hi + 1| ≤ 1.

The first line contains two space-separated numbers, n and m (1 ≤ n ≤ 108, 1 ≤ m ≤ 105) — the number of days of the hike and the number of notes left in the journal. Next m lines contain two space-separated integers di and hdi (1 ≤ di ≤ n, 0 ≤ hdi ≤ 108) — the number of the day when the i-th note was made and height on the di-th day. It is guaranteed that the notes are given in the chronological order, i.e. for all i from 1 to m - 1 the following condition holds: di < di + 1.

If the notes aren't contradictory, print a single integer — the maximum possible height value throughout the whole route. If the notes do not correspond to any set of heights, print a single word 'IMPOSSIBLE' (without the quotes).

NoteFor the first sample, an example of a correct height sequence with a maximum of 2: (0, 0, 1, 2, 1, 1, 0, 1).In the second sample the inequality between h7 and h8 does not hold, thus the information is inconsistent.

import scala.collection._

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(n, m) = readInts(2)
  val ds, hs = Array.ofDim[Int](m)

  for (i <- 0 until m) {
    val Array(d, h) = readInts(2)
    ds(i) = d
    hs(i) = h
  }

  var maxH = (hs.head + ds.head - 1) max (hs.last + (n - ds.last))

  for (i <- 1 until m) {
    val dd = ds(i) - ds(i - 1)
    val dh = hs(i) - hs(i - 1)
    if (dd < math.abs(dh)) {
      println("IMPOSSIBLE")
      System.exit(0)
    }
    val ch = (hs(i) max hs(i - 1)) + (dd - math.abs(dh)) / 2
    if (ch > maxH) maxH = ch
  }

  println(maxH)
}

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

import scala.collection.mutable

object C {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val records = new Array[(Int, Int)](m)
    for (i <- 0 until m ){
      records(i) = (nextInt, nextInt)
    }
    var max = records(0)._2 + records(0)._1 - 1
    for (i <- 1 until m) {
      val diff = records(i)._1 - records(i - 1)._1
      val hDiff = records(i)._2 - records(i - 1)._2
      max = Math.max(records(i)._2, max)
      if (Math.abs(hDiff) > diff) {
        out.println("IMPOSSIBLE")
        return 1
      }
      val x = (diff - hDiff) / 2
      max = Math.max(records(i)._2 + x, max)
    }
    max = Math.max(records(m - 1)._2 + n - records(m - 1)._1, max)
    out.println(max)
    return 0
  }
}

/**
 * Created by slie742 on 9/09/2015.
 */

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

import Math.abs
import Math.max
import Math.min

object TouristNotes {

  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def solve(notes: List[(Int,Int)]) : Option[Int] = {
    def go(prev: (Int,Int), remNotes: List[(Int,Int)],maxHeight: Int) : Option[Int] = remNotes match {
      case Nil => Some(maxHeight)
      case (d,h) :: rest if abs(h-prev._2) > d - prev._1 =>
        None
      case (d,h) :: rest =>
        //println(s"current = ($d,$h), maxHeight=$maxHeight, between=${(abs(h-prev._2)+ (d - prev._1))/2}")
        val newMax = max(maxHeight, min(h,prev._2) + (abs(h-prev._2)+ (d - prev._1))/2)
        go ( (d,h), rest, newMax)
    }
    go(notes.head, notes.tail, notes.head._2+notes.head._1 - 1)
  }

  def main(args: Array[String]) {
    val (n,m) = readTuple()
    val notes = for {
      i <- 1 to m
      (d,h) = readTuple()
    } yield (d,h)
    solve(notes.toList) match {
      case None => println("IMPOSSIBLE")
      case Some(h) => println(max(h, notes.last._2 + (n-notes.last._1) ))
    }
  }

}

/**
 * Created by slie742 on 9/09/2015.
 */

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

import Math.abs
import Math.max

object TouristNotes {

  def readInts() : Array[Int] =
    readLine.split(' ').map(_.toInt)

  def readLongs() : Array[Long] =
    readLine.split(' ').map(_.toLong)

  def readTuple() : (Int,Int) = {
    val line = readInts
    (line(0),line(1))
  }
  def readTupleLong() : (Long,Long) = {
    val line = readLongs
    (line(0),line(1))
  }

  def readTriple() : (Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2))
  }
  def readQuad() : (Int,Int,Int,Int) = {
    val line = readInts
    (line(0),line(1),line(2),line(3))
  }

  def solve(notes: List[(Int,Int)]) : Option[Int] = {
    def go(prev: (Int,Int), remNotes: List[(Int,Int)],maxHeight: Int) : Option[Int] = remNotes match {
      case Nil => Some(maxHeight)
      case (d,h) :: rest if abs(h-prev._2) > d - prev._1 =>
        None
      case (d,h) :: rest =>
        val newMax = max(maxHeight, (abs(h-prev._2)+ (d - prev._1))/2)
        go ( (d,h), rest, newMax)
    }
    go(notes.head, notes.tail, notes.head._2+notes.head._1 - 1)
  }

  def main(args: Array[String]) {
    val (n,m) = readTuple()
    val notes = for {
      i <- 1 to m
      (d,h) = readTuple()
    } yield (d,h)
    solve(notes.toList) match {
      case None => println("IMPOSSIBLE")
      case Some(h) => println(max(h, notes.last._2 + (n-notes.last._1) ))
    }
  }

}


Mad scientist Mike does not use slow hard disks. His modification of a hard drive has not one, but n different heads that can read data in parallel.When viewed from the side, Mike's hard drive is an endless array of tracks. The tracks of the array are numbered from left to right with integers, starting with 1. In the initial state the i-th reading head is above the track number hi. For each of the reading heads, the hard drive's firmware can move the head exactly one track to the right or to the left, or leave it on the current track. During the operation each head's movement does not affect the movement of the other heads: the heads can change their relative order; there can be multiple reading heads above any of the tracks. A track is considered read if at least one head has visited this track. In particular, all of the tracks numbered h1, h2, ..., hn have been read at the beginning of the operation.  Mike needs to read the data on m distinct tracks with numbers p1, p2, ..., pm. Determine the minimum time the hard drive firmware needs to move the heads and read all the given tracks. Note that an arbitrary number of other tracks can also be read.

The first line of the input contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of disk heads and the number of tracks to read, accordingly. The second line contains n distinct integers hi in ascending order (1 ≤ hi ≤ 1010, hi < hi + 1) — the initial positions of the heads. The third line contains m distinct integers pi in ascending order (1 ≤ pi ≤ 1010, pi < pi + 1) - the numbers of tracks to read. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams or the %I64d specifier.

Print a single number — the minimum time required, in seconds, to read all the needed tracks.

NoteThe first test coincides with the figure. In this case the given tracks can be read in 2 seconds in the following way:   during the first second move the 1-st head to the left and let it stay there;  move the second head to the left twice;  move the third head to the right twice (note that the 6-th track has already been read at the beginning). One cannot read the tracks in 1 second as the 3-rd head is at distance 2 from the 8-th track.

import scala.collection._

object E extends App {

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

  val Array(n, m) = readInts(2)
  val hs = readLongs(n)
  val ps = readLongs(m)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) >>> 1
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def can(steps: Long): Boolean = {
    var hi = 0
    var pi = 0
    var read = -1L
    while (pi < ps.length && hi < hs.length) {
      if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {
        read = math.max(math.max(hs(hi),
            hs(hi) + steps - 2 * (hs(hi) - ps(pi))),
            hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)
      } else if (ps(pi) > hs(hi) && ps(pi) <= hs(hi) + steps) {
        read = hs(hi) + steps
      }
      hi += 1
      while (pi < ps.length && ps(pi) <= read) pi += 1
    }

    pi == ps.length
  }

  println(binSearch(0, 100000000000L))
}

import scala.collection._

object E extends App {

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

  val Array(n, m) = readInts(2)
  val hs = readLongs(n)
  val ps = readLongs(m)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) hi + 1
    else {
      val mid = (low + hi) >>> 1
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def can(steps: Long): Boolean = {
    var hi = 0
    var pi = 0
    var read = -1L
    while (pi < ps.length && hi < hs.length) {
      if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {
        read = math.max(math.max(hs(hi), hs(hi) + steps - 2 * (hs(hi) - ps(pi))), hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)
      } else if (ps(pi) > hs(hi) && ps(pi) <= hs(hi) + steps) {
        read = hs(hi) + steps
      }
      hi += 1
      while (pi < ps.length && ps(pi) <= read) pi += 1
    }

    pi == ps.length
  }

  println(binSearch(0, 10000000001L))
}

import scala.collection._

object E extends App {

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

  val Array(n, m) = readInts(2)
  val hs = readLongs(n)
  val ps = readLongs(m)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) hi + 1
    else {
      val mid = (low + hi) >>> 1
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def can(steps: Long): Boolean = {
    var hi = 0
    var pi = 0
    var read = -1L
    while (pi < ps.length && hi < hs.length) {
      if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {
        read = math.max(hs(hi), hs(hi) + steps - 2 * (hs(hi) - ps(pi)))
      } else if (ps(pi) <= hs(hi) + steps) {
        read = hs(hi) + steps
      }
      hi += 1
      while (pi < ps.length && ps(pi) <= read) pi += 1
    }

    pi == ps.length
  }

  println(binSearch(0, 10000000001L))
}

import scala.collection._

object E extends App {

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

  val Array(n, m) = readInts(2)
  val hs = readLongs(n)
  val ps = readLongs(m)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) low
    else {
      val mid = (low + hi) >>> 1
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def can(steps: Long): Boolean = {
    var hi = 0
    var pi = 0
    var read = -1L
    while (pi < ps.length && hi < hs.length) {
      if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {
        read = math.max(math.max(hs(hi),
            hs(hi) + steps - 2 * (hs(hi) - ps(pi))),
            hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)
      } else if (ps(pi) > hs(hi) && ps(pi) <= hs(hi) + steps) {
        read = hs(hi) + steps
      }
      hi += 1
      while (pi < ps.length && ps(pi) <= read) pi += 1
    }

    pi == ps.length
  }

  println(binSearch(0, 10000000001L))
}

import scala.collection._

object E extends App {

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

  val Array(n, m) = readInts(2)
  val hs = readLongs(n)
  val ps = readLongs(m)

  @annotation.tailrec
  def binSearch(low: Long, hi: Long): Long = {
    if (hi < low) hi + 1
    else {
      val mid = (low + hi) >>> 1
      if (can(mid)) binSearch(low, mid - 1)
      else binSearch(mid + 1, hi)
    }
  }

  def can(steps: Long): Boolean = {
    var hi = 0
    var pi = 0
    var read = -1L
    while (pi < ps.length && hi < hs.length) {
      if (ps(pi) <= hs(hi) && ps(pi) >= hs(hi) - steps) {
        read = math.max(math.max(hs(hi), hs(hi) + steps - 2 * (hs(hi) - ps(pi))), hs(hi) + (steps - (hs(hi) - ps(pi))) / 2)
      } else if (ps(pi) <= hs(hi) + steps) {
        read = hs(hi) + steps
      }
      hi += 1
      while (pi < ps.length && ps(pi) <= read) pi += 1
    }

    pi == ps.length
  }

  println(binSearch(0, 10000000001L))
}


Theofanis really likes sequences of positive integers, thus his teacher (Yeltsa Kcir) gave him a problem about a sequence that consists of only special numbers.Let's call a positive number special if it can be written as a sum of different non-negative powers of $$$n$$$. For example, for $$$n = 4$$$ number $$$17$$$ is special, because it can be written as $$$4^0 + 4^2 = 1 + 16 = 17$$$, but $$$9$$$ is not.Theofanis asks you to help him find the $$$k$$$-th special number if they are sorted in increasing order. Since this number may be too large, output it modulo $$$10^9+7$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^9$$$; $$$1 \le k \le 10^9$$$).

For each test case, print one integer — the $$$k$$$-th special number in increasing order modulo $$$10^9+7$$$.

object B extends App {

  lazy val Mod = (1e9 + 7).toLong

  def kthSpecialNumber(n: Int, k: Int): Long =
    (0 to 31)
      .foldLeft((0L, 1L)) {
        case ((result, power), i) if (1 & (k >> i)) == 1 => ((result + power) % Mod, (n * power) % Mod)
        case ((result, power), _)                        => (result, (n * power) % Mod)
      }
      ._1

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextInt()
    val k = nextInt()

    out.println(kthSpecialNumber(n, k))
  }

  out.flush()

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

}

object B extends App {

  lazy val Mod = (1e9 + 7).toLong

  def log2(n: Int): Int = 31 - Integer.numberOfLeadingZeros(n)

  def specialNumbers(n: Int, k: Int): Long = {

    val powers: Array[Long] = {
      val size = log2(k) + 1
      val data = Array.fill(size)(1L)
      (1 until size).foreach { i => data(i) = (n * data(i - 1)) % Mod }
      data
    }

    @annotation.tailrec
    def go(k: Int, result: Long): Long = k match {
      case 0 => result
      case k =>
        val l = log2(k)
        val i = k - (1 << l)

        go(i, (result + powers(l)) % Mod)
    }

    go(k, 0L)
  }

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n = nextInt()
    val k = nextInt()

    out.println(specialNumbers(n, k))
  }

  out.flush()

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

}

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

object sample 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 myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readLong()
        var k = readInt()
        var sum = 0L
        var pow = 1L
        while (k > 0) {
            if (k % 2 == 1) {
                sum += pow
                sum %= rem
            }
            pow *= n
            pow %= rem
            k /= 2
        }
        writer.println(sum)
    }
    writer.flush()
}