A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.Nickolas adores permutations. He likes some permutations more than the others. He calls such permutations perfect. A perfect permutation is such permutation p that for any i (1 ≤ i ≤ n) (n is the permutation size) the following equations hold ppi = i and pi ≠ i. Nickolas asks you to print any perfect permutation of size n for the given n.

A single line contains a single integer n (1 ≤ n ≤ 100) — the permutation size.

If a perfect permutation of size n doesn't exist, print a single integer -1. Otherwise print n distinct integers from 1 to n, p1, p2, ..., pn — permutation p, that is perfect. Separate printed numbers by whitespaces.

import java.util
import scala.collection.mutable.ArrayBuffer

object Main {
  var tokenizer = new util.StringTokenizer("")

  def readToken = {
    while (!tokenizer.hasMoreTokens) tokenizer = new util.StringTokenizer(readLine)
    tokenizer.nextToken
  }

  def readInt = readToken.toInt

  // >>>
  // >>>

  def main(args: Array[String]) {
    val n = readInt
    if (n % 2 == 1) {
      print(-1)
    } else {
      (1 to n).foreach(i => printf("%d ", if (i % 2 == 1) i + 1 else i - 1))
    }
  }
}

import java.util.Scanner

object PerfectPermutation {
  def main(args: Array[String]) = {
    val sc = new Scanner(System.in)
    val size = sc.nextInt()
    val res = perfectPermutation(size)
    res match {
      case None => println(-1)
      case Some(list) => list.foreach { i => print(s"$i ") }
    }
  }

  def perfectPermutation(size: Int): Option[List[Int]] = {
    if (size % 2 == 1) None
    else Some((1 to size).map(i => if (i % 2 == 0) i - 1 else i + 1).toList)
  }
}

import java.util._
import scala.io._
import java.lang.System._

object Main {
  def main(args: Array[String]) {
    val sc = new Scanner(in)
    val n = sc.nextInt
    if (n % 2 == 1) println(-1)
    else{
      (1 to n) map {
        case i if i % 2 == 0 => i-1
        case i               => i+1
      } foreach {
          e => print(e+" ")
      }
    }
  }
}

import java.util.Scanner
object A extends App {
  val sc= new Scanner(System.in)
  val n = sc.nextInt
  if (n % 2 == 0) {
    println((1 to n).map{x => x + (x % 2) * 2 - 1}.mkString(" "))
  } else {
    println(-1)
  }
}

import scala.io.StdIn

object A233 {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    println(n match {
      case x if x % 2 != 0 => -1
      case x => (1 to n).grouped(2). map(_.reverse).flatten.mkString(" ")
    })
  }
}

import java.util.StringTokenizer

object _233A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  if (n % 2 == 1) println(-1)
  else {
    val a = (1 to n).toArray
    for (i <- 0 until(n, 2)) {
      val cb = a(i)
      a(i) = a(i + 1)
      a(i + 1) = cb
    }
    println(a.mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  if (n % 2 == 1)
    println("-1")
  else
    println(Range(1, n + 1).map{i =>
      if (i % 2 == 0) i - 1
      else i + 1
      }.mkString(" "))
}

object A233 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    if(n%2 == 1) {
      println("-1")
    } else {
      println((2 to n by 2).flatMap(x => Array(x, x-1)).mkString(" "))
    }
  }

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

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

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

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

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

}

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

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

  val N = sc.nextInt

  val answer =
    if (N % 2 == 1) "-1"
    else {
      for (i <- 0 until N) yield {
        if (i % 2 == 0) i + 2
        else i
      }
    }.mkString(" ")

  out.println(answer)
  out.close
}

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

  val n = readInt()

  val ans =
    if (n % 2 == 0)
      (1 to n).map(i => if (i % 2 == 0) i - 1 else i + 1)
    else
      IndexedSeq(-1)

  println(ans.mkString(" "))
}

import annotation.tailrec
import java.io._

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readInt = reader.readLine().toInt

  val n = readInt
  def ans = if(n % 2 == 0) (n to 1) by -1 else Iterable(-1)

  def main(args: Array[String]) {
    println(ans.mkString(" "))
  }
}

object test5 extends App {
    val n=readLine.toInt
    if(n%2==1)
    	println(-1)
    else
    {
        val arr=new Array[Int](n)
        for(i<-0 until n) arr(i)=i+1
        for(i<-0 until n by 2)
        {
        	val tmp=arr(i)
        	arr(i)=arr(i+1)
        	arr(i+1)=tmp
        }

        println(arr.mkString(" "))
    }
}

object test5 extends App {
    val n=readLine.toInt
    if(n%2==1)
    	println(-1)
    else
    {
        val arr=new Array[Int](n)
        for(i<-0 until n by 2)
        {
        	arr(i)=i+2
        	arr(i+1)=i+1
        }

        println(arr.mkString(" "))
    }
}

object Main {
  def main(args: Array[String]) {
    val n= readInt()
    if (n % 2 == 0) {
      val a = (1 to n).map{
        case i: Int if i % 2 == 0 => i - 1
        case i: Int if i % 2 == 1 => i + 1
      }
      println(a.mkString(" "))
    } else println("-1")
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  if (n % 2 == 1)
    println("-1")
  else
    println(Range(1, n + 1).map{i =>
      if (i % 2 == 0) i + 1
      else i - 1
      }.mkString(" "))
}

object test5 extends App {
    val n=readLine.toInt
    if(n==1)
    	println(-1)
    else
    {
        val arr=new Array[Int](n)
        for(i<-0 until n) arr(i)=i
        arr(0)=n
        println(arr.mkString(" "))
    }
}


DZY loves colors, and he enjoys painting.On a colorful day, DZY gets a colorful ribbon, which consists of n units (they are numbered from 1 to n from left to right). The color of the i-th unit of the ribbon is i at first. It is colorful enough, but we still consider that the colorfulness of each unit is 0 at first.DZY loves painting, we know. He takes up a paintbrush with color x and uses it to draw a line on the ribbon. In such a case some contiguous units are painted. Imagine that the color of unit i currently is y. When it is painted by this paintbrush, the color of the unit becomes x, and the colorfulness of the unit increases by |x - y|.DZY wants to perform m operations, each operation can be one of the following:  Paint all the units with numbers between l and r (both inclusive) with color x.  Ask the sum of colorfulness of the units between l and r (both inclusive). Can you help DZY?

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105). Each of the next m lines begins with a integer type (1 ≤ type ≤ 2), which represents the type of this operation. If type = 1, there will be 3 more integers l, r, x (1 ≤ l ≤ r ≤ n; 1 ≤ x ≤ 108) in this line, describing an operation 1. If type = 2, there will be 2 more integers l, r (1 ≤ l ≤ r ≤ n) in this line, describing an operation 2.

