Recently, Tokitsukaze found an interesting game. Tokitsukaze had $$$n$$$ items at the beginning of this game. However, she thought there were too many items, so now she wants to discard $$$m$$$ ($$$1 \le m \le n$$$) special items of them.These $$$n$$$ items are marked with indices from $$$1$$$ to $$$n$$$. In the beginning, the item with index $$$i$$$ is placed on the $$$i$$$-th position. Items are divided into several pages orderly, such that each page contains exactly $$$k$$$ positions and the last positions on the last page may be left empty.Tokitsukaze would do the following operation: focus on the first special page that contains at least one special item, and at one time, Tokitsukaze would discard all special items on this page. After an item is discarded or moved, its old position would be empty, and then the item below it, if exists, would move up to this empty position. The movement may bring many items forward and even into previous pages, so Tokitsukaze would keep waiting until all the items stop moving, and then do the operation (i.e. check the special page and discard the special items) repeatedly until there is no item need to be discarded.    Consider the first example from the statement: $$$n=10$$$, $$$m=4$$$, $$$k=5$$$, $$$p=[3, 5, 7, 10]$$$. The are two pages. Initially, the first page is special (since it is the first page containing a special item). So Tokitsukaze discards the special items with indices $$$3$$$ and $$$5$$$. After, the first page remains to be special. It contains $$$[1, 2, 4, 6, 7]$$$, Tokitsukaze discards the special item with index $$$7$$$. After, the second page is special (since it is the first page containing a special item). It contains $$$[9, 10]$$$, Tokitsukaze discards the special item with index $$$10$$$. Tokitsukaze wants to know the number of operations she would do in total.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 10^{18}$$$, $$$1 \le m \le 10^5$$$, $$$1 \le m, k \le n$$$) — the number of items, the number of special items to be discarded and the number of positions in each page. The second line contains $$$m$$$ distinct integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_1 < p_2 < \ldots < p_m \le n$$$) — the indices of special items which should be discarded.

Print a single integer — the number of operations that Tokitsukaze would do in total.

NoteFor the first example:  In the first operation, Tokitsukaze would focus on the first page $$$[1, 2, 3, 4, 5]$$$ and discard items with indices $$$3$$$ and $$$5$$$;  In the second operation, Tokitsukaze would focus on the first page $$$[1, 2, 4, 6, 7]$$$ and discard item with index $$$7$$$;  In the third operation, Tokitsukaze would focus on the second page $$$[9, 10]$$$ and discard item with index $$$10$$$. For the second example, Tokitsukaze would focus on the second page $$$[6, 7, 8, 9, 10]$$$ and discard all special items at once.

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 solve(): Unit = {
    val _ = nl()
    val N = ni()
    val K = nl()
    val P = nal(N)
    REP(N) { i =>
      P(i) -= 1
    }

    var p = 0
    var ans = 0
    while(p < N) {
      val m = (P(p) - p) % K
      val remain = K - 1 - m
      var i = 0
      while(p + i + 1 < N && P(p + i + 1) - P(p) <= remain) {
        i += 1
      }
      debug(s"[$p, ${p+i}]")
      p += i + 1
      ans += 1
    }

    out.println(ans)
  }
}


Suppose you have two points $$$p = (x_p, y_p)$$$ and $$$q = (x_q, y_q)$$$. Let's denote the Manhattan distance between them as $$$d(p, q) = |x_p - x_q| + |y_p - y_q|$$$.Let's say that three points $$$p$$$, $$$q$$$, $$$r$$$ form a bad triple if $$$d(p, r) = d(p, q) + d(q, r)$$$.Let's say that an array $$$b_1, b_2, \dots, b_m$$$ is good if it is impossible to choose three distinct indices $$$i$$$, $$$j$$$, $$$k$$$ such that the points $$$(b_i, i)$$$, $$$(b_j, j)$$$ and $$$(b_k, k)$$$ form a bad triple.You are given an array $$$a_1, a_2, \dots, a_n$$$. Calculate the number of good subarrays of $$$a$$$. A subarray of the array $$$a$$$ is the array $$$a_l, a_{l + 1}, \dots, a_r$$$ for some $$$1 \le l \le r \le n$$$.Note that, according to the definition, subarrays of length $$$1$$$ and $$$2$$$ are good.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It's guaranteed that the sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print the number of good subarrays of array $$$a$$$.

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

  type P = (Int, Int)

  def d(p: P, q: P): Int = math.abs(p._1 - q._1) + math.abs(p._2 - q._2)

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)

    val ans = (0 until n).foldLeft(0) { case (count, i) =>
      (i until n).takeWhile {
        case j if i + 2 <= j =>
          val r = (j, an(j))

          (i until j).forall { k =>
            val p = (k, an(k))

            ((k + 1) until j).forall { t =>
              val q = (t, an(t))

              d(p, r) != d(p, q) + d(q, r)
            }
          }
        case _               => true
      }.length + count
    }

    println(ans)
  }
}


