A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence (or, shortly, an RBS) is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example:  bracket sequences "()()" and "(())" are regular (the resulting expressions are: "(1)+(1)" and "((1+1)+1)");  bracket sequences ")(", "(" and ")" are not. There was an RBS. Some brackets have been replaced with question marks. Is it true that there is a unique way to replace question marks with brackets, so that the resulting sequence is an RBS?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of testcases. The only line of each testcase contains an RBS with some brackets replaced with question marks. Each character is either '(', ')' or '?'. At least one RBS can be recovered from the given sequence. The total length of the sequences over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print "YES" if the way to replace question marks with brackets, so that the resulting sequence is an RBS, is unique. If there is more than one way, then print "NO".

NoteIn the first testcase, the only possible original RBS is "(())".In the second testcase, there are multiple ways to recover an RBS.In the third and the fourth testcases, the only possible original RBS is "()".In the fifth testcase, the original RBS can be either "((()()))" or "(())()()".

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val s = tokenizer.nextToken()
      var t = true
      var r: Long = 0
      var l: Long = 0
      val len: Long = s.length
      val nn: Long = len / 2
      for (i <- s) {
        if (i.toString == "(") {
          l+=1
        }
        else if (i.toString == ")") {
          r+=1
        }
      }
      var cou = 1
      var rs:Long = nn - r
      var ls:Long = nn-l
      if (rs * ls < 1) {
        cou = 0
      }
      var ri:Long = 0
      var le:Long = 0
      var c = 0
      var ttt = 1
      for (i <- s) {
        if (i.toString == "(") {
          c += 1
        }
        else if (i.toString == ")") {
          c -= 1
          if (c<0) {
            t = false
          }
        }
        else {
          if (ls > 1) {
            c += 1
            ls -=1
          }
          else if (( ls == 1) && (ttt == 1) && (rs > 0)) {
            rs-=1
            c -= 1
            ttt-=1
            if (c<0) {
              t = false
            }
          }
          else if (ls == 1){
            c += 1
            ls -=1
          }
          else {
            rs-=1
            c -= 1
            if (c<0) {
              t = false
            }
          }
        }
      }
      if (cou == 0) {
        t = false
      }
      if (t) {
        println("NO")
      }
      else println("YES")
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val s = tokenizer.nextToken()
      var t = true
      var r: Long = 0
      var l: Long = 0
      val len: Long = s.length
      val nn: Long = len / 2
      for (i <- s) {
        if (i.toString == "(") {
          l+=1
        }
        else if (i.toString == ")") {
          r+=1
        }
      }
      var rs:Long = nn - r
      var ls:Long = nn-l
      var ri:Long = 0
      var le:Long = 0
      for (i <- s) {
        if (i.toString == "(") {
          le+=1
        }
        else if (i.toString == ")") {
          ri+=1
        }
        else {
          if ((ri != le) && (rs > 0) && (ls > 0)){
            t = false
            ri +=1
            rs -=1
          }
          else if (ri == le)  {
            ls -=1
            le +=1
          }
          else if (ls > 0) {
            ls -=1
            le +=1
          }
          else {
            ri +=1
            rs -=1
          }
        }
      }
      if (t) {
        println("YES")
      }
      else println("NO")
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val s = tokenizer.nextToken()
      var t = true
      var r = 0
      var l = 0
      val len = s.length
      val nn = len / 2
      for (i <- s) {
        if (i.toString == "(") {
          l+=1
        }
        else if (i.toString == ")") {
          r+=1
        }
      }
      var rs = nn - r
      var ls = nn-l
      var ri = 0
      var le = 0
      for (i <- s) {
        if (i.toString == "(") {
          le+=1
        }
        else if (i.toString == ")") {
          ri+=1
        }
        else {
          if ((ri != le) && (rs > 0) && (ls > 0)){
            t = false
            ri +=1
            rs -=1
          }
          else if (ri == le)  {
            ls -=1
            le +=1
          }
          else if (ls > 0) {
            ls -=1
            le +=1
          }
          else {
            ri +=1
            rs -=1
          }
        }
      }
      if (t) {
        println("YES")
      }
      else println("NO")
    }
  }
}

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val s = tokenizer.nextToken()
      var t = true
      var r = 0
      var l = 0
      val len = s.length
      val nn = len / 2

      for (i <- s) {
        if (i.toString == "(") {
          l+=1
        }
        else if (i.toString == ")") {
          r+=1
        }
      }
      var rs = nn - r
      var ls = nn-l
      var ri = 0
      var le = 0
      for (i <- s) {
        if (i.toString == "(") {
          le+=1
        }
        else if (i.toString == ")") {
          ri+=1
        }
        else {
          if ((ri != le) && (rs > 0) && (ls > 0)){
            t = false
            ri +=1
            rs -=1
          }
          else if ((ri == le) || (ls > 0)) {
            ls -=1
            le +=1
          }
          else {
            ri +=1
            rs -=1
          }
        }
      }
      if (t) {
        println("YES")
      }
      else println("NO")
    }
  }
}


The grasshopper is located on the numeric axis at the point with coordinate $$$x_0$$$.Having nothing else to do he starts jumping between integer points on the axis. Making a jump from a point with coordinate $$$x$$$ with a distance $$$d$$$ to the left moves the grasshopper to a point with a coordinate $$$x - d$$$, while jumping to the right moves him to a point with a coordinate $$$x + d$$$.The grasshopper is very fond of positive integers, so for each integer $$$i$$$ starting with $$$1$$$ the following holds: exactly $$$i$$$ minutes after the start he makes a jump with a distance of exactly $$$i$$$. So, in the first minutes he jumps by $$$1$$$, then by $$$2$$$, and so on.The direction of a jump is determined as follows: if the point where the grasshopper was before the jump has an even coordinate, the grasshopper jumps to the left, otherwise he jumps to the right.For example, if after $$$18$$$ consecutive jumps he arrives at the point with a coordinate $$$7$$$, he will jump by a distance of $$$19$$$ to the right, since $$$7$$$ is an odd number, and will end up at a point $$$7 + 19 = 26$$$. Since $$$26$$$ is an even number, the next jump the grasshopper will make to the left by a distance of $$$20$$$, and it will move him to the point $$$26 - 20 = 6$$$.Find exactly which point the grasshopper will be at after exactly $$$n$$$ jumps.

