You are given an array $$$a$$$ consisting of $$$n$$$ integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from $$$a$$$ to make it a good array. Recall that the prefix of the array $$$a=[a_1, a_2, \dots, a_n]$$$ is a subarray consisting several first elements: the prefix of the array $$$a$$$ of length $$$k$$$ is the array $$$[a_1, a_2, \dots, a_k]$$$ ($$$0 \le k \le n$$$).The array $$$b$$$ of length $$$m$$$ is called good, if you can obtain a non-decreasing array $$$c$$$ ($$$c_1 \le c_2 \le \dots \le c_{m}$$$) from it, repeating the following operation $$$m$$$ times (initially, $$$c$$$ is empty):  select either the first or the last element of $$$b$$$, remove it from $$$b$$$, and append it to the end of the array $$$c$$$. For example, if we do $$$4$$$ operations: take $$$b_1$$$, then $$$b_{m}$$$, then $$$b_{m-1}$$$ and at last $$$b_2$$$, then $$$b$$$ becomes $$$[b_3, b_4, \dots, b_{m-3}]$$$ and $$$c =[b_1, b_{m}, b_{m-1}, b_2]$$$.Consider the following example: $$$b = [1, 2, 3, 4, 4, 2, 1]$$$. This array is good because we can obtain non-decreasing array $$$c$$$ from it by the following sequence of operations:  take the first element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2, 1]$$$, $$$c = [1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4, 2]$$$, $$$c = [1, 1]$$$;  take the last element of $$$b$$$, so $$$b = [2, 3, 4, 4]$$$, $$$c = [1, 1, 2]$$$;  take the first element of $$$b$$$, so $$$b = [3, 4, 4]$$$, $$$c = [1, 1, 2, 2]$$$;  take the first element of $$$b$$$, so $$$b = [4, 4]$$$, $$$c = [1, 1, 2, 2, 3]$$$;  take the last element of $$$b$$$, so $$$b = [4]$$$, $$$c = [1, 1, 2, 2, 3, 4]$$$;  take the only element of $$$b$$$, so $$$b = []$$$, $$$c = [1, 1, 2, 2, 3, 4, 4]$$$ — $$$c$$$ is non-decreasing. Note that the array consisting of one element is good.Print the length of the shortest prefix of $$$a$$$ to delete (erase), to make $$$a$$$ to be a good array. Note that the required length can be $$$0$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer: the length of the shortest prefix of elements you need to erase from $$$a$$$ to make it a good array.

NoteIn the first test case of the example, the array $$$a$$$ is already good, so we don't need to erase any prefix.In the second test case of the example, the initial array $$$a$$$ is not good. Let's erase first $$$4$$$ elements of $$$a$$$, the result is $$$[4, 5, 2]$$$. The resulting array is good. You can prove that if you erase fewer number of first elements, the result will not be good.

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

  val t = readInt()

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

    val i = an.zipWithIndex.lastIndexWhere {
      case (_, 0) => true
      case (a, i) => a > an(i - 1)
    }

    val j = an.zipWithIndex.lastIndexWhere({
      case (_, 0) => true
      case (a, j) => a < an(j - 1)
    }, i)

    println(j)
  }
}

import scala.Console.in

object App extends App {
  val cases: Long = Console.in.readLine().toInt
  val data = Vector.range(0, cases).map(_ => {
    in.readLine()
    in.readLine().split(" ").toVector.map(_.toLong)
  })

  def f(arr: Vector[Long]): Long = {
    val pMin = arr.length - 1

    def max(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos
    }

    def min(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos
    }

    (arr foldRight (arr foldRight pMin) ((_, pos) => max(pos))) ((_, pos) => min(pos))
  }

  val answer = for (datum <- data) yield f(datum)

  answer map(a => {
    print(a.toString)
    print("\n")
  })
}

import scala.Console.in

object App extends App {
  val cases: Long = Console.in.readLine().toInt
  val data = Vector.range(0, cases).map(_ => {
    in.readLine()
    in.readLine().split(" ").toVector.map(_.toLong)
  })

  def f(arr: Vector[Long]): Long = {
    val pMin = arr.length - 1

    def max(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos
    }

    def min(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos
    }

    val pMax = (arr foldRight pMin) ((_, pos) => max(pos))
    (arr foldRight pMax) ((_, pos) => min(pos))
  }

  val answer = for (datum <- data) yield f(datum)

  answer map(a => print(a.toString ++ "\n"))
}

import scala.Console.in

object App extends App {
  val cases: Long = Console.in.readLine().toInt
  val data = Vector.range(0, cases).map(_ => {
    in.readLine()
    in.readLine().split(" ").toVector.map(_.toLong)
  })

  def f(arr: Vector[Long]): Long = {
    val zipped = arr.zipWithIndex
    val pMin = zipped.last._2

    def max(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos
    }

    def min(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos
    }

    val pMax = (zipped foldRight pMin) ((_, pos) => max(pos))
    (zipped foldRight pMax) ((_, pos) => min(pos))
  }

  val answer = for (datum <- data) yield f(datum)

  answer map(a => print(a.toString ++ "\n"))
}

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

  val t = readInt()

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

    println()
    println(an.mkString(" "))

    val i = an.zipWithIndex.lastIndexWhere {
      case (_, 0) => true
      case (a, i) => a > an(i - 1)
    }

    val j = an.zipWithIndex.lastIndexWhere({
      case (_, 0) => true
      case (a, j) => a < an(j - 1)
    }, i)

    println(j)
  }
}

import scala.Console.in

object App extends App {
  val cases: Long = Console.in.readLine().toInt
  val data = Vector.range(0, cases).map(_ => {
    in.readLine()
    in.readLine().split(" ").toVector.map(_.toLong)
  })

  def f(arr: Vector[Long]): Long = {
    val zipped = arr.zipWithIndex
    val pMin = zipped.last._2

    def max(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) <= arr.apply(pos - 1)) pos - 1 else pos
    }

    def min(pos: Int): Int = pos match {
      case pos => if (pos > 0 && arr.apply(pos) >= arr.apply(pos - 1)) pos - 1 else pos
    }

    val pMax = (zipped foldRight pMin) ( (_, pos) => max(pos))
    print(pMax)
    (zipped foldRight pMax) ((_, pos) => min(pos))
  }

  val answer = for (datum <- data) yield f(datum)

  print(answer)
}


You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.

NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. There are other possible answers like "5 4 5 6 -2 8".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. There are other possible answers like "2 4 8 1".

object B extends App {

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

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val m  = (n - 1) / 2
    val an = scala.io.StdIn.readLine().split(" ").map(_.toInt).sorted
    val bn = List(m, m + (n + 1) % 2).distinct.map(an) ::: (0 until m).foldLeft(List.empty[Int])((bn, i) =>
      an(i) :: an(n - i - 1) :: bn
    )

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

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

object SortMe {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 1 to t) {
      val _ = StdIn.readInt()
      val nums = StdIn.readLine().trim.split(" ").map(_.toLong).sorted.toList
      val result = build(nums)
      println(result.mkString(" "))
    }

    def build(items: List[Long]): List[Long] = {
      @tailrec
      def go(accum: List[Long], xs: List[Long], ys: List[Long]): List[Long] = {
        (xs.headOption, ys.headOption) match {
          case (_, None) => accum
          case (None, Some(y)) => y +: accum
          case (Some(x), Some(y)) => go(x +: y +: accum, xs.tail, ys.tail)
        }
      }
      val (xs, ys) = items.splitAt(items.length / 2)
      go(List.empty[Long], xs, ys.reverse)
    }
  }
}

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