For each operation 2, print a line containing the answer — sum of colorfulness.

NoteIn the first sample, the color of each unit is initially [1, 2, 3], and the colorfulness is [0, 0, 0].After the first operation, colors become [4, 4, 3], colorfulness become [3, 2, 0].After the second operation, colors become [4, 5, 5], colorfulness become [3, 3, 2].So the answer to the only operation of type 2 is 8.

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

/**
  * Created by hama_du on 2014/09/01.
  */
object ProblemC extends App {
  val in = new InputReader(System.in)
  val out = new PrintWriter(System.out)

  val n = in.nextInt()
  val m = in.nextInt()
  val seg = new SegmentTree(n)
  seg.init(n)

  for (i <- 0 until m) {
    val t = in.nextInt()
    val l = in.nextInt()-1
    val r = in.nextInt()
    if (t == 1) {
      val x = in.nextInt()
      seg.update(l, r, x)
    } else {
      out.println(seg.range(l, r))
    }
  }
  out.flush()

  // libraries

  class SegmentTree(n: Int) {
    val N = Integer.highestOneBit(n-1)<<1
    val values = new Array[Long](N<<1)
    val color = new Array[Int](N<<1)
    val diff = new Array[Long](N<<1)

    def init(n: Int) {
      Arrays.fill(color, -1)
      for (i <- (N-1) to (N-1+n)) {
        color(i) = i-N+2
      }
    }

    def update(l: Int, r: Int, value: Int) {
      update(l, r, value, -1, 0, 0, N)
    }

    def update(l: Int, r: Int, value: Int, currentColor: Int, idx: Int, fr: Int, to: Int): Long = {
      // update the color
      if (currentColor != -1) {
        color(idx) = currentColor
      }
      val toColor = color(idx)

      if (to <= l || r <= fr) {
        // nothing to do
        0L
      } else {
        var result = 0L
        val med = (fr + to) / 2
        if (l <= fr && to <= r) {
          if (color(idx) == -1) {
            // different color => calculate each of them
            result = update(l, r, value, toColor, (idx<<1)+1, fr, med) + update(l, r, value, toColor, (idx<<1)+2, med, to)
          } else {
            // same color => yeah!!
            val diffColor = Math.abs(value - color(idx)) * 1L
            result = diffColor * (to - fr)
            diff(idx) += diffColor
          }
          color(idx) = value
        } else {
          result = update(l, r, value, toColor, (idx<<1)+1, fr, med) + update(l, r, value, toColor, (idx<<1)+2, med, to)
          color(idx) = -1
        }
        values(idx) += result
        return result
      }
    }

    def range(l: Int, r: Int): Long = {
      range(l, r, 0, 0, N)
    }

    def range(l: Int, r: Int, idx: Int, fr: Int, to: Int): Long = {
      if (to <= l || r <= fr) {
        0L
      } else if (l <= fr && to <= r) {
        values(idx)
      } else {
        val med = (fr + to) / 2
        range(l, r, (idx<<1)+1, fr, med) + range(l, r, (idx<<1)+2, med, to) + diff(idx) * (Math.min(r, to) - Math.max(l, fr))
      }
    }

  }

  class InputReader(stream: InputStream) {
    val buf = new Array[Byte](1024)
    var curChar = 0
    var numChars = 0

    def next(): Int = {
      if (numChars == -1)
        throw new InputMismatchException();
      if (curChar >= numChars) {
        curChar = 0;
        numChars = stream.read(buf);
        if (numChars <= 0) {
          -1;
        }
      }
      val res = buf(curChar)
      curChar += 1
      res
    }

    def nextLong(): Long = {
      var c = next()
      while (isSpaceChar(c)) {
        c = next()
      }
      var sgn = 1
      if (c == '-') {
        sgn = -1
        c = next()
      }
      var res = 0L
      do {
        if (c < '0' || c > '9')
          throw new InputMismatchException()
        res *= 10
        res += c - '0'
        c = next()
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt(): Int = {
      nextLong.toInt
    }

    def isSpaceChar(c: Int) = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
  }

}

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

/**
  * Created by hama_du on 2014/09/01.
  */
object ProblemC extends App {
  val in = new InputReader(System.in)
  val out = new PrintWriter(System.out)

  val n = in.nextInt()
  val m = in.nextInt()
  val seg = new SegmentTree(n)
  seg.init(n)

  for (i <- 0 until m) {
    val t = in.nextInt()
    val l = in.nextInt()-1
    val r = in.nextInt()
    if (t == 1) {
      val x = in.nextInt()
      seg.update(l, r, x)
    } else {
      out.println(seg.range(l, r))
    }
  }
  out.flush()

  // libraries

  class SegmentTree(n: Int) {
    val N = Integer.highestOneBit(n-1)<<1
    val values = new Array[Long](N<<1)
    val color = new Array[Int](N<<1)
    val diff = new Array[Long](N<<1)

    def init(n: Int) {
      Arrays.fill(color, -1)
      for (i <- (N-1) to (N-1+n)) {
        color(i) = i-N+2
      }
    }

    def update(l: Int, r: Int, value: Int) {
      update(l, r, value, -1, 0, 0, N)
    }