YouKn0wWho has an integer sequence $$$a_1, a_2, \ldots a_n$$$. Now he will split the sequence $$$a$$$ into one or more consecutive subarrays so that each element of $$$a$$$ belongs to exactly one subarray. Let $$$k$$$ be the number of resulting subarrays, and $$$h_1, h_2, \ldots, h_k$$$ be the lengths of the longest increasing subsequences of corresponding subarrays.For example, if we split $$$[2, 5, 3, 1, 4, 3, 2, 2, 5, 1]$$$ into $$$[2, 5, 3, 1, 4]$$$, $$$[3, 2, 2, 5]$$$, $$$[1]$$$, then $$$h = [3, 2, 1]$$$.YouKn0wWho wonders if it is possible to split the sequence $$$a$$$ in such a way that the bitwise XOR of $$$h_1, h_2, \ldots, h_k$$$ is equal to $$$0$$$. You have to tell whether it is possible.The longest increasing subsequence (LIS) of a sequence $$$b_1, b_2, \ldots, b_m$$$ is the longest sequence of valid indices $$$i_1, i_2, \ldots, i_k$$$ such that $$$i_1 \lt i_2 \lt \ldots \lt i_k$$$ and $$$b_{i_1} \lt b_{i_2} \lt \ldots \lt b_{i_k}$$$. For example, the LIS of $$$[2, 5, 3, 3, 5]$$$ is $$$[2, 3, 5]$$$, which has length $$$3$$$.An array $$$c$$$ is a subarray of an array $$$b$$$ if $$$c$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$)  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print "YES" (without quotes) if it is possible to split into subarrays in the desired way, print "NO" (without quotes) otherwise. You can print each letter in any register (upper or lower).

NoteIn the first test case, YouKn0wWho can split the sequence in the following way: $$$[1, 3, 4]$$$, $$$[2, 2]$$$, $$$[1, 5]$$$. This way, the LIS lengths are $$$h = [3, 1, 2]$$$, and the bitwise XOR of the LIS lengths is $$$3 \oplus 1 \oplus 2 = 0$$$.In the second test case, it can be shown that it is impossible to split the sequence into subarrays that will satisfy the condition.

object B extends App {

  def xorSpeciaLISt(xs: IndexedSeq[Int]): Boolean =
    xs.length % 2 == 0 || xs.indices.tail.exists { i => xs(i) <= xs(i - 1) }

  import InOut._

  val t = nextInt()

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

    xorSpeciaLISt(an) match {
      case true  => out.println("YES")
      case false => out.println("NO")
    }
  }

  out.flush()

  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 = _

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

}

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

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

    case class pair(var minl: Int, var maxl:  Int, var minr: Int, var maxr:  Int, var ind:  Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return minl.compareTo(that.minl)
        }
    }
    val rem = 1000000007
    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        val arr = new Array[Int](n+1)
        var flag = false
        for (i <- 1 to n) {
            arr(i) = readInt()
            if (i > 1 && arr(i) <= arr(i-1))
                flag = true
        }
        if (n % 2 == 0) {
            writer.println("YES")
        } else {
            if (flag)
                writer.println("YES")
            else
                writer.println("NO")
        }
    }
    writer.flush()
}


A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from $$$1$$$ to $$$9$$$ (inclusive) are round.For example, the following numbers are round: $$$4000$$$, $$$1$$$, $$$9$$$, $$$800$$$, $$$90$$$. The following numbers are not round: $$$110$$$, $$$707$$$, $$$222$$$, $$$1001$$$.You are given a positive integer $$$n$$$ ($$$1 \le n \le 10^4$$$). Represent the number $$$n$$$ as a sum of round numbers using the minimum number of summands (addends). In other words, you need to represent the given number $$$n$$$ as a sum of the least number of terms, each of which is a round number.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. Each test case is a line containing an integer $$$n$$$ ($$$1 \le n \le 10^4$$$).

Print $$$t$$$ answers to the test cases. Each answer must begin with an integer $$$k$$$ — the minimum number of summands. Next, $$$k$$$ terms must follow, each of which is a round number, and their sum is $$$n$$$. The terms can be printed in any order. If there are several answers, print any of them.

import scala.io.StdIn

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    var n = StdIn.readLine().toInt
    var ans = List.empty[Int]
    if(n == 10000) {
      println(1)
      println(n)
    } else {
      if (n / 1000 != 0) {
        val x = (n / 1000) * 1000
        ans = (x :: ans)
        n = n - x
      }
      if (n / 100 != 0) {
        val x = (n / 100) * 100
        ans = (x :: ans)
        n = n - x
      }
      if(n / 10 != 0){
        val x = (n / 10) * 10
        ans = (x :: ans)
        n = n - x
      }
      if(n != 0){
        ans = n :: ans
      }
      println(ans.size)
      ans.foreach(x => print(s"$x "))
      println()
    }
  }
}

import scala.annotation.tailrec
import scala.io.StdIn

object Main {
   def main(args: Array[String]): Unit = {
      val count = StdIn.readInt()
      (0 until count)
        .map(_ => StdIn.readInt())
        .map(x => extractLocal(x))
        .foreach(x => {
             println(x.length)
             x.foreach(y => print(y.toString() + ' '))
             println()
          })
   }

   @tailrec
   def extractLocal(s: Int, result: List[Int] = Nil): List[Int] = {
     if (s == 0) {
       result
     } else if (s < 10) {
       s :: result
     } else {
       val min = findMin(s)
       val mod = s % min
       if (min < 10) min :: result
       else extractLocal(mod, (s - mod) :: result)
     }
   }

   def findMin(s: Int) =
     if (s > 1000) 1000
     else if (s > 100) 100
     else if (s > 10) 10
     else s

}

import scala.annotation.tailrec
import scala.io.StdIn

object A {