object SortMe {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 1 to t) {
      val _ = StdIn.readInt()
      val nums = StdIn.readLine().trim.split(" ").map(_.toLong).sorted.toList
      val result = build(nums)
      println(result.mkString(" "))
    }

    def build(items: List[Long]): List[Long] = {
      @tailrec
      def go(accum: List[Long], xs: List[Long], ys: List[Long]): List[Long] = {
        (xs, ys) match {
          case (_, Nil) => accum
          case (Nil, y :: Nil) => y +: accum
          case (x :: tailx, y :: taily) => go(x +: y +: accum, tailx, taily)
        }
      }
      val (xs, ys) = items.splitAt(items.length / 2)
      go(List.empty[Long], xs, ys.reverse)
    }
  }
}

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

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

    val b  = an(an.length / 2)
    val bn = an.sortBy(a => (a - b).abs)

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

import scala.io.StdIn
object SortMe {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 1 to t) {
      val _ = StdIn.readInt()
      val nums = StdIn.readLine().trim.split(" ").map(_.toLong)
      val sorted = nums.indices
        .sortBy { index =>
          if (index == nums.length - 1) math.abs(nums(index))
          else math.abs(nums(index+1) - nums(index))
        }
        .map(nums(_))

      System.out.println(sorted.mkString(" "))
    }
  }
}


There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the third — at time $$$2 \cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the second — at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.

The first line contains a single integer $$$k$$$ ($$$1 \le k \le 1000$$$) — the number of test cases. Each of the next $$$k$$$ lines contains three integers $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \le n, x, t \le 2 \cdot 10^9$$$) — the number of participants, the start interval and the contest duration.

Print $$$k$$$ lines, in the $$$i$$$-th line print the total dissatisfaction of participants in the $$$i$$$-th test case.

NoteIn the first example the first participant starts at $$$0$$$ and finishes at time $$$5$$$. By that time the second and the third participants start, so the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$2$$$ and finishes at time $$$7$$$. By that time the third the fourth participants start, so the dissatisfaction of the second participant is $$$2$$$. The third participant starts at $$$4$$$ and finishes at $$$9$$$. By that time the fourth participant starts, so the dissatisfaction of the third participant is $$$1$$$.The fourth participant starts at $$$6$$$ and finishes at $$$11$$$. By time $$$11$$$ everyone finishes the contest, so the dissatisfaction of the fourth participant is $$$0$$$.In the second example the first participant starts at $$$0$$$ and finishes at time $$$2$$$. By that time the second participants starts, and the third starts at exactly time $$$2$$$. So the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$1$$$ and finishes at time $$$3$$$. At that time the third participant is solving the contest.

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

  /** Dissatisfaction equals to the number of participants that
    * started the contest (or starting it now), but haven't yet
    * finished it.
    *
    * @param n The number of participants
    * @param x The start interval
    * @param t The contest duration
    */
  private def dissatisfaction(n: Int, x: Int, t: Int): Long = {
    // 1. Рассмотрим все i такие, что i * x + t <= (n-1) * x
    //    i + t/x <= n - 1
    //    i <= n - 1 - t/x
    //    i принадлежит [1, n - 1 - t/x], а значит таких i ровно min(0, n - t/x)
    //    (i + m) * x <= i * x + t
    //    i + m <= i + t/x
    //    m <= t/x, а значит m принадлежит [1, t/x]
    //    В результате получим max(0, n - t/x) * t/x
    // 2. В случае, когда (n - 1) * x попадает в интервал [i * x, i * x + t]
    //    получаем, что m принимает значение n - 1 - i, т.е. 0, 1, 2, ..., (t/x - 1)
    //    В результате получим t/x * (t/x - 1) / 2
    val d = (t / x).toLong
    d * 0L.max(n - d) + d.min(n) * (d.min(n) - 1L) / 2L
  }

  val k = readInt()

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

    val ans = dissatisfaction(n, x, t)

    println(ans)
  }
}

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

  /** Dissatisfaction equals to the number of participants that
    * started the contest (or starting it now), but haven't yet
    * finished it.
    *
    * @param n The number of participants
    * @param x The start interval
    * @param t The contest duration
    */
  private def dissatisfaction(n: Int, x: Int, t: Int): Long = {
    // 1. Рассмотрим все i такие, что i * x + t <= (n-1) * x
    //    i + t/x <= n - 1
    //    i <= n - 1 - t/x
    //    i принадлежит [1, n - 1 - t/x], а значит таких i ровно min(0, n - t/x)
    //    (i + m) * x <= i * x + t
    //    i + m <= i + t/x
    //    m <= t/x, а значит m принадлежит [1, t/x]
    //    В результате получим max(0, n - t/x) * t/x
    // 2. В случае, когда (n - 1) * x попадает в интервал [i * x, i * x + t]
    //    получаем, что m принимает значение n - 1 - i, т.е. 0, 1, 2, ..., (t/x - 1)
    //    В результате получим t/x * (t/x - 1) / 2
    val d = (t / x).toLong
    d * 0L.max(n - d) + d * (d - 1L) / 2L
  }

  val k = readInt()

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

    val ans = dissatisfaction(n, x, t)

    println(ans)
  }
}


During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.For a given list of pairs of integers $$$(a_1, b_1)$$$, $$$(a_2, b_2)$$$, ..., $$$(a_n, b_n)$$$ their WCD is arbitrary integer greater than $$$1$$$, such that it divides at least one element in each pair. WCD may not exist for some lists.For example, if the list looks like $$$[(12, 15), (25, 18), (10, 24)]$$$, then their WCD can be equal to $$$2$$$, $$$3$$$, $$$5$$$ or $$$6$$$ (each of these numbers is strictly greater than $$$1$$$ and divides at least one number in each pair).You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 150\,000$$$) — the number of pairs. Each of the next $$$n$$$ lines contains two integer values $$$a_i$$$, $$$b_i$$$ ($$$2 \le a_i, b_i \le 2 \cdot 10^9$$$).

Print a single integer — the WCD of the set of pairs.  If there are multiple possible answers, output any; if there is no answer, print $$$-1$$$.