The first line of input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$x_0$$$ ($$$-10^{14} \leq x_0 \leq 10^{14}$$$) and $$$n$$$ ($$$0 \leq n \leq 10^{14}$$$) — the coordinate of the grasshopper's initial position and the number of jumps.

Print exactly $$$t$$$ lines. On the $$$i$$$-th line print one integer — the answer to the $$$i$$$-th test case — the coordinate of the point the grasshopper will be at after making $$$n$$$ jumps from the point $$$x_0$$$.

NoteThe first two test cases in the example correspond to the first two jumps from the point $$$x_0 = 0$$$. Since $$$0$$$ is an even number, the first jump of length $$$1$$$ is made to the left, and the grasshopper ends up at the point $$$0 - 1 = -1$$$.Then, since $$$-1$$$ is an odd number, a jump of length $$$2$$$ is made to the right, bringing the grasshopper to the point with coordinate $$$-1 + 2 = 1$$$.

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

  override def solve(io: IO) = io.repeat {
    val x, n = io.read[Long]
    val jump = (n%4 match {
      case 0 => 0
      case 1 => -n
      case 2 => 1
      case 3 => n+1
    }) * (if (x%2 == 0) 1 else -1)
    io.write(x + jump)
  }
}
/****************************[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
      }
    }
  }
}


Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.Right now he has a map of some imaginary city with $$$n$$$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $$$u$$$ and $$$v$$$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $$$w$$$ that the original map has a tunnel between $$$u$$$ and $$$w$$$ and a tunnel between $$$w$$$ and $$$v$$$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.

The first line of the input contains a single integer $$$n$$$ ($$$2 \leq n \leq 200\,000$$$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \ne v_i$$$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $$$n$$$ stations and $$$n - 1$$$ tunnels form a tree.

Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map.

NoteIn the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $$$6$$$.In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $$$(1, 4)$$$. For these two stations the distance is $$$2$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val V, U = Array.ofDim[Int](N - 1)
    rep(N - 1) { i =>
      V(i) = ni() - 1
      U(i) = ni() - 1
    }
    val t = packUGraph(N, V, U)
    val (_, p, q) = traceBfs(t)
    val sum = Array.ofDim[Long](2, 2) // パスの長さ (偶奇) = (Σlen, Σ1)
    val dp = Array.ofDim[Long](N, 2, 2) // 深さ 偶奇 = (Σdepth, Σ1)
    rep_r(N) { i =>
      val v = q(i)
      // vを追加
      dp(v)(0)(1) += 1

      t(v) foreach { u =>
        if (p(v) != u) {
          def cl(x: Int) = dp(v)(x)(1)
          def sl(x: Int) = dp(v)(x)(0)
          def cr(x: Int) = dp(u)(x)(1)
          def sr(x: Int) = dp(u)(x)(0) + cr(x) // 個数*1を足す

          // u側が１深くなるので偶奇が反転する
          rep(2) { xl =>
            rep(2) { xr =>
              sum(xl ^ xr ^ 1)(0) += (sl(xl) * cr(xr) + sr(xr) * cl(xl))
              sum(xl ^ xr ^ 1)(1) += cl(xl) * cr(xr)
            }
          }

          // dp(v)にdp(u)をマージする
          rep(2) { x =>
            // 1深くなるので反転する
            dp(v)(x)(0) += sr(x ^ 1)
            dp(v)(x)(1) += cr(x ^ 1)
          }
        }
      }
    }

    // { y = Σ(2a + 1):  Σ(a + 1) = (y - cnt) / 2 + cnt }
    val ans = sum(0)(0) / 2 + (sum(1)(0) - sum(1)(1)) / 2 + sum(1)(1)
    out.println(ans)
  }

  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]]): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    p(0) = -1
    val d = Array.fill[Int](n)(INF)
    d(0) = 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 InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

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

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

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

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


And now the numerous qualifying tournaments for one of the most prestigious Russian contests Russian Codec Cup are over. All n participants who have made it to the finals found themselves in a huge m-floored 108-star hotel. Of course the first thought to come in a place like this is "How about checking out the elevator?".The hotel's elevator moves between floors according to one never changing scheme. Initially (at the moment of time 0) the elevator is located on the 1-st floor, then it moves to the 2-nd floor, then — to the 3-rd floor and so on until it reaches the m-th floor. After that the elevator moves to floor m - 1, then to floor m - 2, and so on until it reaches the first floor. This process is repeated infinitely. We know that the elevator has infinite capacity; we also know that on every floor people get on the elevator immediately. Moving between the floors takes a unit of time.For each of the n participant you are given si, which represents the floor where the i-th participant starts, fi, which represents the floor the i-th participant wants to reach, and ti, which represents the time when the i-th participant starts on the floor si.For each participant print the minimum time of his/her arrival to the floor fi. If the elevator stops on the floor si at the time ti, then the i-th participant can enter the elevator immediately. If the participant starts on the floor si and that's the floor he wanted to reach initially (si = fi), then the time of arrival to the floor fi for this participant is considered equal to ti.

The first line contains two space-separated integers n and m (1 ≤ n ≤ 105, 2 ≤ m ≤ 108).  Next n lines contain information about the participants in the form of three space-separated integers si fi ti (1 ≤ si, fi ≤ m, 0 ≤ ti ≤ 108), described in the problem statement.

Print n lines each containing one integer — the time of the arrival for each participant to the required floor.

NoteLet's consider the first sample. The first participant starts at floor s = 2 by the time equal to t = 3. To get to the floor f = 4, he has to wait until the time equals 7, that's the time when the elevator will go upwards for the second time. Then the first participant should get on the elevator and go two floors up. In this case the first participant gets to the floor f at time equal to 9. The second participant starts at the time t = 0 on the floor s = 1, enters the elevator immediately, and arrives to the floor f = 2. The third participant doesn't wait for the elevator, because he needs to arrive to the same floor where he starts.

import scala.collection.mutable.ListBuffer
object P117A extends App {

  def r = readLine.split(" ").map(_.toInt)
  var entries = ListBuffer[Array[Int]]()
  var Array(n, m) = r

  def time2stock(t: Int) = {
    val tmp = (t - 1) % (m - 1)
    if (((t - 1) / (m - 1)) % 2 == 0) 2 + tmp else m - 1 - tmp
  }

  def stock2time(start: Int, stock: Int) = {
    val currStock = time2stock(start)
    val direction = currStock < time2stock(start + 1)
    if (direction) {
      if (currStock <= stock) stock - currStock else m - currStock + m - stock
    } else {
      if (currStock >= stock) currStock - stock else currStock + stock - 2
    }
  }

  for (i <- 1 to n) {
    val Array(s, f, t) = r
    if (s == f) println(t)
    else {
      val arrival = stock2time(t, s) + t
      println(arrival + stock2time(arrival, f))
    }
  }
}

import scala.collection.mutable.ListBuffer
object P117A extends App {

  def r = readLine.split(" ").map(_.toInt)
  var entries = ListBuffer[Array[Int]]()
  var Array(n, m) = r

  def time2stock(t: Int) = {
    val tmp = (t - 1) % (m - 1)
    if (((t - 1) / (m - 1)) % 2 == 0) 2 + tmp else m - 1 - tmp
  }

  def stock2time(start: Int, stock: Int) = {
    val currStock = time2stock(start)
    val direction = currStock < time2stock(start + 1)
    if (direction) {
      if (currStock <= stock) stock - currStock else m - currStock + m - stock - 1
    } else {
      if (currStock >= stock) currStock - stock else currStock + stock - 2
    }
  }

  for (i <- 1 to n) {
    val Array(s, f, t) = r
    if (s == f) println(0)
    else {
      val arrival = stock2time(t, s) + t
      println(arrival + stock2time(arrival, f))
    }
  }
}

import scala.collection.mutable.ListBuffer
object P117A extends App {

  def r = readLine.split(" ").map(_.toInt)
  var entries = ListBuffer[Array[Int]]()
  var Array(n, m) = r

  def time2stock(t: Int) = {
    val tmp = (t - 1) % (m - 1)
    if (((t - 1) / (m - 1)) % 2 == 0) 2 + tmp else m - 1 - tmp
  }

  def stock2time(start: Int, stock: Int) = {
    val currStock = time2stock(start)
    val direction = currStock < time2stock(start + 1)
    if (direction) {
      if (currStock <= stock) stock - currStock else m - currStock + m - stock
    } else {
      if (currStock >= stock) currStock - stock else currStock + stock - 2
    }
  }

  for (i <- 1 to n) {
    val Array(s, f, t) = r
    if (s == f) println(0)
    else {
      val arrival = stock2time(t, s) + t
      println(arrival + stock2time(arrival, f))
    }
  }
}


Vasya has a tree consisting of $$$n$$$ vertices with root in vertex $$$1$$$. At first all vertices has $$$0$$$ written on it.Let $$$d(i, j)$$$ be the distance between vertices $$$i$$$ and $$$j$$$, i.e. number of edges in the shortest path from $$$i$$$ to $$$j$$$. Also, let's denote $$$k$$$-subtree of vertex $$$x$$$ — set of vertices $$$y$$$ such that next two conditions are met:   $$$x$$$ is the ancestor of $$$y$$$ (each vertex is the ancestor of itself);  $$$d(x, y) \le k$$$. Vasya needs you to process $$$m$$$ queries. The $$$i$$$-th query is a triple $$$v_i$$$, $$$d_i$$$ and $$$x_i$$$. For each query Vasya adds value $$$x_i$$$ to each vertex from $$$d_i$$$-subtree of $$$v_i$$$.Report to Vasya all values, written on vertices of the tree after processing all queries.

The first line contains single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — number of vertices in the tree. Each of next $$$n - 1$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$) — edge between vertices $$$x$$$ and $$$y$$$. It is guarantied that given graph is a tree. Next line contains single integer $$$m$$$ ($$$1 \le m \le 3 \cdot 10^5$$$) — number of queries. Each of next $$$m$$$ lines contains three integers $$$v_i$$$, $$$d_i$$$, $$$x_i$$$ ($$$1 \le v_i \le n$$$, $$$0 \le d_i \le 10^9$$$, $$$1 \le x_i \le 10^9$$$) — description of the $$$i$$$-th query.

Print $$$n$$$ integers. The $$$i$$$-th integers is the value, written in the $$$i$$$-th vertex after processing all queries.

NoteIn the first exapmle initial values in vertices are $$$0, 0, 0, 0, 0$$$. After the first query values will be equal to $$$1, 1, 1, 0, 0$$$. After the second query values will be equal to $$$1, 11, 1, 0, 0$$$. After the third query values will be equal to $$$1, 11, 1, 100, 0$$$.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val (from, to) = na2(N - 1, -1)
    val t = packUGraph(N, from, to)
    val (depth, parent, bfs) = traceBfs(t)
    val deepest = depth(bfs(N - 1))

    val M = ni()

    case class Query(d: Int, x: Int)
    val Q = Array.fill[ArrayBuffer[Query]](N)(ArrayBuffer())
    rep(M) { i =>
      val v = ni() - 1
      val d, x = ni()
      Q(v) += Query(d, x)
    }

    val adds = new BIT(deepest + 1)
    val ans = Array.ofDim[Long](N)

    case class Visit(v: Int) {
      var flg = false
    }

    val queue = new java.util.Stack[Visit]()
    queue.push(Visit(0))
    while(!queue.isEmpty) {
      val v = queue.peek()

      if (v.flg) {
        rep(Q(v.v).length) { i =>
          val q = Q(v.v)(i)
          adds.add(min(deepest, q.d + depth(v.v)), -q.x)
        }
        queue.pop()
      } else {
        v.flg = true
        rep(Q(v.v).length) { i =>
          val q = Q(v.v)(i)
          adds.add(min(q.d + depth(v.v), deepest), q.x)
        }

        ans(v.v) = adds.sum(deepest) - (if (depth(v.v) > 0) adds.sum(depth(v.v) - 1) else 0)

        t(v.v).foreach { u =>
          if (u != parent(v.v)) {
            queue.push(Visit(u))
          }
        }
      }
    }

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

  }

  /**
    * @param n ノード数
    */
  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 BIT(n: Int, zero: Long)(f: (Long, Long) => Long) {
    def this(n: Int) = this(n, 0)(_ + _)

    private val N = {
      val a = Integer.highestOneBit(n)
      if (a == n) a else a << 1
    }
    private val bit = if (zero != 0) Array.fill[Long](N + 1)(zero) else Array.ofDim[Long](N + 1)

    /**
      * 0 index
      */
    def sum(i: Int): Long = {
      var x = i + 1
      var s: Long = 0
      while(x > 0) {
        s = f(s, bit(x))
        x -= x & -x
      }
      s
    }

    /**
      * 0 index
      */
    def add(i: Int, a: Long): Unit = {
      var x = i + 1
      while(x <= N) {
        bit(x) = f(bit(x), a)
        x += x & -x
      }
    }
  }

  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[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}