   @tailrec
   def ks(n: Int, acc: Seq[Int], l: Int): Seq[Int] =
      if (n < 10) acc :+ (n * l) else {
         ks(n / 10, acc ++ Some(n % 10).filter(_ != 0).map(_ * l), l * 10)
      }

   def solution(n: Int): Seq[Int] = {
      ks(n, Seq.empty, 1)
   }

   def main(args: Array[String]): Unit = {
      for (_ <- (0 until StdIn.readLine().toInt)) {
         val result = A.solution(StdIn.readLine().toInt)
         println(result.length)
         println(result.mkString(" "))
      }
   }
}

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

import scala.collection.immutable
import scala.collection.mutable.ListBuffer
import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t =ni()
    REP(t) { _ =>
      val n = ni()
      var x = n
      var tens = 1
      val ls = new ListBuffer[Int]
      while (x > 0) {
        val r = x % 10
        if(r * tens > 0) ls += r * tens
        tens *= 10
        x /= 10
      }
      out.println(ls.length)
      out.println(ls.mkString(" "))
    }
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readLine()
    val l  = n.length()
    val rs = n.zipWithIndex.filterNot(_._1 == '0').map { case (c, i) => (c - 48) * math.pow(10, l - i - 1).toInt }

    println(rs.length)
    println(rs.mkString(" "))
  }
}

object A extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readLine()
    val rs = n.reverse.zipWithIndex
      .collect { case (c, i) if c != '0' => (c - 48) * math.pow(10, i).toInt }

    println(rs.length)
    println(rs.mkString(" "))
  }
}

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

  override def solve(io: IO) = io.repeat {
    val n = io.read[Int].toString.reverse

    val ans = n.indices collect {
      case i if n(i) - '0' > 0 => n(i) + ("0" * i)
    }

    io.writeLine(ans.length).writeAll(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def solve(io: IO): Any
  def main(args: Array[String]): Unit = {
    val io = new IO(System.in, System.out)
    try solve(io) finally io.close()
  }
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

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

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

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

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

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

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

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

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

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

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

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

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

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

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

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

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

import scala.io.StdIn.readInt

object Scala {
        def main(args: Array[String]): Unit = {
                var t: Int = readInt()
                while (t > 0) {
                        var x: Int = readInt()
                        var sum: Int = 1;
                        var ls: Array[Int] = Array()
                        while (x > 0) {
                                var m: Int = x % 10
                                if(m > 0) {
                                        ls = ls :+ (sum * m)
                                }
                                x /= 10
                                sum = sum * 10;
                        }
                        println(ls.length)
                        for(i <- ls) {
                                print(s"$i ")
                        }
                        println()
                        t -= 1
                }
        }
}

object C extends App {

  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val x = scala.io.StdIn.readLine()
    println(x.filter(_ != '0').length)
    val m = x.zipWithIndex.collect {
        case (e,i) if(e != '0') => {
                e.asDigit * math.pow(10, x.length-i-1).toInt
            }
    }.mkString(" ")
    println(m)
  }
}

import scala.io.StdIn._

object Main2 extends App {
  val testNumber = readInt()
  1.to(testNumber).foreach {_ =>
    var digit = readInt()
    var answers: Vector[Int] = Vector()
    var divisor = 10
    while (digit > 0) {
      val answer = digit % divisor
      if (answer != 0) answers +:= answer
      digit = digit - answer
      divisor *= 10
    }
    println(answers.size)
    println(answers.mkString(" "))
  }
}

object ProblemA extends App {
  import java.io.{BufferedReader, IOException, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer

  val in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)))
  val out = new PrintWriter(System.out)

  class FastScanner(val in: BufferedReader) {
    var st: StringTokenizer = _;

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

    def nextInt(): Integer = {
      Integer.parseInt(nextToken());
    }

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

    def nextDouble(): Double = {
      nextToken().toDouble;
    }
  }

  val n = in.nextInt()

  def solve(integer: Integer, step: Int = 1, res: List[Int] = List()): Unit = {
    if (integer == 0) {
      println(res.size)
      println(res.mkString(" "))
    } else {
      val k = integer % 10
      if (k != 0) {
        solve(integer / 10, step * 10, k * step :: res)
      } else {
        solve(integer / 10, step * 10, res)
      }
    }
  }

  for (i <- 1 to n) {
    val m = in.nextInt()
    solve(m)
  }

}

import scala.io.StdIn

object Test extends App {

  val s = StdIn.readLine().toInt
  (1 to s).foreach{_ =>
    var n = StdIn.readLine().toInt
    var ans = List.empty[Int]
    if(n == 10000)println(n) else {
      if (n / 1000 != 0) {
        val x = (n / 1000) * 1000
        ans = (x :: ans)
        n = n - x
      }
      if (n / 100 != 0) {
        val x = (n / 100) * 100
        ans = (x :: ans)
        n = n - x
      }
      if(n / 10 != 0){
        val x = (n / 10) * 10
        ans = (x :: ans)
        n = n - x
      }
      if(n != 0){
        ans = n :: ans
      }
      println(ans.size)
      ans.foreach(x => print(s"$x "))
      println()
    }
  }
}

import scala.io.StdIn.readInt

object Scala {
        def main(args: Array[String]): Unit = {
                var t: Int = readInt()
                while (t > 0) {
                        var x: Int = readInt()
                        var sum: Int = 1;
                        while (x > 0) {
                                var m: Int = x % 10
                                if(m > 0) {
                                        print(s"${sum * m} ")
                                }
                                x /= 10
                                sum = sum * 10;
                        }
                        println()
                        t -= 1
                }
        }
}