NoteIn the first example the answer is $$$6$$$ since it divides $$$18$$$ from the first pair, $$$24$$$ from the second and $$$12$$$ from the third ones. Note that other valid answers will also be accepted.In the second example there are no integers greater than $$$1$$$ satisfying the conditions.In the third example one of the possible answers is $$$5$$$. Note that, for example, $$$15$$$ is also allowed, but it's not necessary to maximize the output.

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val primes = listPrimes()
    var initialDivisors: Seq[Int] = {
      val l = in.nextInt
      val r = in.nextInt
      (divisors(l, primes) ::: divisors(r, primes)).distinct
    }
    for (_ <- 2 to n) {
//      println(initialDivisors)
      val l = in.nextInt
      val r = in.nextInt
      initialDivisors = initialDivisors.filter(div => (l % div == 0) || (r % div == 0))
    }
    println(initialDivisors.headOption.getOrElse(-1))
  }

  def divisors(n: Int, knownPrimes: Vector[Int]): List[Int] = {
    var remaining: Int = n
    var result: List[Int] = Nil
    var i = 0
    var cur = 0
    while (remaining > 1 && i < knownPrimes.length) {
      cur = knownPrimes(i)
      if (remaining % cur == 0) {
        result = cur :: result
        while (remaining % cur == 0) {
          remaining = remaining / cur
        }
      } else {
        i = i + 1
      }
    }
    if (remaining > 1) {
      result = remaining :: result
    }
    result
  }

  def listPrimes(): Vector[Int] = {
    val m = Math.sqrt(2 * 1000 * 1000 * 1000).ceil.toInt
    val isPrime = primesAux(m)
    var res = List.empty[Int]
    for (i <- isPrime.indices.reverse) {
      if (isPrime(i)) {
        res = i :: res
      }
    }
    res.toVector
  }

  def primesAux(n: Int): Array[Boolean] = {
    val p = Array.fill(n + 1)(true)
    val nl = n.toLong
    p.update(0, false)
    p.update(1, false)
    for (i <- 2 to n) {
      if (p(i) && i.toLong * i.toLong <= nl) {
        for (j <- (i * i).to(n, i)) {
          p.update(j, false)
        }
      }
    }
    p
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object B extends App {

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

  val Array(n) = readInts(1)

  val LIMIT = 44725
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    var addA, addB = 0
    var aComposite, bComposite = false

    val pit = primes.iterator
    while (pit.hasNext) {

      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
      else if (i == 0) {
        if (a % p == 0) {
          aComposite = true
          var d = a / p
          for (p <- isPrime.indices) if (isPrime(p)) {
            while (d % p == 0) d /= p
          }
          if (d > LIMIT) addA = d
        }
        if (b % p == 0) {
          bComposite = true
          var d = b / p
          for (p <- isPrime.indices) if (isPrime(p)) {
            while (d % p == 0) d /= p
          }
          if (d > LIMIT) addB = d
        }
      }
    }

    if (i == 0) {
      if (!aComposite) primes.add(a)
      if (!bComposite) primes.add(b)
      if (addA > 0) primes.add(addA)
      if (addB > 0) primes.add(addB)
    }

  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}

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

object B extends App {

  def solve(in: InputReader): Unit = {
    val n = in.nextInt
    val primes = listPrimes()
    var initialDivisors: Seq[Int] = {
      val l = in.nextInt
      val r = in.nextInt
      (divisors(l, primes) ::: divisors(r, primes)).distinct
    }
    for (_ <- 2 to n) {
//      println(initialDivisors)
      val l = in.nextInt
      val r = in.nextInt
      initialDivisors = initialDivisors.filter(div => (l % div == 0) || (r % div == 0))
    }
    println(initialDivisors.headOption.getOrElse(-1))
  }

  def divisors(n: Int, knownPrimes: Vector[Int]): List[Int] = {
    var remaining: Int = n
    var result: List[Int] = Nil
    var i = 0
    var cur = 0
    while (remaining >= 1 && i < knownPrimes.length) {
      cur = knownPrimes(i)
      if (remaining % cur == 0) {
        result = cur :: result
        while (remaining % cur == 0) {
          remaining = remaining / cur
        }
      } else {
        i = i + 1
      }
    }
    if (result.nonEmpty) result else List(n)
  }

  def listPrimes(): Vector[Int] = {
    val m = Math.sqrt(2 * 1000 * 1000 * 1000).ceil.toInt
    val ids = primesAux(m)
    var res = List.empty[Int]
    for (i <- ids.indices.reverse) {
      if (ids(i)) {
        res = i :: res
      }
    }
    res.toVector
  }

  def primesAux(n: Int): Array[Boolean] = {
    val p = Array.fill(n + 1)(true)
    val nl = n.toLong
    p.update(0, false)
    p.update(1, false)
    for (i <- 2 to n) {
      if (p(i) && i.toLong * i.toLong <= nl) {
        for (j <- (i * i).to(n, i)) {
          p.update(j, false)
        }
      }
    }
    p
  }

  /*
int n;
vector<char> prime (n+1, true);
prime[0] = prime[1] = false;
for (int i=2; i<=n; ++i)
	if (prime[i])
		if (i * 1ll * i <= n)
			for (int j=i*i; j<=n; j+=i)
				prime[j] = false;
				*/

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextLong: Long = {
      next.toLong
    }

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

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object B extends App {

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

  val Array(n) = readInts(1)

  val LIMIT = 50000
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    var addA, addB = 0
    var aComposite, bComposite = false

    val pit = primes.iterator
    while (pit.hasNext) {

      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
      else if (i == 0) {
        if (a % p == 0) {
          aComposite = true
          val d = a / p
          if (d > LIMIT) addA = d
        }
        if (b % p == 0) {
          bComposite = true
          val d = b / p
          if (d > LIMIT) addB = d
        }
      }
    }

    if (i == 0) {
      if (!aComposite) primes.add(a)
      if (!bComposite) primes.add(b)
      if (addA > 0) primes.add(addA)
      if (addB > 0) primes.add(addB)
    }

  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}

object B 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 LIMIT = 44725
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    val pit = primes.iterator
    var addA, addB = 0
    while (pit.hasNext) {
      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
      else {
        if (a % p == 0) {
          val d = a / p
          if (d > LIMIT) addA = d
        }
        if (b % p == 0) {
          val d = b / p
          if (d > LIMIT) addB = d
        }
      }
    }
    if (addA > 0) primes.add(addA)
    if (addB > 0) primes.add(addB)
    if (i == 0 && primes.isEmpty) {
      primes.add(a)
      primes.add(b)
    }
  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}

object B 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 LIMIT = 44725
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    val pit = primes.iterator
    var addA, addB = 0
    while (pit.hasNext) {
      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
      else if (i == 0) {
        if (a % p == 0) {
          val d = a / p
          if (d > LIMIT) addA = d
        }
        if (b % p == 0) {
          val d = b / p
          if (d > LIMIT) addB = d
        }
      }
    }
    if (i == 0) {
      if (primes.isEmpty) {
        primes.add(a)
        primes.add(b)
      }
      if (addA > 0) primes.add(addA)
      if (addB > 0) primes.add(addB)
    }
  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}

object B 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 LIMIT = 44725
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    val pit = primes.iterator
    while (pit.hasNext) {
      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
    }
    if (i == 0 && primes.isEmpty) {
      primes.add(a)
      primes.add(b)
    }
  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}

object B 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 LIMIT = 44725
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    val pit = primes.iterator
    var addA, addB = 0
    while (pit.hasNext) {
      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
      else {
        if (a % p == 0) {
          val d = a / p
          if (d > LIMIT) addA = d
        }
        if (b % p == 0) {
          val d = b / p
          if (d > LIMIT) addB = d
        }
      }
    }
    if (addA > 0) primes.add(a)
    if (addB > 0) primes.add(b)
    if (i == 0 && primes.isEmpty) {
      primes.add(a)
      primes.add(b)
    }
  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}

object B 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 LIMIT = 44725
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    val pit = primes.iterator
    var addA, addB = 0
    var aComposite, bComposite = false
    while (pit.hasNext) {
      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
      else if (i == 0) {
        if (a % p == 0) {
          aComposite = true
          val d = a / p
          if (d > LIMIT) addA = d
        }
        if (b % p == 0) {
          bComposite = true
          val d = b / p
          if (d > LIMIT) addB = d
        }
      }
    }
    if (i == 0) {
      if (!aComposite) primes.add(a)
      if (!bComposite) primes.add(b)
      if (addA > 0) primes.add(addA)
      if (addB > 0) primes.add(addB)
    }
  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}

object B 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 LIMIT = 44725
  val isPrime = Array.fill(LIMIT)(true)
  isPrime(0) = false
  isPrime(1) = false

  var i = 2
  while (i * i < LIMIT) {
    var j = i * i
    if (isPrime(j)) {
      while (j < LIMIT) {
        isPrime(j) = false
        j += i
      }
    }
    i += 1
  }

  val primes = new java.util.TreeSet[Int]
  for (p <- isPrime.indices) if (isPrime(p)) primes.add(p)

  for (i <- 0 until n) {
    val Array(a, b) = readInts(2)
    val pit = primes.iterator
    var addA, addB = 0
    while (pit.hasNext) {
      val p = pit.next()
      if (a % p != 0 && b % p != 0) pit.remove()
      else if (i == 0) {
        if (a % p == 0) {
          val d = a / p
          if (d > LIMIT) addA = d
        }
        if (b % p == 0) {
          val d = b / p
          if (d > LIMIT) addB = d
        }
      }
    }
    if (i == 0) {
      if (primes.isEmpty) {
        primes.add(a)
        primes.add(b)
      } else {
        if (addA > 0) primes.add(addA)
        if (addB > 0) primes.add(addB)
      }
    }
  }

  println(if (!primes.isEmpty) primes.iterator.next() else -1)
}


Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences of days 0, 010, 01010 are zebras, while sequences 1, 0110, 0101 are not.Oleg tells you the story of days he lived in chronological order in form of string consisting of 0 and 1. Now you are interested if it is possible to divide Oleg's life history into several subsequences, each of which is a zebra, and the way it can be done. Each day must belong to exactly one of the subsequences. For each of the subsequences, days forming it must be ordered chronologically. Note that subsequence does not have to be a group of consecutive days.