    def update(l: Int, r: Int, value: Int, currentColor: Int, idx: Int, fr: Int, to: Int) {
      // update the color
      if (currentColor != -1) {
        color(idx) = currentColor
      }
      val toColor = color(idx)

      if (to <= l || r <= fr) {
        return
      } else {
        val med = (fr + to) / 2
        if (l <= fr && to <= r) {
          if (color(idx) == -1) {
            update(l, r, value, toColor, (idx<<1)+1, fr, med)
            update(l, r, value, toColor, (idx<<1)+2, med, to)
            values(idx) = values((idx << 1) + 1) + values((idx << 1) + 2)
          } else {
            val diffColor = Math.abs(value - color(idx)) * 1L
            diff(idx) += diffColor
            values(idx) += diffColor * (to - fr)
          }
          color(idx) = value
        } else {
          update(l, r, value, toColor, (idx<<1)+1, fr, med)
          update(l, r, value, toColor, (idx<<1)+2, med, to)
          values(idx) = values((idx << 1) + 1) + values((idx << 1) + 2)
          color(idx) = -1
        }
      }
    }

    def range(l: Int, r: Int): Long = {
      range(l, r, 0, 0, N)
    }

    def range(l: Int, r: Int, idx: Int, fr: Int, to: Int): Long = {
      if (to <= l || r <= fr) {
        0L
      } else if (l <= fr && to <= r) {
        values(idx)
      } else {
        val med = (fr + to) / 2
        range(l, r, (idx<<1)+1, fr, med) + range(l, r, (idx<<1)+2, med, to) + diff(idx) * (Math.min(r, to) - Math.max(l, fr))
      }
    }

  }

  class InputReader(stream: InputStream) {
    val buf = new Array[Byte](1024)
    var curChar = 0
    var numChars = 0

    def next(): Int = {
      if (numChars == -1)
        throw new InputMismatchException();
      if (curChar >= numChars) {
        curChar = 0;
        numChars = stream.read(buf);
        if (numChars <= 0) {
          -1;
        }
      }
      val res = buf(curChar)
      curChar += 1
      res
    }

    def nextLong(): Long = {
      var c = next()
      while (isSpaceChar(c)) {
        c = next()
      }
      var sgn = 1
      if (c == '-') {
        sgn = -1
        c = next()
      }
      var res = 0L
      do {
        if (c < '0' || c > '9')
          throw new InputMismatchException()
        res *= 10
        res += c - '0'
        c = next()
      } while (!isSpaceChar(c))
      res * sgn
    }

    def nextInt(): Int = {
      nextLong.toInt
    }

    def isSpaceChar(c: Int) = {
      c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }
  }

}


Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000). The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.

If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.

NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating:  Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7.  With rating 1894 Limak is in the division 2. His rating increases by 5.  Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.

object C extends App {

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

  val Array(n) = readInts(1)
  val cs, ds = Array.ofDim[Int](n)

  for (i <- 0 until n) {
    val Array(c, d) = readInts(2)
    cs(i) = c
    ds(i) = d
  }

  if (ds.forall(_ == 1)) println("Infinity")
  else {

    var max: Long = if (ds.last == 2) 1899L else Int.MaxValue
    var min: Long = if (ds.last == 2) Int.MinValue else 1900L
    var ok = true

    for (i <- n - 2 to 0 by -1) {
      if (ds(i) == 2) {
        max = Math.min(max - cs(i), 1899L)
        min = min - cs(i)
      } else {
        max = max - cs(i)
        min = Math.max(min - cs(i), 1900L)
      }
      if (min > max) ok = false
    }

    for (i <- 0 until n) max += cs(i)

    if (ok) println(max)
    else println("Impossible")
  }
}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def go(n: Int, lower: Int, upper: Int): (Int, Int) = {
      if (n == 0) {
        (lower, upper)
      } else {
        val Array(change, div) = readLine.split(" ").map(_.toInt)
        if (div == 1) go(n - 1, Math.max(lower + change, 1900 + change), upper + change)
        else go(n - 1, lower + change, Math.min(upper + change, 1899 + change))
      }
    }
    val (lower, upper) = go(readInt, -200000000, 200000000)
    println(if (lower > upper) "Impossible" else if (upper > 100000000) "Infinity" else upper)
  }
}

import scala.io.StdIn._

object Solution {
  def main(args: Array[String]): Unit = {
    def go(n: Int, lower: Int, upper: Int): (Int, Int) = {
      if (n == 0) {
        (lower, upper)
      } else {
        val Array(change, div) = readLine.split(" ").map(_.toInt)
        if (div == 1) go(n - 1, Math.max(lower + change, 1900 + change), upper + change)
        else go(n - 1, lower + change, Math.min(upper + change, 1899 + change))
      }
    }
    val (lower, upper) = go(readInt, -200000000, 200000000)
    println(if (lower > upper) "Impossible" else if (upper > 20000000) "Infinity" else upper)
  }
}


A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily $$$7$$$ days!In detail, she can choose any integer $$$k$$$ which satisfies $$$1 \leq k \leq r$$$, and set $$$k$$$ days as the number of days in a week.Alice is going to paint some $$$n$$$ consecutive days on this calendar. On this calendar, dates are written from the left cell to the right cell in a week. If a date reaches the last day of a week, the next day's cell is the leftmost cell in the next (under) row.She wants to make all of the painted cells to be connected by side. It means, that for any two painted cells there should exist at least one sequence of painted cells, started in one of these cells, and ended in another, such that any two consecutive cells in this sequence are connected by side.Alice is considering the shape of the painted cells. Two shapes are the same if there exists a way to make them exactly overlapped using only parallel moves, parallel to the calendar's sides.For example, in the picture, a week has $$$4$$$ days and Alice paints $$$5$$$ consecutive days. [1] and [2] are different shapes, but [1] and [3] are equal shapes.    Alice wants to know how many possible shapes exists if she set how many days a week has and choose consecutive $$$n$$$ days and paints them in calendar started in one of the days of the week. As was said before, she considers only shapes, there all cells are connected by side.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains two integers $$$n$$$, $$$r$$$ ($$$1 \le n \le 10^9, 1 \le r \le 10^9$$$).

For each test case, print a single integer  — the answer to the problem. Please note, that the answer for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

NoteIn the first test case, Alice can set $$$1,2,3$$$ or $$$4$$$ days as the number of days in a week.There are $$$6$$$ possible paintings shown in the picture, but there are only $$$4$$$ different shapes. So, the answer is $$$4$$$. Notice that the last example in the picture is an invalid painting because all cells are not connected by sides.    In the last test case, be careful with the overflow issue, described in the output format.