According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.  However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.

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

/**
  * @author traff
  */

object Main extends App {
  val n = StdIn.readLine().toInt

  val a = StdIn.readLine().split(" ").map(_.toInt)

  var i = n

  var m = mutable.HashSet[Int]()

  for (j <- 1 to n) {
    if (a(j-1) == i) {
      print(a(j-1))
      i-=1
      while (m.contains(i)) {
        print(s" $i")
        m.remove(i)
        i-=1
      }

    } else {
      m.add(a(j-1))
    }
    println()
  }
}

import scala.collection.mutable.ArrayBuffer

object Task1 extends App {
  var pos = 0
  val n = readInt()
  val rawData = readLine()
  val intArray = rawData.split(" ").map(x => x.toInt)
  val data = new ArrayBuffer[Pair[Int, Int]]
  for(i <- 0.until(n)) {
    data.+=(new Pair(i, intArray(i)))
  }
  val sortedData = data.sortWith(_._2 > _._2)
  sortedData.foreach(data => {
    val currPos = data._1
    while (currPos > pos) {
      println()
      pos += 1
    }
    print(data._2 + " ")
  })
}


Sereja has a bracket sequence s1, s2, ..., sn, or, in other words, a string s of length n, consisting of characters "(" and ")".Sereja needs to answer m queries, each of them is described by two integers li, ri (1 ≤ li ≤ ri ≤ n). The answer to the i-th query is the length of the maximum correct bracket subsequence of sequence sli, sli + 1, ..., sri. Help Sereja answer all queries.You can find the definitions for a subsequence and a correct bracket sequence in the notes.