In the only line of input data there is a non-empty string s consisting of characters 0 and 1, which describes the history of Oleg's life. Its length (denoted as |s|) does not exceed 200 000 characters.

If there is a way to divide history into zebra subsequences, in the first line of output you should print an integer k (1 ≤ k ≤ |s|), the resulting number of subsequences. In the i-th of following k lines first print the integer li (1 ≤ li ≤ |s|), which is the length of the i-th subsequence, and then li indices of days forming the subsequence. Indices must follow in ascending order. Days are numbered starting from 1. Each index from 1 to n must belong to exactly one subsequence. If there is no way to divide day history into zebra subsequences, print -1. Subsequences may be printed in any order. If there are several solutions, you may print any of them. You do not have to minimize nor maximize the value of k.

object cTask3 {

  import scala.io.StdIn.readLine
  import scala.collection.mutable
  import scala.collection.mutable.ArrayBuffer

  def zebra(s: List[Char]):Option[List[List[Int]]] = {

    def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {
      lst match {
        case Nil if acc1.isEmpty => Some(acc0)
        case Nil => None
        case '0'::ls => acc1 match {
          case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)
          case _ => helper(ls, List(num)::acc0, acc1, num + 1)
        }
        case '1'::ls => acc0 match {
          case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)
          case _ => None
        }
      }
    }
    helper(s, List(), List(), 1)
  }

  def zebra1(s: Array[Char]):Option[List[mutable.ArrayBuffer[Int]]] = {

    var all: ArrayBuffer[mutable.ArrayBuffer[Int]]=ArrayBuffer()
    var idx = 0
    var cutOff = 0

    for (i <- s.indices) {
      if(s(i) == '0'){
        if(cutOff != 0) {
          cutOff-=1
          all(cutOff)+=(i+1)
        } else {
          idx+=1
          all+=mutable.ArrayBuffer(i + 1)
        }
      } else {
        if(cutOff != idx){
          all(cutOff)+=(i+1)
          cutOff+=1
        } else {
          return None
        }
      }
    }
    if (cutOff != 0) None
    else Some(all.toList)

    }

  def main(args: Array[String]): Unit = {
    val s = readLine.toCharArray
    zebra1(s) match {
      case None => println("-1")
      case Some(xs) => println(xs.length + "\n" + xs.map(x => x.length + " " + x.mkString(" ")).mkString("\n"))
    }

  }
}

object cTask3 {

  import scala.io.StdIn.readLine
  import scala.collection.mutable
  import scala.collection.mutable.ArrayBuffer

  def zebra(s: List[Char]):Option[List[List[Int]]] = {

    def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {
      lst match {
        case Nil if acc1.isEmpty => Some(acc0)
        case Nil => None
        case '0'::ls => acc1 match {
          case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)
          case _ => helper(ls, List(num)::acc0, acc1, num + 1)
        }
        case '1'::ls => acc0 match {
          case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)
          case _ => None
        }
      }
    }
    helper(s, List(), List(), 1)
  }

  def zebra1(s: Array[Char]):Option[List[mutable.ArrayBuffer[Int]]] = {

    var all: ArrayBuffer[mutable.ArrayBuffer[Int]]=ArrayBuffer()
    var idx = 0
    var cutOff = 0

    for (i <- s.indices) {
      if(s(i) == '0'){
        if(cutOff != 0) {
          cutOff-=1
          all(cutOff)+=(i+1)
        } else {
          idx+=1
          all+=mutable.ArrayBuffer(i + 1)
        }
      } else {
        if(cutOff != idx){
          all(cutOff)+=(i+1)
          cutOff+=1
        } else {
          return None
        }
      }
    }
    if (cutOff != 0) None
    else Some(all.toList)

    }

  def main(args: Array[String]): Unit = {
    val s = readLine.toCharArray.toList
    zebra(s) match {
      case None => println("-1")
      case Some(xs) => println(xs.length + "\n" + xs.map(x => x.length + " " + x.reverse.mkString(" ")).mkString("\n"))
    }

  }
}

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

import scala.language.implicitConversions

object Zebras {
  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }
  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }
  def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {
    override def apply(key: I) = getOrElseUpdate(key, f(key))
  }

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val bw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

    val A = br.readLine()
//    val range = 0.until(200000/3);
//    val A = range.map(_ => '0').mkString("") + range.map(_ => '1').mkString("") + range.map(_ => '0').mkString("");
//    val t0 = System.nanoTime()

    case class Ret(valid: Boolean, seqs: List[List[Int]])
    def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {
      if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)
      else {
        if (A(ind) == '0') {
          if (eo.isEmpty) rec(ind + 1, List(ind + 1) :: ez, eo)
          else {
            val first = eo.head
            rec(ind + 1, ((ind + 1) :: first) :: ez, eo.tail)
          }
        } else {
          if (ez.isEmpty) Ret(false, null)
          else {
            val first = ez.head
            rec(ind + 1, ez.tail, ((ind + 1) :: first) :: eo)
          }
        }
      }
    }

    val result = rec(0, List[List[Int]](), List[List[Int]]())

    val t1 = System.nanoTime()
    if (result.valid) {
      bw.println(result.seqs.size)
      result.seqs.foreach(seq => {bw.print(seq.size); bw.print(" "); seq.reverse.foreach(x => {bw.print(x); bw.print(" ")}); bw.println()})
    } else {
      bw.println("-1")
    }

//    bw.println(t1 - t0 + "")
    bw.close()
    br.close()
  }
}

object cTask3 {

  import scala.io.StdIn.readLine
  import scala.collection.mutable
  import scala.collection.mutable.ArrayBuffer

  def zebra(s: List[Char]):Option[List[List[Int]]] = {

    def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {
      lst match {
        case Nil if acc1.isEmpty => Some(acc0)
        case Nil => None
        case '0'::ls => acc1 match {
          case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)
          case _ => helper(ls, List(num)::acc0, acc1, num + 1)
        }
        case '1'::ls => acc0 match {
          case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)
          case _ => None
        }
      }
    }
    helper(s, List(), List(), 1)
  }

  def zebra1(s: Array[Char]):Option[List[mutable.ArrayBuffer[Int]]] = {

    var all: ArrayBuffer[mutable.ArrayBuffer[Int]]=ArrayBuffer()
    var idx = 0
    var cutOff = 0

    for (i <- s.indices) {
      if(s(i) == '0'){
        if(cutOff != 0) {
          cutOff-=1
          all(cutOff)+=(i+1)
        } else {
          idx+=1
          all+=mutable.ArrayBuffer(i + 1)
        }
      } else {
        if(cutOff != idx){
          all(cutOff)+=(i+1)
          cutOff+=1
        } else {
          return None
        }
      }
    }
    if (cutOff != 0) None
    else Some(all.toList)

    }

  def main(args: Array[String]): Unit = {
    val s = readLine.toCharArray.toList
    zebra(s) match {
      case None => println("-1")
      case Some(xs) => println(xs.length + "\n" + xs.map(x => x.length + " " + x.mkString(" ")).mkString("\n"))
    }

  }
}

object cTask3 {

  import scala.io.StdIn.{readLine, readInt}