Nikephoros and Polycarpus play rock-paper-scissors. The loser gets pinched (not too severely!).Let us remind you the rules of this game. Rock-paper-scissors is played by two players. In each round the players choose one of three items independently from each other. They show the items with their hands: a rock, scissors or paper. The winner is determined by the following rules: the rock beats the scissors, the scissors beat the paper and the paper beats the rock. If the players choose the same item, the round finishes with a draw.Nikephoros and Polycarpus have played n rounds. In each round the winner gave the loser a friendly pinch and the loser ended up with a fresh and new red spot on his body. If the round finished in a draw, the players did nothing and just played on.Nikephoros turned out to have worked out the following strategy: before the game began, he chose some sequence of items A = (a1, a2, ..., am), and then he cyclically showed the items from this sequence, starting from the first one. Cyclically means that Nikephoros shows signs in the following order: a1, a2, ..., am, a1, a2, ..., am, a1, ... and so on. Polycarpus had a similar strategy, only he had his own sequence of items B = (b1, b2, ..., bk).Determine the number of red spots on both players after they've played n rounds of the game. You can consider that when the game began, the boys had no red spots on them.

The first line contains integer n (1 ≤ n ≤ 2·109) — the number of the game's rounds. The second line contains sequence A as a string of m characters and the third line contains sequence B as a string of k characters (1 ≤ m, k ≤ 1000). The given lines only contain characters "R", "S" and "P". Character "R" stands for the rock, character "S" represents the scissors and "P" represents the paper.

Print two space-separated integers: the numbers of red spots Nikephoros and Polycarpus have.

NoteIn the first sample the game went like this:  R - R. Draw.  P - S. Nikephoros loses.  S - P. Polycarpus loses.  R - P. Nikephoros loses.  P - R. Polycarpus loses.  S - S. Draw.  R - P. Nikephoros loses. Thus, in total Nikephoros has 3 losses (and 3 red spots), and Polycarpus only has 2.

import java.io._

object Solution {
  def main(args: Array[String]) {
    val in = new BufferedReader(new InputStreamReader(System.in))
    def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a % b)
    def lcm(a: Int, b: Int) = a * b / gcd(a, b)
    val rounds = in.readLine.toInt
    val A = in.readLine
    val B = in.readLine
    val period = lcm(A.length, B.length)
    val xa = new Array[Int](period + 1)
    val xb = new Array[Int](period + 1)
    for(i <- 1 to period) {
      val a = A((i - 1) % A.length)
      val b = B((i - 1) % B.length)
      def win(x: Char, y: Char) = if(x == 'R' && y == 'S' || x == 'S' && y == 'P' || x == 'P' && y == 'R') 1 else 0
      xa(i) = xa(i - 1) + win(b, a)
      xb(i) = xb(i - 1) + win(a, b)
    }
    val full = rounds / period
    val rest = rounds % period
    println("%d %d".format(full * xa.last + xa(rest), full * xb.last + xb(rest)))
  }
}


Permutation p is an ordered set of integers p1,   p2,   ...,   pn, consisting of n distinct positive integers not larger than n. We'll denote as n the length of permutation p1,   p2,   ...,   pn.Your task is to find such permutation p of length n, that the group of numbers |p1 - p2|, |p2 - p3|, ..., |pn - 1 - pn| has exactly k distinct elements.

The single line of the input contains two space-separated positive integers n, k (1 ≤ k < n ≤ 105).

Print n integers forming the permutation. If there are multiple answers, print any of them.

NoteBy |x| we denote the absolute value of number x.

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

object Main {

  val br = new BufferedReader(new InputStreamReader(System.in))
  var st = new StringTokenizer(br.readLine())

  def nextDouble = next.toDouble
  def nextLong = next.toLong
  def nextInt = next.toInt

  def next = {
    while (!st.hasMoreTokens)
      st = new StringTokenizer(br.readLine())
    st.nextToken()
  }

  def main(args: Array[String]) {
    val n = nextInt
    val k = nextInt

    var inc = -1
    var cur = n
    print(n + " ")
    for (i <- k to 1 by -1) {
      cur += inc * i
      print(cur + " ")
      inc = -inc
    }
    for (i <- n - k - 1 to 1 by -1)
      print(i + " ")
  }

}

import java.util.StringTokenizer

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

object _482A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt

  if (k == 1) println((1 to n).mkString(" "))
  else {
    // e.g. n = 8
    // 2 3 4 5 6 7 |8 1    <- k = 2
    // 7 6 5 4 3 |2 8 1    <- k = 3
    // 3 4 5 6 |7 2 8 1    <- k = 4
    // 6 5 4 |3 7 2 8 1    <- k = 5
    // 4 5 |6 3 7 2 8 1    <- k = 6
    // 5 |4 6 3 7 2 8 1    <- k = 7

    //e.g. n = 5
    // 2 3 4 5 1
    // 4 3 2 5 1
    // 3 4 2 5 1

    val ans = new ArrayBuilder.ofInt
    ans += 1
    ans += n

    def doit(i: Int, pre: Int, left: Int, right: Int) {
      if (i < n) {
        if (i >= k) {
          if ((pre - left).abs == 1) {
            ans += left
            doit(i + 1, left, left + 1, right)
          } else {
            ans += right
            doit(i + 1, right, left, right - 1)
          }
        } else {
          if (i % 2 == 0) {
            ans += left
            doit(i + 1, left, left + 1, right)
          } else {
            ans += right
            doit(i + 1, right, left, right - 1)
          }
        }
      }
    }

    doit(2, n, 2, n - 1)
    println(ans.result().mkString(" "))
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, k) = in.next().split(" ").map(_.toInt)
  val r = (0 until k).map { i =>
    if (i % 2 != 0) n - i / 2
    else i / 2 + 1
  }.toList
  val d = r.last
  val z = (k until n).map {
    i => if (d > n / 2) d - i + k - 1
      else d + i - k + 1
  }.toList
  println((r ::: z).mkString(" "))
}