import scala.io.StdIn._

object B extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val Array(n, r) = readLine().split(" ").map(_.toInt)

    val answer =
      if (n <= r) {
        (n - 1).toLong * (n) / 2 + 1
      } else {
        r.toLong * (r + 1) / 2
      }
    println(answer)
  }
}

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val item = in.nextInt()
      val col  = in.nextInt()

      var ans = 0L

      if (item <= col) {
        val r = (item - 1).toLong
        ans = ans + ((r * (r + 1)) / 2)
      } else if (item > col) {
        val r2 = col.toLong
        ans = ans + ((r2 * (r2 + 1)) / 2)
      }

      if (item <= col) {
        ans = ans + 1
      }

      println(ans)
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}

object B extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

//  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val n = in.nextInt()

    n.times {
      val item = in.nextInt()
      val col  = in.nextInt()

      var ans = 0L

      if (item < col) {
        val r = (item - 1).toLong
        ans = ans + ((r * (r + 1)) / 2)
      } else if (item > col) {
        val r2 = col.toLong
        ans = ans + ((r2 * (r2 + 1)) / 2)
      }

      if (item <= col) {
        ans = ans + 1
      }

      println(ans)
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {

    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = {
      Iterator
        .continually(reader.readLine())
        .takeWhile(_ != null)
        .map(new StringTokenizer(_))
        .filter(_.hasMoreTokens)
    }

    private[this] var current: Option[StringTokenizer] = None

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

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

    override def next(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

    override def close(): Unit = reader.close()
  }
}


Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag).You are given an $$$n \times m$$$ grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those that only share a corner do not count).Your job is to colour the blank cells red or white so that every red cell only has white neighbours (and no red ones) and every white cell only has red neighbours (and no white ones). You are not allowed to recolour already coloured cells.

The first line contains $$$t$$$ ($$$1 \le t \le 100$$$), the number of test cases. In each test case, the first line will contain $$$n$$$ ($$$1 \le n \le 50$$$) and $$$m$$$ ($$$1 \le m \le 50$$$), the height and width of the grid respectively. The next $$$n$$$ lines will contain the grid. Each character of the grid is either 'R', 'W', or '.'.

For each test case, output "YES" if there is a valid grid or "NO" if there is not. If there is, output the grid on the next $$$n$$$ lines. If there are multiple answers, print any. In the output, the "YES"s and "NO"s are case-insensitive, meaning that outputs such as "yEs" and "nO" are valid. However, the grid is case-sensitive.

YES
WRWRWR
RWRWRW
WRWRWR
RWRWRW
NO
YES
R
W
R
W
R

NoteThe answer for the first example case is given in the example output, and it can be proven that no grid exists that satisfies the requirements of the second example case. In the third example all cells are initially coloured, and the colouring is valid.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val anm         = Array.fill(n)(readLine().toCharArray)

    val ans = (0 until n).foldLeft((0, 0), (0, 0)) { case ((r, w), i) =>
      (0 until m).foldLeft(r, w) { case ((r, w), j) =>
        anm(i)(j) match {
          case 'R' => if ((i + j) % 2 == 0) ((1, r._2), w) else ((r._1, 1), w)
          case 'W' => if ((i + j) % 2 == 0) (r, (1, w._2)) else (r, (w._1, 1))
          case _   => (r, w)
        }
      }
    }

    ans match {
      case ((0 | 1, 0), (0, 0 | 1)) =>
        println("YES")
        (0 until n).foreach { i =>
          val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'R' else 'W')
          println(l.mkString(""))
        }
      case ((0, 0 | 1), (0 | 1, 0)) =>
        println("YES")
        (0 until n).foreach { i =>
          val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'W' else 'R')
          println(l.mkString(""))
        }
      case _                => println("NO")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val anm         = Array.fill(n)(readLine().toCharArray)

    val ans = anm.zipWithIndex
      .foldLeft[(Boolean, Option[Int])]((true, None)) {
        case (state @ (true, _), (am, i)) =>
          am.zipWithIndex.foldLeft(state) {
            case ((true, t), (c @ ('R' | 'W'), j)) =>
              val e = (i + j + c) % 2
              (t.getOrElse(e) == e, Some(e))
            case (state, _)                        => state
          }
        case (state, _)                   => state
      }

    ans match {
      case (true, t) =>
        println("YES")
        (0 until n).foreach { i =>
          val l = (0 until m).map(j => if ((i + j) % 2 == t.getOrElse(0)) 'R' else 'W')
          println(l.mkString(""))
        }
      case _         => println("NO")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val anm         = Array.fill(n)(readLine().toCharArray)

    val ans = (0 until n).foldLeft((0, 0), (0, 0)) { case ((r, w), i) =>
      (0 until m).foldLeft(r, w) { case ((r, w), j) =>
        anm(i)(j) match {
          case 'R' => if ((i + j) % 2 == 0) ((1, r._2), w) else ((r._1, 1), w)
          case 'W' => if ((i + j) % 2 == 0) (r, (1, w._2)) else (r, (w._1, 1))
          case _   => (r, w)
        }
      }
    }

    ans match {
      case ((1, 0), (0, 1)) =>
        println("YES")
        (0 until n).foreach { i =>
          val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'R' else 'W')
          println(l.mkString(""))
        }
      case ((0, 1), (1, 0)) =>
        println("YES")
        (0 until n).foreach { i =>
          val l = (0 until m).map(j => if ((i + j) % 2 == 0) 'W' else 'R')
          println(l.mkString(""))
        }
      case _                => println("NO")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(n, m) = readLine().split(" ").map(_.toInt)
    val anm         = Array.fill(n)(readLine().toCharArray)

    val ans = anm.zipWithIndex
      .foldLeft[(Boolean, Option[Int], Option[Int])]((true, None, None)) {
        case (state @ (true, _, _), (am, i)) =>
          am.zipWithIndex.foldLeft(state) {
            case ((_, None, None), ('R', j)) => (true, Some((i + j) % 2), Some((i + j + 1) % 2))
            case ((_, None, None), ('W', j)) => (true, Some((i + j + 1) % 2), Some((i + j) % 2))
            case ((_, Some(r), _), ('R', j)) if (i + j) % 2 != r => (false, None, None)
            case ((_, _, Some(w)), ('W', j)) if (i + j) % 2 != w => (false, None, None)
            case (state, _) => state
          }
        case (state, _)                      => state
      }

    ans match {
      case (true, Some(r), Some(w)) =>
        println("YES")
        (0 until n).foreach { i =>
          val l = (0 until m).map(j => if ((i + j) % 2 == r) 'R' else 'W')
          println(l.mkString(""))
        }
      case _                        => println("NO")
    }
  }
}


Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.