  def zebra(s: List[Int]):Option[List[List[Int]]] = {

    def helper(lst: List[Int], acc: List[List[(Int, Int)]], num: Int): Option[List[List[(Int, Int)]]] = {
      def helpmat(elem: Int, num: Int, acc1: List[List[(Int, Int)]], acc2: List[List[(Int, Int)]]): Option[List[List[(Int, Int)]]]={
        acc2 match {
          case Nil if elem == 0 => Some(List((0, num))::acc1)
          case Nil  => None
          case x::xs if elem != x.head._1 => Some(((elem, num)::x)::xs ++ acc1)
          case x::xs => helpmat(elem, num, x::acc1, xs)
        }
      }

      lst match {
        case Nil => Some(acc)
        case x::xs => helpmat(x, num, List(), acc) match {
          case None => None
          case Some(newAcc) => helper(xs, newAcc, num + 1)
        }
      }

    }
    helper(s, List(), 1) match {
      case Some(e) if e.forall(_.head._1 == 0) => Some(e.map(y => y.map(_._2)))
      case _ => None
    }
  }

  def main(args: Array[String]): Unit = {
    var s = readLine.toCharArray.map(_.asDigit).toList
    zebra(s) match {
      case None => println("-1")
      case Some(xs) => xs.foreach(x => println(x.length + " " + x.reverse.mkString(" ")))
    }

  }
}

object cTask3 {

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

  def zebra(s: List[Char]):Option[List[List[Int]]] = {

    def helper(lst: List[Char], acc0: List[List[Int]], acc1: List[List[Int]], num: Int): Option[List[List[Int]]] = {
      lst match {
        case Nil if acc1.isEmpty => Some(acc0)
        case Nil => None
        case '0'::ls => acc1 match {
          case a::as1 =>helper(ls, (num::a)::acc0, as1, num + 1)
          case _ => helper(ls, List(num)::acc0, acc1, num + 1)
        }
        case '1'::ls => acc0 match {
          case a::as0 => helper(ls, as0, (num::a)::acc1, num + 1)
          case _ => None
        }
      }
    }
    helper(s, List(), List(), 1)
  }

  def zebra1(s: Array[Char]):Option[List[List[Int]]] = {

    val acc0:mutable.ArrayBuffer[List[Int]] = mutable.ArrayBuffer()
    val acc1:mutable.ArrayBuffer[List[Int]] = mutable.ArrayBuffer()

    for (i <- s.indices) {
      if(s(i) == '0'){
        if(acc1.nonEmpty) {
          acc0+=i::acc1.head
          acc1-=acc1(0)
        } else acc0 += List(i)
      } else {
        if(acc0.nonEmpty){
          acc1+=i::acc0.head
          acc0-=acc0(0)
        } else {
          return None
        }
      }
    }
    if (acc1.nonEmpty) None
    else Some(acc0.toList)

    }

  def main(args: Array[String]): Unit = {
    val s = readLine.toCharArray
    zebra1(s) match {
      case None => println("-1")
      case Some(xs) => println(xs.length); xs.foreach(x => println(x.length + " " + x.reverse.mkString(" ")))
    }

  }
}

import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.io.InputStreamReader
import java.io.BufferedReader
import java.util.Scanner

import scala.language.implicitConversions

object Zebras {
  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }
  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }
  def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {
    override def apply(key: I) = getOrElseUpdate(key, f(key))
  }

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val bw = new BufferedWriter(new OutputStreamWriter(System.out))

    val A = br.readLine()
//    val A = 0.until(200000).map(_ => '0').mkString("")
//    val t0 = System.nanoTime()

    case class Ret(valid: Boolean, seqs: List[List[Int]])
    def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {
      if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)
      else {
        if (A(ind) == '0') {
          if (eo.size == 0) rec(ind + 1, List(ind + 1) :: ez, eo)
          else {
            val first = eo.head
            rec(ind + 1, ((ind + 1) :: first) :: ez, eo.tail)
          }
        } else {
          if (ez.size == 0) Ret(false, null)
          else {
            val first = ez.head
            rec(ind + 1, ez.tail, ((ind + 1) :: first) :: eo)
          }
        }
      }
    }

    val result = rec(0, List[List[Int]](), List[List[Int]]())

    if (result.valid) {
      bw.write(result.seqs.size + "\n")
      result.seqs.foreach(seq => {bw.write(seq.size + " "); seq.foldRight(0)((x, _) => {bw.write(x + " "); 0}); bw.write("\n")})
    } else {
      bw.write("-1\n")
    }

//    val t1 = System.nanoTime()
//    bw.write(t1 - t0 + "")

//    bw.flush()
  }
}

import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.util.Scanner

import scala.language.implicitConversions

object Zebras {
  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }
  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }
  def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {
    override def apply(key: I) = getOrElseUpdate(key, f(key))
  }

  def main(args: Array[String]): Unit = {
    val bw = new BufferedWriter(new OutputStreamWriter(System.out))

//    val A = sc.next()
    val A = 0.until(200000).map(_ => '0').mkString("")
    val t0 = System.nanoTime()

    case class Ret(valid: Boolean, seqs: List[List[Int]])
    def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {
      if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)
      else {
        if (A(ind) == '0') {
          if (eo.size == 0) rec(ind + 1, List(ind) :: ez, eo)
          else {
            val first = eo.head
            rec(ind + 1, (ind :: first) :: ez, eo.tail)
          }
        } else {
          if (ez.size == 0) Ret(false, null)
          else {
            val first = ez.head
            rec(ind + 1, ez.tail, (ind :: first) :: eo)
          }
        }
      }
    }

    val result = rec(0, List[List[Int]](), List[List[Int]]())

    if (result.valid) {
      bw.write(result.seqs.size + "\n")
      result.seqs.foreach(seq => {bw.write(seq.size + " "); bw.write(seq.reverse.map(_ + 1).mkString(" ")); bw.write("\n")})
    } else {
      bw.write("-1\n")
    }

    val t1 = System.nanoTime()
//    bw.write(t1 - t0 + "")

    bw.flush()
  }
}

import java.io.BufferedWriter
import java.io.OutputStreamWriter
import java.io.InputStreamReader
import java.io.BufferedReader
import java.util.Scanner

import scala.language.implicitConversions

object Zebras {
  class Lazy[A](x: => A) {
    lazy val value = x
    override def toString(): String = value.toString()
  }
  object Lazy {
    def apply[A](x: => A) = new Lazy(x)
    implicit def fromLazy[A](z: Lazy[A]): A = z.value
    implicit def toLazy[A](x: => A): Lazy[A] = Lazy(x)
  }
  def memoize[I, O](f: I => O): I => O = new collection.mutable.HashMap[I, O]() {
    override def apply(key: I) = getOrElseUpdate(key, f(key))
  }

  def main(args: Array[String]): Unit = {
    val br = new BufferedReader(new InputStreamReader(System.in))
    val bw = new BufferedWriter(new OutputStreamWriter(System.out))

//    val A = br.readLine()
    val A = 0.until(200000).map(_ => '0').mkString("")
//    val t0 = System.nanoTime()

    case class Ret(valid: Boolean, seqs: List[List[Int]])
    def rec(ind: Int, ez: List[List[Int]], eo: List[List[Int]]): Ret = {
      if (ind == A.size) if (eo.size == 0) Ret(true, ez) else Ret(false, null)
      else {
        if (A(ind) == '0') {
          if (eo.size == 0) rec(ind + 1, List(ind + 1) :: ez, eo)
          else {
            val first = eo.head
            rec(ind + 1, ((ind + 1) :: first) :: ez, eo.tail)
          }
        } else {
          if (ez.size == 0) Ret(false, null)
          else {
            val first = ez.head
            rec(ind + 1, ez.tail, ((ind + 1) :: first) :: eo)
          }
        }
      }
    }

    val result = rec(0, List[List[Int]](), List[List[Int]]())

    if (result.valid) {
      bw.write(result.seqs.size + "\n")
      result.seqs.foreach(seq => {bw.write(seq.size + " "); seq.reverse.foreach(x => bw.write(x + " ")); bw.write("\n")})
    } else {
      bw.write("-1\n")
    }

//    val t1 = System.nanoTime()
//    bw.write(t1 - t0 + "")

    bw.flush()
  }
}