import scala.io.StdIn.readLine
object Main {
    def main(args: Array[String]): Unit = {
      val lines = readLine.split(" ").map(_.toInt)
      val n = lines(0)
      val k = lines(1)
      if (k == 1) {
        print((1 to n).mkString(" "))
      }
      else {
        var a = 1
        var b = n

        for (i <- 1 to k/2) {
            print(b + " " + a + " ")
            a += 1
            b -= 1

        }

        if (k%2 != 0) {
            print((a to b).reverse.mkString(" "))
        }
        else {
            print((a to b).mkString(" "))
        }

      }

    }

}

import scala.collection._

object A extends App {

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

  val Array(n, k) = readLongs(2)

  var l = 1l
  var r = n

  val res = new mutable.ArrayBuilder.ofLong

  res += l
  l += 1

  for (i <- 1l until k) {
    if (i % 2 == 1) {
      res += r
      r -= 1
    } else {
      res += l
      l += 1
    }
  }

  if (k % 2 == 0) {
    for (i <- k + 1 to n) {
      res += r
      r -= 1
    }
  } else {
    for (i <- k + 1 to n) {
      res += l
      l += 1
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.result.mkString(" "))
  Console.flush

}

import java.util.StringTokenizer

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

object _482A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val k = next.toInt

  if (k == 1) println((1 to n).mkString(" "))
  else {
    // e.g. n = 8
    // 2 3 4 5 6 7 |8 1    <- k = 2
    // 7 6 5 4 3 |2 8 1    <- k = 3
    // 3 4 5 6 |7 2 8 1    <- k = 4
    // 6 5 4 |3 7 2 8 1    <- k = 5
    // 4 5 |6 3 7 2 8 1    <- k = 6
    // 5 |4 6 3 7 2 8 1    <- k = 7

    //e.g. n = 5
    // 2 3 4 5 1
    // 4 3 2 5 1
    // 3 4 2 5 1

    val ans = new ArrayBuilder.ofInt
    ans += 1
    ans += n

    def doit(i: Int, left: Int, right: Int) {
      if (i < n) {
        if (i % 2 == 0) {
          ans += left
          doit(i + 1, left + 1, right)
        } else {
          ans += right
          doit(i + 1, left, right - 1)
        }
      }
    }

    doit(2, 2, n - 1)
    println(ans.result().mkString(" "))
  }
}

import scala.io.StdIn.readLine
object Main {
    def main(args: Array[String]): Unit = {
      val lines = readLine.split(" ").map(_.toInt)
      val n = lines(0)
      val k = lines(1)
      if (k == 1) {
        print((1 to n).mkString(" "))
      }
      else {
        var a = 1
        var b = n

        for (i <- 1 to k/2) {
            print(b + " " + a)
            a += 1
            b -= 1
        }
        print(" ")
        if (k%2 != 0) {
            print((a to b).reverse.mkString(" "))
        }
        else {
            print((a to b).mkString(" "))
        }

      }

    }

}

import scala.collection._

object A extends App {

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

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

  var x = 1L

  val res = new mutable.ArrayBuilder.ofLong

  res += x
  for (i <- 1 to k) {
    x += i
    res += x
  }

  for (i <- k + 2 to n) {
    x += 1
    res += x
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.result.mkString(" "))
  Console.flush

}

import scala.collection._

object A extends App {

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

  val Array(n, k) = readLongs(2)

  var l = 1l
  var r = n

  val res = new mutable.ArrayBuilder.ofLong

  res += l
  l += 1

  for (i <- 1l until k) {
    if (i % 2 == 1) {
      res += r
      r -= 1
    } else {
      res += l
      l += 1
    }
  }

  for (i <- k + 1 to n) {
    res += l
    l += 1
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))
  println(res.result.mkString(" "))
  Console.flush

}


Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.

The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way.

Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.

NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed.

import collection.mutable

object A {
	def main(args: Array[String]) {
		val n = readLine().toInt
    val a = readLine().split(" ").map(x => x.toInt)
    val b = new mutable.HashMap[Int, Int]
    for (x <- a) {
      if (!b.contains(x))
        b(x) = 0
      b(x) += 1
    }
    var good = true
    var ans = 0
    for (x <- b.keySet if x > 0) {
      if (b(x) > 2)
        good = false
      if (b(x) == 2)
        ans += 1
    }
    if (good)
      println(ans)
    else
      println(-1)
	}
}

import collection.mutable

/**
 * Created by antonkov on 9/17/15.
 */