The first line contains a sequence of characters s1, s2, ..., sn (1 ≤ n ≤ 106) without any spaces. Each character is either a "(" or a ")". The second line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains a pair of integers. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n) — the description of the i-th query.

Print the answer to each question on a single line. Print the answers in the order they go in the input.

NoteA subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).A correct bracket sequence is a bracket sequence that can be transformed into a correct aryphmetic expression by inserting characters "1" and "+" between the characters of the string. For example, bracket sequences "()()", "(())" are correct (the resulting expressions "(1)+(1)", "((1+1)+1)"), and ")(" and "(" are not.For the third query required sequence will be «()».For the fourth query required sequence will be «()(())(())».

/**
** http://codeforces.com/contest/380/problem/C
**/

object Main extends App {
	import scala.io.StdIn._
	Console.setOut(new java.io.BufferedOutputStream(Console.out))

    val data = readLine().toCharArray
    val tree = new SegmentTree(data)
    tree.buildSegment()

    val p = readInt()
    for( _ <- 0 to p - 1) {
    	val Array(l, r) = readLine().split(" ").map(_.toInt)
	    println(tree.query(l-1, r-1).balanced)
    }
    Console.flush
}

case class Node(open: Int = 0, balanced: Int = 0, closed: Int = 0) {

	def balanced(other: Node): Int = {
		math.min(open, other.closed)
	}

}
object Node {
	def of(lNode: Node, rNode: Node): Node = {
		val matched = lNode.balanced(rNode)
		Node(lNode.open + rNode.open - matched,
				lNode.balanced + rNode.balanced + 2 * matched,
				lNode.closed + rNode.closed - matched)
	}
}

class SegmentTree(data: Array[Char]) {

	val treeSize = 4 * Integer.highestOneBit(data.size)
    val treeArray = Array.ofDim[Node](treeSize)

	def buildSegment() = {
		def buildLoop(vertex: Int, leftId: Int, rightId: Int): Unit = {
			if(leftId == rightId) {
				if(data(leftId) == '(') {
					treeArray(vertex) = Node(open = 1)
				} else {
					treeArray(vertex) = Node(closed = 1)
				}
			} else {
				val mid = leftId + (rightId - leftId)/2
				val leftV = 2 * vertex
				val rightV = 2 * vertex + 1
				buildLoop(leftV, leftId, mid)
				buildLoop(rightV, mid+1, rightId)

				val minBalanced = treeArray(leftV).balanced(treeArray(rightV))
				val leftNode = treeArray(leftV)
				val rightNode = treeArray(rightV)

				val leftParan = leftNode.open + rightNode.open - minBalanced
				val balancedParan = 2 * minBalanced + leftNode.balanced + rightNode.balanced
				val rightParan = leftNode.closed + rightNode.closed - minBalanced

				treeArray(vertex) = Node(leftParan, balancedParan, rightParan)
			}
		}

		buildLoop(1, 0, data.size - 1)
	}