Vivek has encountered a problem. He has a maze that can be represented as an $$$n \times m$$$ grid. Each of the grid cells may represent the following:  Empty — '.'  Wall — '#'  Good person  — 'G'  Bad person — 'B' The only escape from the maze is at cell $$$(n, m)$$$.A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell $$$(n,m)$$$ is empty. Vivek can also block this cell.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — the number of rows and columns in the maze. Each of the next $$$n$$$ lines contain $$$m$$$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.

For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No" You may print every letter in any case (upper or lower).

NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell $$$(2,2)$$$, and if it is replaced with a wall then the good person at $$$(1,2)$$$ will not be able to escape.For the fourth test case, the good person at $$$(1,1)$$$ cannot escape.For the fifth test case, Vivek can block the cells $$$(2,3)$$$ and $$$(2,2)$$$.For the last test case, Vivek can block the destination cell $$$(2, 2)$$$.

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray
      val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)
      val canGoodGuysReach = reachGood(grid, nm.head, nm.last)
      println(if (couldBlockBadGuys && canGoodGuysReach) "Yes" else "No")
    }
  }

  def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    val marked = Array.ofDim[Boolean](n, m)

    def dfs(i: Int, j: Int): Unit = {
      if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != '#' &&  grid(i - 1)(j) != 'B') {
        marked(i - 1)(j) = true
        dfs(i - 1, j)
      }
      if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != '#' && grid(i)(j - 1) != 'B') {
        marked(i)(j - 1) = true
        dfs(i, j - 1)
      }
      if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != '#'&& grid(i + 1)(j) != 'B') {
        marked(i + 1)(j) = true
        dfs(i + 1, j)
      }
      if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != '#' && grid(i)(j + 1) != 'B') {
        marked(i)(j + 1) = true
        dfs(i, j + 1)
      }
    }

    if (grid(n - 1)(m - 1) != '#' && grid(n - 1)(m - 1) != 'B') {
      marked(n - 1)(m - 1) = true
      dfs(n - 1, m - 1)
    }
    for (i <- marked.indices) {
      for (j <- marked(i).indices) {
        if (grid(i)(j) == 'G' && !marked(i)(j)) return false
      }
    }
    grid(n - 1)(m - 1) != 'B'
  }

  def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    for (i <- grid.indices) {
      for (j <- grid(i).indices) {
        if (grid(i)(j) == 'B') {
          if (i > 0) {
            if (grid(i - 1)(j) == 'G') return false
            if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = '#'
          }
          if (j > 0) {
            if (grid(i)(j - 1) == 'G') return false
            if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = '#'
          }
          if (i < n - 1) {
            if (grid(i + 1)(j) == 'G') return false
            if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = '#'
          }
          if (j < m - 1) {
            if (grid(i)(j + 1) == 'G') return false
            if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = '#'
          }
        }
      }
    }

    true
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

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

  for (_ <- 1 to nextInt) {
    val n, m = nextInt
    val maze = Array.fill(n){ nextLine.toCharArray }

    @inline def get(r: Int, c: Int): Char = {
      if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'
    }

    var can = true

    var r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == '.' &&
          ((r > 0 && maze(r - 1)(c) == 'B') ||
            (r < n - 1 && maze(r + 1)(c) == 'B') ||
            (c > 0 && maze(r)(c - 1) == 'B') ||
            (c < m - 1 && maze(r)(c + 1) == 'B'))) {
          maze(r)(c) = '#'
        } else if (maze(r)(c) == 'G' &&
          ((r > 0 && maze(r - 1)(c) == 'B') ||
            (r < n - 1 && maze(r + 1)(c) == 'B') ||
            (c > 0 && maze(r)(c - 1) == 'B') ||
            (c < m - 1 && maze(r)(c + 1) == 'B'))) {
          can = false
        }
        c += 1
      }
      r += 1
    }

    def dfs(r: Int, c: Int): Unit = {
      maze(r)(c) = '#'
      if (r > 0 && maze(r - 1)(c) != '#') dfs(r - 1, c)
      if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)
      if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)
      if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)
    }

    val s0 = maze(n - 1)(m - 1)
    if (s0 == 'B') can = false
    if ((s0 == 'G' || s0 == '.') && can) {
      dfs(n - 1, m - 1)
    }

    r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == 'G') can = false
        c += 1
      }
      r += 1
    }

    val res = can

    out.println(if (res) "Yes" else "No")

    out.flush()
  }

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

object D {

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