object A {
  def main (args: Array[String]) {
    val n = readLine().toInt
    val a = readLine().split(" ").map(x => x.toInt)
    val b = new mutable.HashMap[Int, Int]
    for (x <- a) {
      if (!b.contains(x))
        b(x) = 0
      b(x) += 1
    }
    var good = true
    var ans = 0
    for (x <- b.keySet if x > 0) {
      if (b(x) > 2)
        good = false
      if (b(x) == 2)
        ans += 1
    }
    if (good)
      println(ans)
    else
      println(-1)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt).filter(_ != 0)
  val enhanced = data.groupBy(x => x).map(x => x._1 -> x._2.length)
  if (enhanced.exists(_._2 > 2))
    println(-1)
  else
    println(enhanced.count(_._2 == 2))
}

/*
A. Разговоры в Spyke
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Поликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.

Как-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.

Помогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.

Обратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.
Входные данные

В первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.

Считайте, что секретари пронумерованы от 1 до n некоторым образом.
Выходные данные

Выведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.
Примеры тестов
Входные данные

6
0 1 7 1 7 10

Выходные данные

2

Входные данные

3
1 1 1

Выходные данные

-1

Входные данные

1
0

Выходные данные

0

Примечание

В первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.

Во втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.

 */
object Task1 extends App {

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(n: Int, ids: IndexedSeq[Long]): Int =
    if (ids.size != n) -1
    else {
      val grouped = ids groupBy (x => x)
      val counts = ((grouped - 0).values map (_.length) toIndexedSeq)
      val dist = counts filterNot (_ < 2)
      if (dist exists (_ > 2)) -1 else dist.size
    }

  val (line1, line2) = (readLine, readLine)
  val n = line1.toInt
  val ids = line2 split (' ') map (_.toLong)

  val res = solve(n, ids)
  println(res)
}

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

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

  val N = sc.nextInt
  val gs = List.fill(N)(sc.nextInt).filterNot(_ == 0).groupBy(identity[Int]).map(_._2.length)

  val answer: Int = {
    gs.find(_ > 2) match {
      case Some(_) => -1
      case None => gs.filter(_ == 2).size
    }
  }

  out.println(answer)
  out.close
}

import io.Source
import java.io.PrintWriter

object CF291A {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val a = in(n).map(_.toInt).filter(_ != 0).toSeq
    val sizes = a.groupBy(identity).toSeq.map(_._2.size)
    if (sizes.exists(_ > 2)) {
      out.println(-1)
    } else {
      out.println(sizes.count(_ == 2))
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ;
    var b = a.distinct.filter(_>0) map (x => a.count(_==x));
    if (b exists(_>2)) println(-1)
    else println(b count(_==2))
  }
}

object Main {
  def main(args: Array[String]) {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val map = scala.collection.mutable.Map[Int, Int]()
    a.foreach(id => if (id != 0) map(id) = map.getOrElse(id, 0) + 1)
    val r = map.values.foldLeft(0) { (acc, count) =>
      if (count == 2 && acc != -1) acc + 1
      else if (count > 2) -1
      else acc
    }
    println(r)
  }
}

import scala.io.StdIn

object Main {
  def main(args: Array[String]): Unit = {
    StdIn.readInt()

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

    val map = arr.foldLeft(Map[Int, Int]())(foldArr) - 0

    val ans = map.find({case (_, value) => value > 2}) match {
      case None => map.foldLeft(0)({(m: Int, x: (Int, Int)) => m + x._2 - 1})
      case Some(_) => -1
    }

    println(ans)
  }

  def foldArr(map: Map[Int, Int], x: Int): Map[Int, Int] = map.updated(x, map.getOrElse(x, 0) + 1)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val enhanced = data.groupBy(x => x).map(x => x._1 -> x._2.length)
  if (enhanced.exists(_._2 > 2))
    println(-1)
  else
    println(enhanced.count(_._2 == 2))
}

/*
A. Разговоры в Spyke
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Поликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.

Как-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.

Помогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.

Обратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.
Входные данные

В первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.

Считайте, что секретари пронумерованы от 1 до n некоторым образом.
Выходные данные

Выведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.
Примеры тестов
Входные данные

6
0 1 7 1 7 10

Выходные данные

2

Входные данные

3
1 1 1

Выходные данные

-1

Входные данные

1
0

Выходные данные

0

Примечание

В первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.

Во втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.

 */
object Task1 extends App {

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(n: Int, ids: IndexedSeq[Int]): Int = {
    val grouped = ids groupBy (x => x)
    val counts = (grouped.values map (_.length) toIndexedSeq)
    val dist = counts filterNot (_ == 1)
    if (dist exists (_ > 2)) -1 else dist.size
  }

  val (line1, line2) = (readLine, readLine)
  val n = line1.toInt
  val ids = line2 split (' ') map (_.toInt)

  val res = solve(n, ids)
  println(res)
}