	def query(l: Int, r: Int, vertex: Int = 1, begin: Int = 0, end: Int = data.size - 1): Node = {
		// println(s"$vertex: $begin $end")

		if(begin > r || l > end) {
			// println("out")
			Node(0, 0, 0)
		} else if(l <= begin && end <= r) {
			val res = treeArray(vertex)
			// println("ret: "+ res)
			res
		} else {
			val mid = begin + (end - begin)/2
			// println(s"mid: $mid")
			val lNode = query(l, math.min(r, mid), 2 * vertex, begin, mid)
			val rNode = query(math.max(l, mid+1), r, 2 * vertex + 1, mid+1, end)
			Node.of(lNode, rNode)
		}
	}

	def pprint() = {
	 	println(treeArray.mkString(" "))
	}
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine

  val nodes = mutable.ArrayBuffer[IndexedSeq[Node]]()
  nodes += s.collect { case ')' => closingNode case '(' => openingNode }

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += (0 until len by 2).map(j => if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1))
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    //println(s"l=$l r=$r level=$level")
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
     // println(s"l0=$l0 r0=$r0")
      if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)
      else if (/*r - l + 1 <= (1 << nextLevel)*/ l0 == r0) calc(l, r, nextLevel)
      else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  case class SegTree(as: Array[Node]) {

    val n = as.length
    val t = Array.ofDim[Node](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		val v2 = v << 1
		build(v2, tl, tm)
		build(v2 + 1, tm + 1, tr)
		t(v) = t(v2) + t(v2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Node = {
    	if (l > r) Node()
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  val v2 = v << 1
    	  query(l, Math.min(r, tm), v2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
    	}
    }

  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine.toCharArray
  val nodes = SegTree(s.map(c => if (c == ')') closingNode else openingNode))

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(nodes.query(l - 1, r - 1).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  case class SegTree(as: Array[Node]) {

    val n = as.length
    val t = Array.ofDim[Node](4 * Integer.highestOneBit(n))
    build(1, 0, n - 1)

    def build(v: Int, tl: Int, tr: Int) {
      if (tl == tr) t(v) = as(tl)
	  else {
		val tm = (tl + tr) >> 1
		val v2 = v << 1
		build(v2, tl, tm)
		build(v2 + 1, tm + 1, tr)
		t(v) = t(v2) + t(v2 + 1)
	  }
    }

    def query(l: Int, r: Int, v: Int = 1, tl: Int = 0, tr: Int = n - 1): Node = {
    	if (l > r) Node()
    	else if (l == tl && r == tr) t(v)
    	else {
    	  val tm = (tl + tr) >> 1
    	  val v2 = v << 1
    	  query(l, Math.min(r, tm), v2, tl, tm) +
    	  	query(Math.max(l, tm + 1), r, v2 + 1, tm + 1, tr)
    	}
    }

  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine.toCharArray
  val nodes = SegTree(s.map(c => if (c == ')') closingNode else openingNode))

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(nodes.query(l - 1, r - 1).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine.toCharArray
  val nodes = mutable.ArrayBuffer[Array[Node]]()
  nodes += s.map(c => if (c == ')') closingNode else openingNode)

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += Array.ofDim[Node](len / 2 + 1)
    for (j <- 0 until len by 2) {
      nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)
    }
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
      if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)
      else if (l0 == r0) calc(l, r, nextLevel)
      else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine.toCharArray
  val nodes = mutable.ArrayBuffer[Array[Node]]()
  nodes += s.map(c => if (c == ')') closingNode else openingNode)

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += Array.ofDim[Node](len / 2 + 1)
    for (j <- 0 until len by 2) {
      nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)
    }
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
      if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)
      else if (l0 == r0) calc(l, r, nextLevel)
      else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  val s = readLine

  val st = mutable.Stack[Char]()

  val cnts = Array.ofDim[Int](s.length)
  var cnt = 0

  val cnts2 = Array.ofDim[Int](s.length)
  var cnt2 = 0

  val uncloseds = Array.ofDim[Int](s.length)
  var unclosed = 0

  val unopeneds = Array.ofDim[Int](s.length)
  var unopened = 0

  val depths = Array.ofDim[Int](s.length)

  for (i <- s.indices) {
    val c = s(i)
    depths(i) = 2 * st.size
    if (c == '(') {
      uncloseds(i) = unclosed
      unclosed += 2
    } else {
      unclosed = Math.max(unclosed - 2, 0)
      uncloseds(i) = unclosed
    }
    if (c == ')' && st.headOption == Some('(')) {
      cnt += 2
      st.pop
    } else st.push(c)
    cnts(i) = cnt
  }

  st.clear
  for (i <- s.indices.reverse) {
    val c = s(i)
    if (c == ')') {
      unopeneds(i) = unopened
      unopened += 2
    } else {
      unopened = Math.max(unopened - 2, 0)
      unopeneds(i) = unopened
    }
    if (c == '(' && st.headOption == Some(')')) {
      cnt2 += 2
      st.pop
    } else st.push(c)
    cnts2(i) = cnt2
  }

//  println(cnts.mkString(" "))
//  println(depths.mkString(" "))
//  println(uncloseds.mkString(" "))
//  println(unopeneds.mkString(" "))

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2).map(_ - 1)
    val ans = Math.min(cnts(r) - cnts(l), cnts2(l) - cnts2(r))
    println(ans)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine

  val nodes = mutable.ArrayBuffer[IndexedSeq[Node]]()
  nodes += s.collect { case ')' => closingNode case '(' => openingNode }

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += (0 until len by 2).map(j => if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1))
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    //println(s"l=$l r=$r level=$level")
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
     // println(s"l0=$l0 r0=$r0")
      if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel)
      else if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)
      else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine

  val nodes = mutable.ArrayBuffer[Array[Node]]()
  nodes += s.toCharArray.map(c => if (c == ')') closingNode else openingNode)

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += Array.ofDim[Node](len / 2 + 1)
    for (j <- 0 until len by 2) {
      nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)
    }
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    //println(s"l=$l r=$r level=$level")
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
     // println(s"l0=$l0 r0=$r0")
      if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel)
      else if (l == (l >> level) << level && r + 1 == ((r + 1) >> level) << level) nodes(level)(l >> level)
      else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine

  val nodes = mutable.ArrayBuffer[Array[Node]]()
  nodes += s.toCharArray.map(c => if (c == ')') closingNode else openingNode)

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += Array.ofDim[Node](len / 2 + 1)
    for (j <- 0 until len by 2) {
      nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)
    }
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    //println(s"l=$l r=$r level=$level")
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
     // println(s"l0=$l0 r0=$r0")
      if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel)
      else if (l == (l >> level) << level && r + 1 == ((r + 1) >> level << level)) nodes(level)(l >> level)
      else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine

  val nodes = mutable.ArrayBuffer[Array[Node]]()
  nodes += s.toCharArray.map(c => if (c == ')') closingNode else openingNode)

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += Array.ofDim[Node](len / 2 + 1)
    for (j <- 0 until len by 2) {
      nodes.last(j >> 1) = if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1)
    }
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
      if (r - l + 1 == 1 << level) nodes(level)(l >> level)
      else if (r - l + 1 > (1 << nextLevel)) calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
      else calc(l, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  case class Node(opening: Int = 0, closing: Int = 0, paired: Int = 0) {
    def +(other: Node) = {
      val matches = this.opening min other.closing
      Node(this.opening + other.opening - matches,
        this.closing + other.closing - matches,
        this.paired + other.paired + 2 * matches)
    }
  }

  val openingNode = Node(opening = 1)
  val closingNode = Node(closing = 1)

  val s = readLine

  val nodes = mutable.ArrayBuffer[IndexedSeq[Node]]()
  nodes += s.collect { case ')' => closingNode case '(' => openingNode }

  var len = nodes(0).length
  var i = 0
  while (len >= 1) {
    nodes += (0 until len by 2).map(j => if (j + 1 >= len) nodes(i)(j) else nodes(i)(j) + nodes(i)(j + 1))
    i += 1
    len /= 2
  }
  val maxLevel = i

  def calc(l: Int, r: Int, level: Int): Node = {
    //println(s"l=$l r=$r level=$level")
    if (level == 0) nodes(level)(l)
    else {
      val nextLevel = level - 1
      val l0 = l >> nextLevel
      val r0 = r >> nextLevel
     // println(s"l0=$l0 r0=$r0")
      if (r - l + 1 <= (1 << nextLevel)) calc(l, r, nextLevel)
      else if (l == (l >> level) << level && r + 1 == l + ((r - l + 1) >> level) << level) nodes(level)(l >> level)
      else calc(l, (r0 << nextLevel) - 1, nextLevel) + calc(r0 << nextLevel, r, nextLevel)
    }
  }

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2)
    println(calc(l - 1, r - 1, maxLevel).paired)
  }

  Console.flush
}