  for (_ <- 1 to nextInt) {
    val n, m = nextInt
    val maze = Array.fill(n){ nextLine.toCharArray }

    @inline def get(r: Int, c: Int): Char = {
      if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'
    }

    var can = true

    var r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == '.' &&
          (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {
          maze(r)(c) = '#'
        } else if (maze(r)(c) == 'G' &&
          (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {
          can = false
        }
        c += 1
      }
      r += 1
    }

    def dfs(r: Int, c: Int): Unit = {
      maze(r)(c) = '#'
      if (r > 0 && maze(r - 1)(c) != '#') dfs(r - 1, c)
      if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)
      if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)
      if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)
    }

    val s0 = maze(n - 1)(m - 1)
    if (s0 == 'B') can = false
    if ((s0 == 'G' || s0 == '.') && can) {
      dfs(n - 1, m - 1)
    }

    r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == 'G') can = false
        c += 1
      }
      r += 1
    }

    val res = can

    out.println(if (res) "Yes" else "No")

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

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray
      val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)
      val canGoodGuysReach = reachGood(grid, nm.head, nm.last)
      println(if (couldBlockBadGuys && canGoodGuysReach) "Yes" else "No")
    }
  }

  def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    val marked = Array.ofDim[Boolean](n, m)

    def dfs(i: Int, j: Int): Unit = {
      if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W') {
        marked(i - 1)(j) = true
        dfs(i - 1, j)
      }
      if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W') {
        marked(i)(j - 1) = true
        dfs(i, j - 1)
      }
      if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W') {
        marked(i + 1)(j) = true
        dfs(i + 1, j)
      }
      if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W') {
        marked(i)(j + 1) = true
        dfs(i, j + 1)
      }
    }

    if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') dfs(n - 1, m - 1)
    for (i <- marked.indices) {
      for (j <- marked(i).indices) {
        if (grid(i)(j) == 'G' && ! marked(i)(j)) return false
      }
    }
    true
  }

  def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    for (i <- grid.indices) {
      for (j <- grid(i).indices) {
        if (grid(i)(j) == 'B') {
          if (i > 0) {
            if (grid(i - 1)(j) == 'G') return false
            if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'
          }
          if (j > 0) {
            if (grid(i)(j - 1) == 'G') return false
            if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'
          }
          if (i < n - 1) {
            if (grid(i + 1)(j) == 'G') return false
            if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'
          }
          if (j < m - 1) {
            if (grid(i)(j + 1) == 'G') return false
            if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'
          }
        }
      }
    }

    true
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray
      val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)
      val canGoodGuysReach = reachGood(grid, nm.head, nm.last)
      println(if (couldBlockBadGuys && canGoodGuysReach) "Yes" else "No")
    }
  }

  def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    val marked = Array.ofDim[Boolean](n, m)

    def dfs(i: Int, j: Int): Unit = {
      if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W') {
        marked(i - 1)(j) = true
        dfs(i - 1, j)
      }
      if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W') {
        marked(i)(j - 1) = true
        dfs(i, j - 1)
      }
      if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W') {
        marked(i + 1)(j) = true
        dfs(i + 1, j)
      }
      if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W') {
        marked(i)(j + 1) = true
        dfs(i, j + 1)
      }
    }

    if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') {
      dfs(n - 1, m - 1)
      marked(n - 1)(m - 1) = true
    }
    for (i <- marked.indices) {
      for (j <- marked(i).indices) {
        if (grid(i)(j) == 'G' && ! marked(i)(j)) return false
      }
    }
    true
  }

  def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    for (i <- grid.indices) {
      for (j <- grid(i).indices) {
        if (grid(i)(j) == 'B') {
          if (i > 0) {
            if (grid(i - 1)(j) == 'G') return false
            if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'
          }
          if (j > 0) {
            if (grid(i)(j - 1) == 'G') return false
            if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'
          }
          if (i < n - 1) {
            if (grid(i + 1)(j) == 'G') return false
            if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'
          }
          if (j < m - 1) {
            if (grid(i)(j + 1) == 'G') return false
            if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'
          }
        }
      }
    }

    true
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray
      val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)
      val canGoodGuysReach = reachGood(grid, nm.head, nm.last)
      println(if (couldBlockBadGuys && canGoodGuysReach) "Yes" else "No")
    }
  }

  def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    val marked = Array.ofDim[Boolean](n, m)

    def dfs(i: Int, j: Int): Unit = {
      if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W') {
        marked(i - 1)(j) = true
        dfs(i - 1, j)
      }
      if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W') {
        marked(i)(j - 1) = true
        dfs(i, j - 1)
      }
      if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W') {
        marked(i + 1)(j) = true
        dfs(i + 1, j)
      }
      if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W') {
        marked(i)(j + 1) = true
        dfs(i, j + 1)
      }
    }

    if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') {
      marked(n - 1)(m - 1) = true
      dfs(n - 1, m - 1)
    }
    for (i <- marked.indices) {
      for (j <- marked(i).indices) {
        if (grid(i)(j) == 'G' && !marked(i)(j)) return false
      }
    }
    grid(n - 1)(m - 1) != 'B'
  }

  def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    for (i <- grid.indices) {
      for (j <- grid(i).indices) {
        if (grid(i)(j) == 'B') {
          if (i > 0) {
            if (grid(i - 1)(j) == 'G') return false
            if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'
          }
          if (j > 0) {
            if (grid(i)(j - 1) == 'G') return false
            if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'
          }
          if (i < n - 1) {
            if (grid(i + 1)(j) == 'G') return false
            if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'
          }
          if (j < m - 1) {
            if (grid(i)(j + 1) == 'G') return false
            if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'
          }
        }
      }
    }

    true
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray
      val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)
      val canGoodGuysReach = reachGood(grid, nm.head, nm.last)
      println(if (couldBlockBadGuys && canGoodGuysReach) "Yes" else "No")
    }
  }

  def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    val marked = Array.ofDim[Boolean](n, m)

    def dfs(i: Int, j: Int): Unit = {
      if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != '#' &&  grid(i - 1)(j) != 'B') {
        marked(i - 1)(j) = true
        dfs(i - 1, j)
      }
      if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != '#' && grid(i)(j - 1) != 'B') {
        marked(i)(j - 1) = true
        dfs(i, j - 1)
      }
      if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != '#'&& grid(i + 1)(j) != 'B') {
        marked(i + 1)(j) = true
        dfs(i + 1, j)
      }
      if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != '#' && grid(i)(j + 1) != 'B') {
        marked(i)(j + 1) = true
        dfs(i, j + 1)
      }
    }

    if (grid(n - 1)(m - 1) != '#' && grid(n - 1)(m - 1) != 'B') {
      marked(n - 1)(m - 1) = true
      dfs(n - 1, m - 1)
    }
    for (i <- marked.indices) {
      for (j <- marked(i).indices) {
        if (grid(i)(j) == 'G' && !marked(i)(j)) return false
      }
    }
    grid(n - 1)(m - 1) != 'B'
  }

  def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    for (i <- grid.indices) {
      for (j <- grid(i).indices) {
        if (grid(i)(j) == 'B') {
          if (i > 0) {
            if (grid(i - 1)(j) == 'G') return false
            if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'
          }
          if (j > 0) {
            if (grid(i)(j - 1) == 'G') return false
            if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'
          }
          if (i < n - 1) {
            if (grid(i + 1)(j) == 'G') return false
            if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'
          }
          if (j < m - 1) {
            if (grid(i)(j + 1) == 'G') return false
            if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'
          }
        }
      }
    }

    true
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

import scala.io.StdIn.readLine

object Solution {
  val mod: Int = Math.pow(10, 9).toInt + 7

  def main(args: Array[String]): Unit = {
    //    val src = io.Source.fromFile("/usr/share/dict/words")
    //    val lines = src.getLines()
    //    src.close()
    val t = readLine().toInt
    for (i <- 1 to t) {
      val nm = readIntLine()
      val grid = (1 to nm.head).map(_ => readLine().toCharArray).toArray
      val couldBlockBadGuys = blockBadGuys(grid, nm.head, nm.last)
      val canGoodGuysReach = reachGood(grid, nm.head, nm.last)
      println(if (couldBlockBadGuys && canGoodGuysReach) "Yes" else "No")
    }
  }

  def reachGood(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    val marked = Array.ofDim[Boolean](n, m)

    def dfs(i: Int, j: Int): Unit = {
      if (i > 0 && !marked(i - 1)(j) && grid(i - 1)(j) != 'W' &&  grid(i - 1)(j) != 'B') {
        marked(i - 1)(j) = true
        dfs(i - 1, j)
      }
      if (j > 0 && !marked(i)(j - 1) && grid(i)(j - 1) != 'W' && grid(i)(j - 1) != 'B') {
        marked(i)(j - 1) = true
        dfs(i, j - 1)
      }
      if (i < n - 1 && !marked(i + 1)(j) && grid(i + 1)(j) != 'W'&& grid(i + 1)(j) != 'B') {
        marked(i + 1)(j) = true
        dfs(i + 1, j)
      }
      if (j < m - 1 && !marked(i)(j + 1) && grid(i)(j + 1) != 'W' && grid(i)(j + 1) != 'B') {
        marked(i)(j + 1) = true
        dfs(i, j + 1)
      }
    }

    if (grid(n - 1)(m - 1) != 'W' && grid(n - 1)(m - 1) != 'B') {
      marked(n - 1)(m - 1) = true
      dfs(n - 1, m - 1)
    }
    for (i <- marked.indices) {
      for (j <- marked(i).indices) {
        if (grid(i)(j) == 'G' && !marked(i)(j)) return false
      }
    }
    grid(n - 1)(m - 1) != 'B'
  }

  def blockBadGuys(grid: Array[Array[Char]], n: Int, m: Int): Boolean = {
    for (i <- grid.indices) {
      for (j <- grid(i).indices) {
        if (grid(i)(j) == 'B') {
          if (i > 0) {
            if (grid(i - 1)(j) == 'G') return false
            if (grid(i - 1)(j) != 'B') grid(i - 1)(j) = 'W'
          }
          if (j > 0) {
            if (grid(i)(j - 1) == 'G') return false
            if (grid(i)(j - 1) != 'B') grid(i)(j - 1) = 'W'
          }
          if (i < n - 1) {
            if (grid(i + 1)(j) == 'G') return false
            if (grid(i + 1)(j) != 'B') grid(i + 1)(j) = 'W'
          }
          if (j < m - 1) {
            if (grid(i)(j + 1) == 'G') return false
            if (grid(i)(j + 1) != 'B') grid(i)(j + 1) = 'W'
          }
        }
      }
    }

    true
  }