/*
A. Разговоры в Spyke
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Поликарп — директор большой корпорации. В этой корпорации работает n секретарей, каждый из которых пользуется известной VoIP-системой Spyke для ведения переговоров в течение рабочего дня. Известно, что, когда два человека устанавливают телефонное соединение Spyke, сеть Spyke присваивает этому разговору уникальный идентификационный номер (целое положительное число) — номер сессии.

Как-то раз Поликарп захотел узнать, кто из секретарей разговаривает по Spyke, а кто — нет. Он выписал для каждого секретаря номер сессии его разговора, или 0, если этот секретарь сейчас не разговаривает по Spyke.

Помогите Поликарпу по этим данным определить, сколько пар секретарей сейчас ведут разговор между собой. Если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти, требуется сообщить об этом.

Обратите внимание, секретари могут разговаривать по Spyke не только друг с другом — возможны разговоры с внешними собеседниками. Также не разрешены конференции Spyke — то есть в каждом разговоре должны участвовать ровно два собеседника.
Входные данные

В первой строке записано целое число n (1 ≤ n ≤ 103) — количество секретарей в корпорации Поликарпа. В следующей строке записаны n целых чисел через пробел: id1, id2, ..., idn (0 ≤ idi ≤ 109). Число idi равно номеру сессии разговора секретаря номер i, если он разговаривает в данный момент по Spyke, или равно нулю, в противном случае.

Считайте, что секретари пронумерованы от 1 до n некоторым образом.
Выходные данные

Выведите единственное целое число — количество пар секретарей, которые ведут разговор между собой, или -1, если в данные Поликарпа закралась ошибка, и описанная ситуация никак не могла произойти.
Примеры тестов
Входные данные

6
0 1 7 1 7 10

Выходные данные

2

Входные данные

3
1 1 1

Выходные данные

-1

Входные данные

1
0

Выходные данные

0

Примечание

В первом тестовом примере есть два телефонных разговора между секретарями: секретарь номер 2 и секретарь номер 4, секретарь номер 3 и секретарь номер 5.

Во втором тестовом примере описанная ситуация невозможна, так как не разрешены конференции.

 */
object Task1 extends App {

  /** Finds number of pairs, returns -1 if triplet or more */
  def solve(n: Int, ids: IndexedSeq[Long]): Int = {
    val grouped = ids groupBy (x => x)
    val counts = (grouped.values map (_.length) toIndexedSeq)
    val dist = counts filterNot (_ < 2)
    if (dist exists (_ > 2)) -1 else dist.size
  }

  val (line1, line2) = (readLine, readLine)
  val n = line1.toInt
  val ids = line2 split (' ') map (_.toLong)

  val res = solve(n, ids)
  println(res)
}

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

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

  val N = sc.nextInt
  val gs = List.fill(N)(sc.nextInt).groupBy(identity[Int]).map(_._2.length)

  val answer: Int = {
    gs.find(_ > 2) match {
      case Some(_) => -1
      case None => gs.filter(_ == 2).size
    }
  }

  out.println(answer)
  out.close
}

import io.Source
import java.io.PrintWriter