import scala.collection._

object C extends App {

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

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

  val s = readLine

  val st = mutable.Stack[Char]()

  val cnts = Array.ofDim[Int](s.length)
  var cnt = 0

  val cnts2 = Array.ofDim[Int](s.length)
  var cnt2 = 0

  val uncloseds = Array.ofDim[Int](s.length)
  var unclosed = 0

  val unopeneds = Array.ofDim[Int](s.length)
  var unopened = 0

  val depths = Array.ofDim[Int](s.length)

  for (i <- s.indices) {
    val c = s(i)
    depths(i) = 2 * st.size
    if (c == '(') {
      uncloseds(i) = unclosed
      unclosed += 2
    } else {
      unclosed = Math.max(unclosed - 2, 0)
      uncloseds(i) = unclosed
    }
    if (c == ')' && st.headOption == Some('(')) {
      cnt += 2
      st.pop
    } else st.push(c)
    cnts(i) = cnt
  }

  st.clear
  for (i <- s.indices.reverse) {
    val c = s(i)
    if (c == ')') {
      unopeneds(i) = unopened
      unopened += 2
    } else {
      unopened = Math.max(unopened - 2, 0)
      unopeneds(i) = unopened
    }
    if (c == '(' && st.headOption == Some(')')) {
      cnt2 += 2
      st.pop
    } else st.push(c)
    cnts2(i) = cnt2
  }

//  println(cnts.mkString(" "))
//  println(depths.mkString(" "))
//  println(uncloseds.mkString(" "))
  //println(unopeneds.mkString(" "))

  val m = readInt

  for (i <- 0 until m) {
    val Array(l, r) = readInts(2).map(_ - 1)
    val ans = cnts(r) - cnts(l) - (if (l == 0) 0 else uncloseds(l) - uncloseds(r))
    println(ans)
  }

  Console.flush
}


You are given a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$. You need to paint all the digits in two colors so that:  each digit is painted either in the color $$$1$$$ or in the color $$$2$$$;  if you write in a row from left to right all the digits painted in the color $$$1$$$, and then after them all the digits painted in the color $$$2$$$, then the resulting sequence of $$$n$$$ digits will be non-decreasing (that is, each next digit will be greater than or equal to the previous digit). For example, for the sequence $$$d=914$$$ the only valid coloring is $$$211$$$ (paint in the color $$$1$$$ two last digits, paint in the color $$$2$$$ the first digit). But $$$122$$$ is not a valid coloring ($$$9$$$ concatenated with $$$14$$$ is not a non-decreasing sequence).It is allowed that either of the two colors is not used at all. Digits painted in the same color are not required to have consecutive positions.Find any of the valid ways to paint the given sequence of digits or determine that it is impossible to do.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10000$$$) — the number of test cases in the input. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — the length of a given sequence of digits. The next line contains a sequence of $$$n$$$ digits $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). The digits are written in a row without spaces or any other separators. The sequence can start with 0. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$2\cdot10^5$$$.