The first line of the input contains a string s (1 ≤ |s| ≤ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.

If there is no way of replacing '#' characters which leads to a beautiful string print  - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.

Note|s| denotes the length of the string s.

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

import scala.annotation.tailrec

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], level : Int = 0) = {
      @tailrec
      def inner (x: List[Char], level : Int, acc : List[Int]) : List[Int] = {
        x match {
          case '(' :: tail => inner(tail, level + 1, level + 1 :: acc)
          case ')' :: tail => inner(tail, level - 1, level - 1 :: acc)
          case _ :: tail => inner(tail, level, level :: acc)
          case Nil => acc.reverse
        }
      }
      inner(x, level, Nil)
    }

    @tailrec def zeroFixer (l : List[Int], acc: Int = 0, accList : List[Int] = Nil) : List[Int] = {
      l match {
        case x :: Nil => (acc + x :: accList).reverse
        case x :: tail => zeroFixer(tail, acc + x - 1, 1 :: accList)
        case Nil => accList.reverse
      }
    }

    @tailrec def stringFiller (hashes: List[Int], str: List[Char], acc : List[Char] = Nil) : List[Char] = {
      str match {
          case '#' :: tail => stringFiller(hashes.tail, tail, (")" * hashes.head).toList ::: acc)
          case x :: tail => stringFiller(hashes, tail, x :: acc)
          case Nil => acc.reverse
      }
    }

    val chars = str.toList
    val charRanks = balanceChecker(chars)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    val hashRankDiffFixed = zeroFixer(hashRankDiffButLast :+ lastItem)
    val strFilledValidation = balanceChecker(stringFiller(hashRankDiffFixed, chars))

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFixed)
    println(strFilledValidation)
    */

    if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    def zeroFixer (l : List[Int], acc: Int) : List[Int] = {
      l match {
        case x :: Nil => acc + x :: Nil
        case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)
        case Nil => Nil
      }
    }

    def stringFiller (hashes: List[Int], str: List[Char]) : List[Char] = {
      str match {
          case '#' :: tail => (")" * hashes.head).toCharArray.toList ::: stringFiller(hashes.tail, tail)
          case x :: tail => x :: stringFiller(hashes, tail)
          case Nil => Nil
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem
    val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)
    val charFilled = stringFiller(hashRankDiffFixed, chars)
    val strFilledValidation = balanceChecker(charFilled, 0)

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    println(hashRankDiffFixed)
    println(charFilled.mkString)
    println(strFilledValidation)
    */

    if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

import scala.annotation.tailrec

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], level : Int) : List[Int] = {
      @tailrec
      def inner (x: List[Char], level : Int, acc : List[Int] = Nil) : List[Int] = {
        x match {
          case '(' :: tail => inner(tail, level + 1, level + 1 :: acc)
          case ')' :: tail => inner(tail, level - 1, level - 1 :: acc)
          case _ :: tail => inner(tail, level, level :: acc)
          case Nil => acc.reverse
        }
      }
      inner(x, level, Nil)
    }

    @tailrec def zeroFixer (l : List[Int], acc: Int, accList : List[Int] = Nil) : List[Int] = {
      l match {
        case x :: Nil => (acc + x :: accList).reverse
        case x :: tail => zeroFixer(tail, acc + x - 1, 1 :: accList)
        case Nil => accList.reverse
      }
    }

    @tailrec def stringFiller (hashes: List[Int], str: List[Char], acc : List[Char] = Nil) : List[Char] = {
      str match {
          case '#' :: tail => stringFiller(hashes.tail, tail, (")" * hashes.head).toCharArray.toList ::: acc)
          case x :: tail => stringFiller(hashes, tail, x :: acc)
          case Nil => acc.reverse
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem
    val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)
    val charFilled = stringFiller(hashRankDiffFixed, chars)
    val strFilledValidation = balanceChecker(charFilled, 0)

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    println(hashRankDiffFixed)
    println(charFilled.mkString)
    println(strFilledValidation)
    */

    if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

object Solution extends App {
  def check(str: String) = {
    var open = 0
    str.foldLeft(0) {
      case (-1, el) => -1
      case (x, ')') => x - 1
      case (x, '(') => x + 1
    }
  }

  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val r = str.lastIndexOf("#")
  val first = str.take(r).replace('#', ')')
  val t = check(first)
  val open = str.count(_ == '(')
  if (t < 1)
    println(-1)
  else {
    val count = str.count(_ == '#')
    val nStr = first + (")" * Math.max(1, 2 * open - str.length + 1)) + str.drop(r + 1)
    if (check(nStr) == 0) {
      println((1 to count - 1).map(_ => 1).mkString("\n"))
      println(2 * open - str.length + 1)
    } else {
      println(-1)
    }
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object A extends App {

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

  val s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false
  var lastAdd = 0

  val lastHash = s.lastIndexOf('#')
  val hashCnt = s.count(_ == '#')
  val openCnt = s.count(_ == '(')
  val closeCnt = s.count(_ == ')')

  for (i <- s.indices) s(i) match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      lastAdd = if (i == lastHash) math.max(1, openCnt - closeCnt - cntsAdd) else 1
      cntsAdd += lastAdd
      cntClose += lastAdd
      if (cntClose > cntOpen) bad = true
  }

  if (bad) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (hashCnt - 1))
    println(lastAdd)
    Console.flush
  }
}

object Main extends App {