  def matching(first: Array[Int], second: Array[Int]): Int = {
    val n = first.length
    val mapInt = Array.ofDim[Int](first.length)
    for (i <- first.indices) {
      mapInt(first(i) - 1) = i + 1
    }

    val differences = Array.ofDim[Int](second.length)
    for (i <- first.indices) {
      differences( (mapInt(second(i) - 1) - i - 1 + n) % n) += 1
    }

    var max = 0
    for (i <- differences.indices) {
      if (differences(i) > max)
        max = differences(i)
    }

    max
  }

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

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

  def printArray[T](arr: Array[T]): Unit = {
    print(arr(0))
    for (i <- 1 until arr.length) {
      print(" " + arr(i))
    }
    println()
  }

}

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

  for (_ <- 1 to nextInt) {
    val n, m = nextInt
    val maze = Array.fill(n){ nextLine.toCharArray }

    def get(r: Int, c: Int): Char = {
      if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'
    }

    for (r <- 0 until n) {
      for (c <- 0 until m) {
        if (maze(r)(c) == '.' &&
          (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {
          maze(r)(c) = '#'
        }
      }
    }

    def dfs(r: Int, c: Int): Unit = {
      maze(r)(c) = '#'
      if (get(r - 1, c) != '#') dfs(r - 1, c)
      if (get(r + 1, c) != '#') dfs(r + 1, c)
      if (get(r, c - 1) != '#') dfs(r, c - 1)
      if (get(r, c + 1) != '#') dfs(r, c + 1)
    }

    val s0 = maze(n - 1)(m - 1)
    if (s0 == 'G' || s0 == '.') dfs(n - 1, m - 1)

    val res = !maze.exists(_.contains('G'))

    out.println(if (res) "Yes" else "No")

    out.flush()
  }

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

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

  for (_ <- 1 to nextInt) {
    val n, m = nextInt
    val maze = Array.fill(n){ nextLine.toCharArray }

    @inline def get(r: Int, c: Int): Char = {
      if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'
    }

    var can = true

    var r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == '.' &&
          (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {
          maze(r)(c) = '#'
        } else if (maze(r)(c) == 'G' &&
          (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {
          can = false
        }
        c += 1
      }
      r += 1
    }

    def dfs(r: Int, c: Int): Unit = {
      maze(r)(c) = '#'
      if (r > 0 && maze(r)(c) != '#') dfs(r - 1, c)
      if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)
      if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)
      if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)
    }

    val s0 = maze(n - 1)(m - 1)
    if (s0 == 'B') can = false
    if ((s0 == 'G' || s0 == '.') && can) {
      dfs(n - 1, m - 1)
    }

    r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == 'G') can = false
        c += 1
      }
      r += 1
    }

    val res = can

    out.println(if (res) "Yes" else "No")

    out.flush()
  }

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

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

  for (_ <- 1 to nextInt) {
    val n, m = nextInt
    val maze = Array.fill(n){ nextLine.toCharArray }

    @inline def get(r: Int, c: Int): Char = {
      if (r >= 0 && r < n && c >= 0 && c < m) maze(r)(c) else '#'
    }

    var can = true

    var r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == '.' &&
          (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {
          maze(r)(c) = '#'
        } else if (maze(r)(c) == 'G' &&
          (get(r - 1, c) == 'B' || get(r + 1, c) == 'B' || get(r, c - 1) == 'B' || get(r, c + 1) == 'B')) {
          can = false
        }
        c += 1
      }
      r += 1
    }

    def dfs(r: Int, c: Int): Unit = {
      maze(r)(c) = '#'
      if (r > 0 && maze(r)(c) != '#') dfs(r - 1, c)
      if (r < n - 1 && maze(r + 1)(c) != '#') dfs(r + 1, c)
      if (c > 0 && maze(r)(c - 1) != '#') dfs(r, c - 1)
      if (c < m - 1 && maze(r)(c + 1) != '#') dfs(r, c + 1)
    }

    val s0 = maze(n - 1)(m - 1)
    if ((s0 == 'G' || s0 == '.') && can) {
      dfs(n - 1, m - 1)
    }

    r = 0
    while (r < n) {
      var c = 0
      while (c < m) {
        if (maze(r)(c) == 'G') can = false
        c += 1
      }
      r += 1
    }

    val res = can

    out.println(if (res) "Yes" else "No")

    out.flush()
  }

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


Martians are actively engaged in interplanetary trade. Olymp City, the Martian city known for its spaceport, has become a place where goods from all the corners of our Galaxy come. To deliver even more freight from faraway planets, Martians need fast spaceships.A group of scientists conducts experiments to build a fast engine for the new spaceship. In the current experiment, there are $$$n$$$ elementary particles, the $$$i$$$-th of them has type $$$a_i$$$.Denote a subsegment of the particle sequence ($$$a_1, a_2, \dots, a_n$$$) as a sequence ($$$a_l, a_{l+1}, \dots, a_r$$$) for some left bound $$$l$$$ and right bound $$$r$$$ ($$$1 \le l \le r \le n$$$). For instance, the sequence $$$(1\ 4\ 2\ 8\ 5\ 7)$$$ for $$$l=2$$$ and $$$r=4$$$ has the sequence $$$(4\ 2\ 8)$$$ as a subsegment. Two subsegments are considered different if at least one bound of those subsegments differs.Note that the subsegments can be equal as sequences but still considered different. For example, consider the sequence $$$(1\ 1\ 1\ 1\ 1)$$$ and two of its subsegments: one with $$$l=1$$$ and $$$r=3$$$ and another with $$$l=2$$$ and $$$r=4$$$. Both subsegments are equal to $$$(1\ 1\ 1)$$$, but still considered different, as their left and right bounds differ.The scientists want to conduct a reaction to get two different subsegments of the same length. Denote this length $$$k$$$. The resulting pair of subsegments must be harmonious, i. e. for some $$$i$$$ ($$$1 \le i \le k$$$) it must be true that the types of particles on the $$$i$$$-th position are the same for these two subsegments. For example, the pair $$$(1\ 7\ 3)$$$ and $$$(4\ 7\ 8)$$$ is harmonious, as both subsegments have $$$7$$$ on the second position. The pair $$$(1\ 2\ 3)$$$ and $$$(3\ 1\ 2)$$$ is not harmonious.The longer are harmonious subsegments, the more chances for the scientists to design a fast engine. So, they asked you to calculate the maximal possible length of harmonious pair made of different subsegments.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The following are descriptions of the test cases. The first line contains an integer $$$n$$$ ($$$2 \le n \le 150\,000$$$) — the amount of elementary particles in the sequence. The second line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 150\,000$$$) — types of elementary particles. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3\cdot10^5$$$.

For each test, print a single integer, maximal possible length of harmonious pair made of different subsegments. If such pair does not exist, print $$$-1$$$ instead.

NoteThe first test case is shown on the picture below:  As you can see from it, you may choose the subsegments $$$(2\ 1\ 3\ 4)$$$ and $$$(3\ 1\ 5\ 2)$$$, which are a harmonious pair. Their length is equal to $$$4$$$, so the answer is $$$4$$$.In the second test case, you need to take two subsegments: one with $$$l=1$$$ and $$$r=5$$$, and one with $$$l=2$$$ and $$$r=6$$$. It's not hard to observe that these segments are a harmonious pair and considered different even though they are both equal to $$$(1\ 1\ 1\ 1\ 1)$$$.In the third test case, you cannot make a harmonious pair, so the answer is $$$-1$$$.

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

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

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

    case class pair(val l: Int, val r: Int, val c: Long)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (r-l).compareTo(that.r-that.l)
        }
    }

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

    val t = readInt()
    val po = new Array[Int](maxn)

    for (tt <- 1 to t) {
        val n = readInt()
        var ans = -1
        var a = 0
        for (i <- 1 to 150000) {
            po(i) = 0
        }
        for (i <- 1 to n) {
            a = readInt()
            if (po(a) != 0) {
                ans = max(ans, po(a) + n - i)
            }
            po(a) = i
        }
        writer.println(ans)

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