Print $$$t$$$ lines — the answers to each of the test cases in the input. If there is a solution for a test case, the corresponding output line should contain any of the valid colorings written as a string of $$$n$$$ digits $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), where $$$t_i$$$ is the color the $$$i$$$-th digit is painted in. If there are several feasible solutions, print any of them. If there is no solution, then the corresponding output line should contain a single character '-' (the minus sign).

NoteIn the first test case, $$$d=040425524644$$$. The output $$$t=121212211211$$$ is correct because $$$0022444$$$ (painted in $$$1$$$) concatenated with $$$44556$$$ (painted in $$$2$$$) is $$$002244444556$$$ which is a sorted sequence of $$$n$$$ given digits.

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

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

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

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

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

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

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

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

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

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

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

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

  def solve2(): Unit = {
    val N = ni()
    val D = ns(N).map(_-'0')
    def isSorted2(as: ArrayBuffer[Int]): Boolean = {
      REP(as.length - 1) { i =>
        if (as(i) > as(i + 1)) return false
      }
      true
    }

    def isSorted(ones: ArrayBuffer[Int], twos: ArrayBuffer[Int]): Boolean = {
      isSorted2(ones) && isSorted2(twos) && {
        ones.isEmpty || twos.isEmpty || ones.last <= twos.head
      }
    }

    def showResult(med: Int, lastOneIx: Int): Unit = {
      val A = Array.ofDim[Int](N)
      REP(N) { i =>
        A(i) = if (D(i) < med) 1
        else if(D(i) > med) 2
        else {
          if (i < lastOneIx) 2 else 1
        }
      }
      out.println(A.mkString)
    }

    val ones, twos = ArrayBuffer[Int]()
    REP(10) { med =>
      ones.clear()
      twos.clear()
      var lastOneIx = -1
      REP(N) { i =>
        if (D(i) < med) {
          ones += D(i)
          lastOneIx = i
        }
      }
      TO(if (lastOneIx != - 1) lastOneIx + 1 else 0, N - 1) { i =>
        if (D(i) == med) ones += D(i)
      }
      REP(N) { i =>
        if (D(i) > med || D(i) == med && i < lastOneIx) {
          twos += D(i)
        }
      }
      debug(s"med:$med")
      debug(ones.mkString(" "))
      debug(twos.mkString(" "))
      if (isSorted(ones, twos)) {
        debug(s"med:$med lastOneIx:$lastOneIx")
        showResult(med, lastOneIx)
        return
      }
    }
    out.println("-")
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve2(): Unit = {
    val N = ni()
    val D = ns(N).map(_-'0')
    def isSorted2(as: ArrayBuffer[Int]): Boolean = {
      REP(as.length - 1) { i =>
        if (as(i) > as(i + 1)) return false
      }
      true
    }

    def isSorted(ones: ArrayBuffer[Int], twos: ArrayBuffer[Int]): Boolean = {
      isSorted2(ones) && isSorted2(twos) && {
        ones.isEmpty || twos.isEmpty || ones.last <= twos.head
      }
    }

    def showResult(med: Int, oneMxIx: Int): Unit = {
      val A = Array.ofDim[Int](N)
      REP(N) { i =>
        A(i) = if (D(i) < med) 1
        else if(D(i) > med) 2
        else {
          if (i < oneMxIx) 2 else 1
        }
      }
      out.println(A.mkString)
    }

    val ones, twos = ArrayBuffer[Int]()
    REP(10) { med =>
      ones.clear()
      twos.clear()
      var oneMx = -1
      var oneMxIx = -1
      REP(N) { i =>
        if (D(i) < med) {
          ones += D(i)
          if (D(i) > oneMx) {
            oneMx = D(i)
            oneMxIx = i
          }
        }
      }
      if (oneMxIx != -1) {
        TO(oneMxIx + 1, N - 1) { i =>
          if (D(i) == med) ones += D(i)
        }
      }
      REP(N) { i =>
        if (D(i) > med || D(i) == med && i < oneMxIx) {
          twos += D(i)
        }
      }
      debug(ones.mkString(" "))
      debug(twos.mkString(" "))
      if (isSorted(ones, twos)) {
        showResult(med, oneMxIx)
        return
      }
    }
    out.println("-")
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }
}

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

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

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

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

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

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

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

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

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

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

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

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

  def solve2(): Unit = {
    val N = ni()
    val D = ns(N).map(_-'0')
    def isSorted2(as: ArrayBuffer[Int]): Boolean = {
      REP(as.length - 1) { i =>
        if (as(i) > as(i + 1)) return false
      }
      true
    }

    def isSorted(ones: ArrayBuffer[Int], twos: ArrayBuffer[Int]): Boolean = {
      isSorted2(ones) && isSorted2(twos) && {
        ones.isEmpty || twos.isEmpty || ones.last <= twos.head
      }
    }

    def showResult(med: Int, oneMxIx: Int): Unit = {
      val A = Array.ofDim[Int](N)
      REP(N) { i =>
        A(i) = if (D(i) < med) 1
        else if(D(i) > med) 2
        else {
          if (i < oneMxIx) 2 else 1
        }
      }
      out.println(A.mkString)
    }

    val ones, twos = ArrayBuffer[Int]()
    REP(10) { med =>
      ones.clear()
      twos.clear()
      var oneMx = -1
      var oneMxIx = -1
      REP(N) { i =>
        if (D(i) < med) {
          ones += D(i)
          if (D(i) > oneMx) {
            oneMx = D(i)
            oneMxIx = i
          }
        }
      }
      TO(if (oneMxIx != - 1) oneMxIx + 1 else 0, N - 1) { i =>
        if (D(i) == med) ones += D(i)
      }
      REP(N) { i =>
        if (D(i) > med || D(i) == med && i < oneMxIx) {
          twos += D(i)
        }
      }
      debug(ones.mkString(" "))
      debug(twos.mkString(" "))
      if (isSorted(ones, twos)) {
        debug(s"med:$med oneMxIx:$oneMxIx")
        showResult(med, oneMxIx)
        return
      }
    }
    out.println("-")
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }
}