  val s = readLine.split("").filter(_ != "")
  val total = s.size
  val open = s.count(_ == "(")
  val close = s.count(_ == ")")
  val hashes = total - (open + close)

  if((open - close) < hashes) {
    println("-1")
    System.exit(0)
  }

  val init = (0, 0, List[Int]())
  val (sum, _, steps) = s.foldLeft(init)({
    case ((sumAcc, hashesAcc, stepsAcc), i) =>
     i match {
        case "(" => (sumAcc + 1, hashesAcc, stepsAcc)
        case ")" =>
          if(sumAcc == 0) {
            println("-1")
            System.exit(0)
            (sumAcc, hashesAcc, stepsAcc)
          } else {
            (sumAcc-1, hashesAcc, stepsAcc)
          }
       case "#" =>
          if(sumAcc == 0) {
            println("-1")
            System.exit(0)
            (sumAcc, hashesAcc, stepsAcc)
          } else if(hashesAcc == hashes - 1) {
            val add = (open - close) - (hashes - 1)
            if(sumAcc < add) {
              println("-1")
              System.exit(0)
              (sumAcc, hashesAcc, stepsAcc)
            } else {
              (sumAcc - add, hashesAcc + 1, add :: stepsAcc)
            }
          } else {
            (sumAcc - 1, hashesAcc + 1, 1 :: stepsAcc)
         }
     }
  })