object CF291A {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val a = in(n).map(_.toInt).toSeq
    val sizes = a.groupBy(identity).toSeq.map(_._2.size)
    if (sizes.exists(_ > 2)) {
      out.println(-1)
    } else {
      out.println(sizes.count(_ == 2))
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

import io.Source
import java.io.PrintWriter

object CF291A {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val a = in(n).filter(_ != 0).map(_.toInt).toSeq
    val sizes = a.groupBy(identity).toSeq.map(_._2.size)
    if (sizes.exists(_ > 2)) {
      out.println(-1)
    } else {
      out.println(sizes.count(_ == 2))
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ;
    var b = a.distinct map (x => a.count(_==x));
    if (b exists(_>2)) println(-1)
    else println(b count(_==2))
  }
}

object A {
  def READ: Array[Int] = readLine() split (" ") map (_.toInt);
  def main(args: Array[String]) {
    var Array(n) = READ
    var a = READ;
    var b = a.distinct.map(_>0) map (x => a.count(_==x));
    if (b exists(_>2)) println(-1)
    else println(b count(_==2))
  }
}


Can the greatest common divisor and bitwise operations have anything in common? It is time to answer this question.Suppose you are given a positive integer $$$a$$$. You want to choose some integer $$$b$$$ from $$$1$$$ to $$$a - 1$$$ inclusive in such a way that the greatest common divisor (GCD) of integers $$$a \oplus b$$$ and $$$a \> \& \> b$$$ is as large as possible. In other words, you'd like to compute the following function:$$$$$$f(a) = \max_{0 < b < a}{gcd(a \oplus b, a \> \& \> b)}.$$$$$$Here $$$\oplus$$$ denotes the bitwise XOR operation, and $$$\&$$$ denotes the bitwise AND operation.The greatest common divisor of two integers $$$x$$$ and $$$y$$$ is the largest integer $$$g$$$ such that both $$$x$$$ and $$$y$$$ are divided by $$$g$$$ without remainder.You are given $$$q$$$ integers $$$a_1, a_2, \ldots, a_q$$$. For each of these integers compute the largest possible value of the greatest common divisor (when $$$b$$$ is chosen optimally).

The first line contains an integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of integers you need to compute the answer for. After that $$$q$$$ integers are given, one per line: $$$a_1, a_2, \ldots, a_q$$$ ($$$2 \le a_i \le 2^{25} - 1$$$) — the integers you need to compute the answer for.

For each integer, print the answer in the same order as the integers are given in input.

NoteFor the first integer the optimal choice is $$$b = 1$$$, then $$$a \oplus b = 3$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$3$$$ and $$$0$$$ is $$$3$$$.For the second integer one optimal choice is $$$b = 2$$$, then $$$a \oplus b = 1$$$, $$$a \> \& \> b = 2$$$, and the greatest common divisor of $$$1$$$ and $$$2$$$ is $$$1$$$.For the third integer the optimal choice is $$$b = 2$$$, then $$$a \oplus b = 7$$$, $$$a \> \& \> b = 0$$$, and the greatest common divisor of $$$7$$$ and $$$0$$$ is $$$7$$$.

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

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

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

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

  def solve(): Unit = {

    REP(ni()) { _ =>
      val a = ni()

      val all1 = Integer.highestOneBit(a) - 1 + Integer.highestOneBit(a)
      // 全部ビットたっているかどうか
      val ans = if (all1 == a) {
        // 全部ビットたっていたら gcd(a^b, a&b) == gcd(b, ~b)
        // b + ~b == a == (n + m) * c
        // n + m >= 2でcを最大化なので、すなわち２番目に大きいdevisorといっしょ
        val d = divisors(a)
        d(d.length - 2)
      } else {
        // 0のビットがあるのでa&b==0 のbをつくることができる
        // 一番左は0になりえないので、b = ~a のとき b^a == 2^n - 1 で最大にできる
        all1
      }
      out.println(ans)
    }
  }

  /**
    * O(√x)
    */
  def divisors(x: Int): Array[Int] = {
    val pre = ArrayBuffer[Int]()
    val post = ArrayBuffer[Int]()
    REP(math.sqrt(x).toInt, 1) { d =>
      if (x % d == 0) {
        pre += d
        if (d * d != x) post += x / d
      }
    }

    val res = Array.ofDim[Int](pre.length + post.length)
    REP(pre.length)(i => res(i) = pre(i))
    val preLen = pre.length
    val postLen = post.length
    REP(postLen)(i => res(i + preLen) = post(postLen - 1 - i))
    res
  }

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

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

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

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

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

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

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

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

object C extends App {

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

  val Array(q) = readInts(1)

  def gcd(x: Long, y: Long): Long = if (y == 0) x else gcd(y, x % y)

  for (_ <- 1 to q) {
    val a = readLine.toInt
    val mask = Integer.highestOneBit(a) * 2 - 1
    val b = a ^ mask
    val res = if (b == 0) 1 else gcd(a ^ b, a & b)
    println(res)
  }
}


Vasya has a grid with $$$2$$$ rows and $$$n$$$ columns. He colours each cell red, green, or blue.Vasya is colourblind and can't distinguish green from blue. Determine if Vasya will consider the two rows of the grid to be coloured the same.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 100$$$) — the number of columns of the grid. The following two lines each contain a string consisting of $$$n$$$ characters, each of which is either R, G, or B, representing a red, green, or blue cell, respectively — the description of the grid.

For each test case, output "YES" if Vasya considers the grid's two rows to be identical, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

6

2

RG

RB

4

GRBG

GBGB

5

GGGGG

BBBBB

7

BBBBBBB

RRRRRRR

8

RGBRRGBR

RGGRRBGR

1

G

G

NoteIn the first test case, Vasya sees the second cell of each row as the same because the second cell of the first row is green and the second cell of the second row is blue, so he can't distinguish these two cells. The rest of the rows are equal in colour. Therefore, Vasya will say that the two rows are coloured the same, even though they aren't.In the second test case, Vasya can see that the two rows are different.In the third test case, every cell is green or blue, so Vasya will think they are the same.

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

  override def solve(io: IO) = io.repeat {
    val (_, a, b) = io.read[(Int, String, String)]
    val ans = a.replace('G', 'B') == b.replace('G', 'B')
    io.write(ans.toEnglish.toUpperCase())
  }
}
/****************************[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
      }
    }
  }
}


William really likes the cellular automaton called "Game of Life" so he decided to make his own version. For simplicity, William decided to define his cellular automaton on an array containing $$$n$$$ cells, with each cell either being alive or dead.Evolution of the array in William's cellular automaton occurs iteratively in the following way:  If the element is dead and it has exactly $$$1$$$ alive neighbor in the current state of the array, then on the next iteration it will become alive. For an element at index $$$i$$$ the neighbors would be elements with indices $$$i - 1$$$ and $$$i + 1$$$. If there is no element at that index, it is considered to be a dead neighbor.  William is a humane person so all alive elements stay alive. Check the note section for examples of the evolution.You are given some initial state of all elements and you need to help William find the state of the array after $$$m$$$ iterations of evolution.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^3$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n \le 10^3, 1 \le m \le 10^9$$$), which are the total number of cells in the array and the number of iterations. The second line of each test case contains a string of length $$$n$$$ made up of characters "0" and "1" and defines the initial state of the array. "1" means a cell is alive and "0" means it is dead. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

In each test case output a string of length $$$n$$$, made up of characters "0" and "1"  — the state of the array after $$$m$$$ iterations of evolution.

NoteSequence of iterations of evolution for the first test case   01000000001  — initial state  11100000011  — first iteration of evolution  11110000111  — second iteration of evolution  11111001111  — third iteration of evolution Sequence of iterations of evolution for the second test case   0110100101  — initial state  1110111101  — first iteration of evolution  1110111101  — second iteration of evolution

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

  val t = readInt()

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

    def go(i: Int): Boolean =
      if (i == 0) false
      else {
        var flag = false

        for {
          j <- 0 until n if state(j) == 0
          l  = if (j == 0) 0 else state(j - 1)
          r  = if (j + 1 == n) 0 else state(j + 1)
          sj = l ^ r if sj != state(j)
        } {
          flag = true
          state(j) = sj
        }

        flag && go(i - 1)
      }

    go(m)

    println(state.mkString(""))
  }
}