Alice is playing with some stones.Now there are three numbered heaps of stones. The first of them contains $$$a$$$ stones, the second of them contains $$$b$$$ stones and the third of them contains $$$c$$$ stones.Each time she can do one of two operations:  take one stone from the first heap and two stones from the second heap (this operation can be done only if the first heap contains at least one stone and the second heap contains at least two stones);  take one stone from the second heap and two stones from the third heap (this operation can be done only if the second heap contains at least one stone and the third heap contains at least two stones). She wants to get the maximum number of stones, but she doesn't know what to do. Initially, she has $$$0$$$ stones. Can you help her?

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. Next $$$t$$$ lines describe test cases in the following format: Line contains three non-negative integers $$$a$$$, $$$b$$$ and $$$c$$$, separated by spaces ($$$0 \leq a,b,c \leq 100$$$) — the number of stones in the first, the second and the third heap, respectively. In hacks it is allowed to use only one test case in the input, so $$$t = 1$$$ should be satisfied.

Print $$$t$$$ lines, the answers to the test cases in the same order as in the input. The answer to the test case is the integer  — the maximum possible number of stones that Alice can take after making some operations.

NoteFor the first test case in the first test, Alice can take two stones from the second heap and four stones from the third heap, making the second operation two times. Then she can take one stone from the first heap and two stones from the second heap, making the first operation one time. The summary number of stones, that Alice will take is $$$9$$$. It is impossible to make some operations to take more than $$$9$$$ stones, so the answer is $$$9$$$.

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

  override def apply(io: IO): io.type = {
    val inputs = io.read[Seq[(Int, Int, Int)]]

    inputs foreach { case (a, b, c) =>
        var ans = 0
        for {
          x <- 0 to a
          y <- 0 to (c/2)
          if (2*x + y) <= b
        } ans = ans max (3*(x + y))

        io.writeLine(ans)
    }

    io
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).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)

  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: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

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

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

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: 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
      }
    }
  }
}


A number is called 2050-number if it is $$$2050$$$, $$$20500$$$, ..., ($$$2050 \cdot 10^k$$$ for integer $$$k \ge 0$$$).Given a number $$$n$$$, you are asked to represent $$$n$$$ as the sum of some (not necessarily distinct) 2050-numbers. Compute the minimum number of 2050-numbers required for that.

The first line contains a single integer $$$T$$$ ($$$1\le T\leq 1\,000$$$) denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 10^{18}$$$) denoting the number to be represented.

For each test case, output the minimum number of 2050-numbers in one line.  If $$$n$$$ cannot be represented as the sum of 2050-numbers, output $$$-1$$$ instead.

object CF1517A extends App {
    def readLong: Long = scala.io.StdIn.readLine.toLong
  def readInt: Int = scala.io.StdIn.readLine.toInt

  var T = readInt
    for (t <- 0 until T) {
      var x: Long = 205000000000000000L
      var n = readLong
      var ans = 0
      while (x >= 2050) {
        while (n >= x) {
          ans += 1
          n -= x
        }
        x /= 10
      }
      if (n == 0) {
        println(ans)
      } else {
        println(-1)
      }
    }
}

object cf1517a {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

  def readLong(): Long= {
		Console.in.readLine().toLong
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		val res = for (nCase <- 1 to cases) yield {
			var v = readLong()
			var res = 0L
			var cSubstractor = 205000000000000000L
			while ( (v > 0) && (cSubstractor >= 2050L) ) {
				if (v >= cSubstractor) {
					res += v/cSubstractor
					v -= cSubstractor*(v/cSubstractor)
				}
				cSubstractor /= 10
			}
			if (v == 0) res else -1L
    }

		res.foreach( println(_))
  }
}

import scala.io.StdIn

object Main extends App {
  val n = StdIn.readInt()
  for (_ <- 0 until n) {
    val number: BigInt = BigInt(StdIn.readLine())
    println(if (number % 2050 != 0) -1 else (number / 2050).toString.split("").map(_.toInt).sum)
  }
}

import scala.collection._
import scala.collection.mutable.TreeSet
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util._

// https://codeforces.com/contest/977/problem/F

object Sum {
  def main(args: Array[String]): Unit = {
    val n = readInt()

    (0 until n).foreach(_ => {
      var v = readLong()

      var mul = 2050l
      while (10l * mul <= v) {
        mul *= 10l
      }

      var count = 0
      while (mul >= 2050 && v >= 0) {
        if (mul <= v) {
          v -= mul
          count += 1
        } else {
          mul /= 10
        }
      }

      if (v == 0) {
        println(count)
      } else {
        println(-1)
      }
    })
  }
}

object CF1517A extends App {
    def readLong: Long = scala.io.StdIn.readLine.toLong
  def readInt: Int = scala.io.StdIn.readLine.toInt

  var T = readInt
    for (t <- 0 until T) {
      var x: Long = 20500000000000000L
      var n = readLong
      var ans = 0
      while (x >= 2050) {
        while (n >= x) {
          ans += 1
          n -= x
        }
        x /= 10
      }
      if (n == 0) {
        println(ans)
      } else {
        println(-1)
      }
    }
}

object cf1517a {

  def readInt(): Int = {
		Console.in.readLine().toInt
	}

  def readLong(): Long= {
		Console.in.readLine().toLong
	}

	def readInts(): Array[Int] = {
		val line = Console.in.readLine()
		line.split(' ').map( _.toInt)
	}

	def main(args: Array[String]): Unit = {
		val cases = readInt()
		var nCase = 0
		val res = for (nCase <- 1 to cases) yield {
			var v = readLong()
			var res = 0L
			var cSubstractor = 20500000000000000L
			while ( (v > 0) && (cSubstractor >= 2050L) ) {
				if (v >= cSubstractor) {
					res += v/cSubstractor
					v -= cSubstractor*(v/cSubstractor)
				}
				cSubstractor /= 10
			}
			if (v == 0) res else -1L
    }

		res.foreach( println(_))
  }
}