   if(sum == 0) {
     steps.reverse foreach println
   } else {
     println("-1")
   }

}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    def zeroFixer (l : List[Int], acc: Int) : List[Int] = {
      l match {
        case x :: Nil => acc + x :: Nil
        case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)
        case Nil => Nil
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem
    val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    println(hashRankDiffFixed)
    */

    if (hashRankDiffFull.exists(_ < 0) || hashRankDiffFixed.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {
      out.println(-1)
      return
    }

    if (hashRankDiffButLast.count(_ == 0) < lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
      */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRankDiffButLast.count(_ == 0) < lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum
    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    val str_adapted = str.replaceAll("##", "#(#)")

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str_adapted.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum
    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*
    println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    def zeroFixer (l : List[Int], acc: Int) : List[Int] = {
      l match {
        case x :: Nil => acc + x :: Nil
        case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)
        case Nil => Nil
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    /*println(chars)
    println(charRanks)
    println(hashRankDiffButLast :+ lastItem)
    */

    val hashRankDiffFull = zeroFixer(hashRankDiffButLast :+ lastItem, 0)

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {
      out.println(-1)
      return
    }

    if (hashRankDiffButLast.count(_ == 0) <= lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
      */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#")) {
      out.println("-1")
      return
    }

    val str_adapted = str.replaceAll("##", "#(#)")

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str_adapted.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum
    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*
    println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {
      out.println(-1)
      return
    }

    if (hashRankDiffButLast.count(_ == 0) < lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
      */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

object Solution extends App {
  def check(str: String) = {
    var open = 0
    str.foldLeft(0) {
      case (-1, el) => -1
      case (x, ')') => x - 1
      case (x, '(') => x + 1
    }
  }

  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val r = str.lastIndexOf("#")
  val first = str.take(r).replace('#', ')')
  val t = check(first)
  val open = str.count(_ == '(')
  if (t == -1)
    println(-1)
  else {
    val count = str.count(_ == '#')
    val nStr = first + (")" * (2 * open - str.length + 1)) + str.drop(r + 1)
    if (check(nStr) == 0) {
      println((1 to count - 1).map(_ => 1).mkString("\n"))
      println(2 * open - str.length + 1)
    } else {
      println(-1)
    }
  }
}

object Solution extends App {
  def check(str: String) = {
    var open = 0
    str.foldLeft(0) {
      case (-1, el) => -1
      case (x, ')') => x - 1
      case (x, '(') => x + 1
    }
  }

  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val r = str.lastIndexOf("#")
  val first = str.take(r).replace('#', ')')
  val t = check(first)
  val open = str.count(_ == '(')
  if (t < 1)
    println(-1)
  else {
    val count = str.count(_ == '#')
    val nStr = first + (")" * (2 * open - str.length + 1)) + str.drop(r + 1)
    if (check(nStr) == 0) {
      println((1 to count - 1).map(_ => 1).mkString("\n"))
      println(2 * open - str.length + 1)
    } else {
      println(-1)
    }
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object A extends App {

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

  val s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false
  var lastAdd = 0

  val lastHash = s.lastIndexOf('#')
  val hashCnt = s.count(_ == '#')
  val openCnt = s.count(_ == '(')
  val closeCnt = s.count(_ == ')')

  for (i <- s.indices) s(i) match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      lastAdd = if (i == lastHash) openCnt - closeCnt - hashCnt + 1 else 1
      cntsAdd += lastAdd
      cntClose += lastAdd
      if (cntClose > cntOpen) bad = true
  }

  if (bad || cntClose > cntOpen || lastAdd == 0) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (hashCnt - 1))
    println(lastAdd)
    Console.flush
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object A extends App {

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

  val s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false

  for (c <- s) c match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      cntsAdd += 1
      cntClose += 1
      if (cntClose > cntOpen) bad = true
  }

  if (bad) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (cntsAdd - 1))
    if (cntsAdd > 0) println(cntOpen - cntClose + 1)
    Console.flush
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object A extends App {

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

  val s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false
  var lastAdd = 0

  val lastHash = s.lastIndexOf('#')
  val hashCnt = s.count(_ == '#')
  val openCnt = s.count(_ == '(')
  val closeCnt = s.count(_ == ')')

  for (i <- s.indices) s(i) match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      lastAdd = if (i == lastHash) math.max(1, openCnt - closeCnt - cntsAdd + 1) else 1
      cntsAdd += lastAdd
      cntClose += lastAdd
      if (cntClose > cntOpen) bad = true
  }

  if (bad) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (hashCnt - 1))
    println(lastAdd)
    Console.flush
  }
}


We start with a string $$$s$$$ consisting only of the digits $$$1$$$, $$$2$$$, or $$$3$$$. The length of $$$s$$$ is denoted by $$$|s|$$$. For each $$$i$$$ from $$$1$$$ to $$$|s|$$$, the $$$i$$$-th character of $$$s$$$ is denoted by $$$s_i$$$. There is one cursor. The cursor's location $$$\ell$$$ is denoted by an integer in $$$\{0, \ldots, |s|\}$$$, with the following meaning:   If $$$\ell = 0$$$, then the cursor is located before the first character of $$$s$$$.  If $$$\ell = |s|$$$, then the cursor is located right after the last character of $$$s$$$.  If $$$0 < \ell < |s|$$$, then the cursor is located between $$$s_\ell$$$ and $$$s_{\ell+1}$$$. We denote by $$$s_\text{left}$$$ the string to the left of the cursor and $$$s_\text{right}$$$ the string to the right of the cursor. We also have a string $$$c$$$, which we call our clipboard, which starts out as empty. There are three types of actions:  The Move action. Move the cursor one step to the right. This increments $$$\ell$$$ once.  The Cut action. Set $$$c \leftarrow s_\text{right}$$$, then set $$$s \leftarrow s_\text{left}$$$.  The Paste action. Append the value of $$$c$$$ to the end of the string $$$s$$$. Note that this doesn't modify $$$c$$$. The cursor initially starts at $$$\ell = 0$$$. Then, we perform the following procedure:  Perform the Move action once.  Perform the Cut action once.  Perform the Paste action $$$s_\ell$$$ times.  If $$$\ell = x$$$, stop. Otherwise, return to step 1. You're given the initial string $$$s$$$ and the integer $$$x$$$. What is the length of $$$s$$$ when the procedure stops? Since this value may be very large, only find it modulo $$$10^9 + 7$$$. It is guaranteed that $$$\ell \le |s|$$$ at any time.

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer $$$x$$$ ($$$1 \le x \le 10^6$$$). The second line of each test case consists of the initial string $$$s$$$ ($$$1 \le |s| \le 500$$$). It is guaranteed, that $$$s$$$ consists of the characters "1", "2", "3". It is guaranteed that the sum of $$$x$$$ in a single file is at most $$$10^6$$$. It is guaranteed that in each test case before the procedure will stop it will be true that $$$\ell \le |s|$$$ at any time.

For each test case, output a single line containing a single integer denoting the answer for that test case modulo $$$10^9 + 7$$$.

NoteLet's illustrate what happens with the first test case. Initially, we have $$$s = $$$ 231. Initially, $$$\ell = 0$$$ and $$$c = \varepsilon$$$ (the empty string). The following things happen if we follow the procedure above:  Step 1, Move once: we get $$$\ell = 1$$$.  Step 2, Cut once: we get $$$s = $$$ 2 and $$$c = $$$ 31.  Step 3, Paste $$$s_\ell = $$$ 2 times: we get $$$s = $$$ 23131.  Step 4: $$$\ell = 1 \not= x = 5$$$, so we return to step 1.   Step 1, Move once: we get $$$\ell = 2$$$.  Step 2, Cut once: we get $$$s = $$$ 23 and $$$c = $$$ 131.  Step 3, Paste $$$s_\ell = $$$ 3 times: we get $$$s = $$$ 23131131131.  Step 4: $$$\ell = 2 \not= x = 5$$$, so we return to step 1.   Step 1, Move once: we get $$$\ell = 3$$$.  Step 2, Cut once: we get $$$s = $$$ 231 and $$$c = $$$ 31131131.  Step 3, Paste $$$s_\ell = $$$ 1 time: we get $$$s = $$$ 23131131131.  Step 4: $$$\ell = 3 \not= x = 5$$$, so we return to step 1.   Step 1, Move once: we get $$$\ell = 4$$$.  Step 2, Cut once: we get $$$s = $$$ 2313 and $$$c = $$$ 1131131.  Step 3, Paste $$$s_\ell = $$$ 3 times: we get $$$s = $$$ 2313113113111311311131131.  Step 4: $$$\ell = 4 \not= x = 5$$$, so we return to step 1.   Step 1, Move once: we get $$$\ell = 5$$$.  Step 2, Cut once: we get $$$s = $$$ 23131 and $$$c = $$$ 13113111311311131131.  Step 3, Paste $$$s_\ell = $$$ 1 times: we get $$$s = $$$ 2313113113111311311131131.  Step 4: $$$\ell = 5 = x$$$, so we stop. At the end of the procedure, $$$s$$$ has length $$$25$$$.

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

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

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

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

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

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

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

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

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

object Workspace {
  import Main._
}

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val x = ni()
      val s = ns()
      var slen: Long = s.length
      val prefix = ArrayBuffer[Int]()
      s.foreach { c =>
        prefix += c-'0'
      }

//      val aa = ArrayBuffer[Int]()
      var i = 0
      while(i < x) {
        val times = prefix(i) - 1
//        aa += times + 1
        val t = prefix.length
        if (prefix.length < x) {
          REP(times) { _ =>
            REP(t - i - 1, i + 1) { j =>
              prefix += prefix(j)
            }
          }
        }
        slen += (MOD + slen-i-1) % MOD * times % MOD
        slen %= MOD
        i += 1

//        debug(s"slen:$slen")
//        debug(prefix.mkString)
      }
//      debug(s"times: ${aa.mkString}")
      out.println(slen)
    }
  }
}


Not so long ago, Vlad came up with an interesting function: $$$f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x \bmod a$$$, where $$$\left\lfloor\frac{x}{a}\right\rfloor$$$ is $$$\frac{x}{a}$$$, rounded down, $$$x \bmod a$$$ — the remainder of the integer division of $$$x$$$ by $$$a$$$.For example, with $$$a=3$$$ and $$$x=11$$$, the value $$$f_3(11) = \left\lfloor\frac{11}{3}\right\rfloor + 11 \bmod 3 = 3 + 2 = 5$$$.The number $$$a$$$ is fixed and known to Vlad. Help Vlad find the maximum value of $$$f_a(x)$$$ if $$$x$$$ can take any integer value from $$$l$$$ to $$$r$$$ inclusive ($$$l \le x \le r$$$).

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. This is followed by $$$t$$$ lines, each of which contains three integers $$$l_i$$$, $$$r_i$$$ and $$$a_i$$$ ($$$1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9$$$) — the left and right boundaries of the segment and the fixed value of $$$a$$$.

For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given $$$a$$$.

NoteIn the first sample:  $$$f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 \bmod 3 = 0 + 1 = 1$$$,  $$$f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 \bmod 3 = 0 + 2 = 2$$$,  $$$f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 \bmod 3 = 1 + 0 = 1$$$,  $$$f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 \bmod 3 = 1 + 1 = 2$$$ As an answer, obviously, $$$f_3(2)$$$ and $$$f_3(4)$$$ are suitable.

import scala.io.StdIn.readLine

object Solution {
  def main(args: Array[String]): Unit = {

    def f(nums: Array[Long]) = {
      val l: Long = nums(0)
      val r: Long = nums(1)
      val a: Long = nums(2)

      val q = r / a
      if (l  < q * a) Math.max(q - 1 + a - 1, r / a + r % a)
      else r / a + r % a

    }

    val cases = readLine().toInt
    for (
      i <- 0 until cases;
      s = readLine().split("\\s+").map(_.toLong)
    ) println(f(s))

  }
}


This is the easy version of the problem. The difference between the versions is that in the easy version all prices $$$a_i$$$ are different. You can make hacks if and only if you solved both versions of the problem.Today is Sage's birthday, and she will go shopping to buy ice spheres. All $$$n$$$ ice spheres are placed in a row and they are numbered from $$$1$$$ to $$$n$$$ from left to right. Each ice sphere has a positive integer price. In this version all prices are different.An ice sphere is cheap if it costs strictly less than two neighboring ice spheres: the nearest to the left and the nearest to the right. The leftmost and the rightmost ice spheres are not cheap. Sage will choose all cheap ice spheres and then buy only them.You can visit the shop before Sage and reorder the ice spheres as you wish. Find out the maximum number of ice spheres that Sage can buy, and show how the ice spheres should be reordered.

The first line contains a single integer $$$n$$$ $$$(1 \le n \le 10^5)$$$ — the number of ice spheres in the shop. The second line contains $$$n$$$ different integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$ — the prices of ice spheres.

In the first line print the maximum number of ice spheres that Sage can buy. In the second line print the prices of ice spheres in the optimal order. If there are several correct answers, you can print any of them.

NoteIn the example it's not possible to place ice spheres in any order so that Sage would buy $$$3$$$ of them. If the ice spheres are placed like this $$$(3, 1, 4, 2, 5)$$$, then Sage will buy two spheres: one for $$$1$$$ and one for $$$2$$$, because they are cheap.

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

import scala.annotation.tailrec

object D1 {
  def solve(in: Input, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val arr = Array.fill(n)(in.nextInt())
    java.util.Arrays.sort(arr)
    for (i <- 1 until arr.length by 2) {
      val tmp = arr(i - 1)
      arr(i - 1) = arr(i)
      arr(i) = tmp
    }
    out.println((n - 1) / 2)
    out.println(arr.mkString(" "))
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("5\n1 2 3 4 5", "2\n2 1 4 3 5 ", "Sample"),
    ("1\n1", "0\n1", "Size 1"),
    ("2\n1 2", "0\n2 1", "Size 2"),
    ("3\n1 2 3", "1\n2 1 3", "Size 3"),
    ("4\n1 2 3 4", "1\n2 1 4 3", "Size 4"),
  )

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

  val bn = Array.ofDim[Int](n)

  bn(0) = an(0)
  (1 until n).foreach {
    case i if i % 2 == 0 => bn(i) = an(i - 1)
    case i => bn(i) = an((n - 1) min (i + 1))
  }

  println((n - 1) / 2)
  println(bn.mkString(" "))
}

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

  if (n <= 2) {
    println(0)
    println(an.mkString(" "))
  } else {
    println((n - 1) / 2)

    val bn = Array.ofDim[Int](n)

    bn(0) = an(0)
    (1 until n).foreach {
      case i if i % 2 == 0 => bn(i) = an(i - 1)
      case i => bn(i) = an((n - 1) min (i + 1))
    }

    println(bn.mkString(" "))
  }
}

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

  if (n <= 2) {
    println(n)
    println(an.mkString(" "))
  } else {
    println((n - 1) / 2)

    val bn = Array.ofDim[Int](n)

    bn(0) = an(0)
    (1 until n).foreach {
      case i if i % 2 == 0 => bn(i) = an(i - 1)
      case i => bn(i) = an((n - 1) min (i + 1))
    }

    println(bn.mkString(" "))
  }
}


CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example:  Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example:  $$$7 \mod 3=1$$$, because $$$7 = 3 \cdot 2 + 1$$$,  $$$15 \mod 4=3$$$, because $$$15 = 4 \cdot 3 + 3$$$.

The input consists of multiple test cases.  The first line contains an integer $$$t (t \geq 1)$$$ — the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $$$n(1 \leq n \leq 10^5)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$

For each test case, print the answer in a single line.

object A extends App {

  lazy val Mod = 1000000007L

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n   = nextInt()
    val ans = (3 to 2 * n).foldLeft(1L)((f, i) => (f * i) % Mod)

    out.println(ans)
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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

}

import scala.io.StdIn._

object A extends App {
  def factorial(n: Long): Long = {
    var f = 1L
    for(i <- 3 to n.toInt)
      f = (f * i) % 1000000007
    f
  }

  (1 to readInt()).foreach(_ => {
    println(((factorial(2L*readLong()))))
  })
}

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

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

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }

    val mod = 1000000007
    var d = new Array[Long](100010)
    d(1) = 1
    for (i <- 2 to 100000) {
        d(i) = d(i-1) * (2*i-1).toLong
        d(i) %= mod
        d(i) *= (2*i).toLong
        d(i) %= mod
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        writer.println(d(n))
    }
    writer.flush()
}

object A extends App {

  lazy val Mod = 1000000007L

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n   = nextInt()
    val ans = (3 to n).foldLeft(1L)((f, i) => (f * i) % Mod)

    out.println(ans)
  }

  out.flush()

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

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

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

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

    def nextLine() = in.readLine()

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

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

}