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

  override def apply(io: IO): io.type = {
    val seq = Seq(4, 8, 15, 16, 23, 42).zipWithIndex.toMap
    val nums = io.read[Seq[Int]].map(seq)

    val table = mutable.Map.empty[Int, Int].withDefaultValue(0)

    var ans = 0

    nums foreach {
      case 0 => table(0) += 1
      case n if table(n - 1) == 0 => ans += 1
      case n =>
        table(n - 1) -= 1
        table(n) += 1
    }

    ans += table.collect({ case (k, v) if k < 5 => v*(k+1) }).sum

    io.write(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 apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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

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

object CF565C extends App {

  import scala.io.StdIn

  var map = Map(4 -> 0, 8 -> 1, 15 -> 2, 16 -> 3, 23 -> 4, 42 -> 5)

  val n = StdIn.readInt
  val as = StdIn.readLine.split(" ").map(x => map.get(x.toInt).get)

  var array = Array.ofDim[Int](6)
  var array2 = Array.ofDim[Int](6)
  var drop = 0

  for (a <- as) {
    if (a == 0) {
      array(a) += 1
      array2(a) += 1
    } else {
      if (array(a - 1) > 0) {
        array(a - 1) -= 1
        array(a) += 1
        array2(a) += 1

        if (a == 5) {
          for (i <- 0 until 6) {
            array2(i) -= 1
          }
          array(5) -= 1
        }
      } else {
        drop += 1
      }
    }
  }

  drop += array2.sum

  println(drop)
}

import scala.collection.mutable

object Lost {

  val in = new java.util.Scanner(System.in)

  def nextInt = in.next().toInt

  def findCount(array: Array[Int]): Int = {
    var count = array.length

    if (array.isEmpty) return count
    val buff = new mutable.HashMap[Int, Int]().withDefaultValue(0)

    for (el <- array) {
      if (el == 4) {
        buff.update(8, buff(8) + 1)
      }
      else {
        if (buff.contains(el)) {
          val next = el match {
            case 8 => 15
            case 15 => 16
            case 16 => 23
            case 23 => 42
            case 42 => 1
          }
          if (buff(el) == 1) buff.remove(el)
          else buff.update(el, buff(el) - 1)
          buff.update(next, buff(next) + 1)
          if (el == 42) count -= 6
        }
      }
    }

    count
  }

  def main(args: Array[String]): Unit = {
    val size = in.nextLine
    val array = in.nextLine.split(" ").map(_.toInt)
    println(findCount(array))
  }

}

import scala.collection.mutable

object Lost {

  val in = new java.util.Scanner(System.in)

  def nextInt = in.next().toInt

  def findCount(array: Array[Int]): Int = {
    var count = array.length

    if (array.isEmpty) return count

    val buff = new mutable.HashMap[Int, Int]().withDefaultValue(0)
    for (el <- array) {
      if (el == 4) {
        buff.update(8, buff(8) + 1)
      }
      else {
        if (buff.contains(el)) {
          val next = el match {
            case 8 => 15
            case 15 => 16
            case 16 => 23
            case 23 => 42
            case 42 => 1
          }
          buff.update(el, buff(el) - 1)
          buff.update(next, buff(next) + 1)
          if (el == 42) count -= 6
        }
      }
    }

    count
  }

  def main(args: Array[String]): Unit = {
    val size = in.nextLine
    val array = in.nextLine.split(" ").map(_.toInt)
    println(findCount(array))
  }

}


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

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 CE87A(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 CE87A(fScanner: Main.FastScanner, out: java.io.PrintWriter) {

  import Main._
  import fScanner._

  def solve(): Unit = {
    val t= ni()
    REP(t) { _ =>
      val s = ns()
      val a = Array.fill[Int](3)(-1)
      var mn = Int.MaxValue
      REP(s.length) { i =>
        a(s.charAt(i) - '1') = i
        if(!a.contains(-1)){
          val y = a.max - a.min + 1
          if(y < mn) mn = y
        }
      }
      if(mn == Int.MaxValue){
        out.println(0)
      } else out.println(mn)
    }
  }
}

object ProblemB extends App {

  import java.io.{BufferedReader, InputStreamReader, PrintWriter}
  import java.util.StringTokenizer
  import scala.collection.mutable

  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 t = in.nextInt()
  for (_ <- 1 to t) {
    val s = in.nextToken()
    val count1 = new Array[Int](s.length + 1)
    val count2 = new Array[Int](s.length + 1)
    val count3 = new Array[Int](s.length + 1)
    var index = 0
    var result = Int.MaxValue

    for (i <- 1 to s.length) {
      if (i >  0) {
        count1(i) = count1(i - 1)
        count2(i) = count2(i - 1)
        count3(i) = count3(i - 1)
      }
      s(i - 1) match {
        case '1' =>
          count1(i) = count1(i) + 1
        case '2' =>
          count2(i) = count2(i) + 1
        case '3' =>
          count3(i) = count3(i) + 1
      }

      while (count1(i) - count1(index) > 0 && count2(i) - count2(index) > 0 && count3(i) - count3(index) > 0) {
        if (i - index < result) {
          result = i - index
        }
        index = index + 1
      }
    }

    if (result == Int.MaxValue) {
      result = 0
    }

    println(result)

  }

}


import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000

  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong

  read()
  val n = int()
  read()
  val a = Array.fill(n)(int())
  val b = readLine().toCharArray.map {
    case '0' => false
    case _ => true
  }

  var lmax = INF
  var lmin = -INF
  var rmax = INF
  var rmin = -INF

  for ((as, bs) <- a.sliding(5) zip b.sliding(5)) {
    bs match {
      case (Array(true, true, true, true, false)) =>
        rmax = Math.min(rmax, as.min - 1)
//      case (Array(true, true, true, true, true)) =>
//        rmin = as.min
//      case (Array(false, false, false, false, false)) =>
//        lmax = as.max
      case (Array(false, false, false, false, true)) =>
        lmin = Math.max(lmin, as.max + 1)
      case _ =>
    }
  }

  println(lmin + " " + rmax)

}

object dAlenaHeater {

  import scala.io.StdIn.{readInt, readLine}
  def heater(arr: Array[Int], b: Array[Int]):(Int, Int) = {

    def change(four: List[Int], rest: List[Int], pat: List[Int], l: Int, r: Int):(Int, Int) =
      pat match {
        case 0 :: 1 :: _ if rest.isEmpty => ((l :: four).max, r)
        case 0 :: 1 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, (l :: four).max, r)
        case 1 :: 0 :: _ if rest.isEmpty => (l, (r :: four).min)
        case 1 :: 0 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, (r :: four).min)
        case _ if rest.isEmpty => (l, r)
        case Nil => (l, r)
        case _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, r)
      }

    val pair = change(arr.take(5).toList, arr.drop(5).toList, b.drop(3).toList, -1000000001, 1000000001 )
    (pair._1 + 1, pair._2 - 1)
  }

  def main(args: Array[String]):Unit = {
    val n = readInt()
    val arr: Array[Int] = readLine().split(" ").map(_.toInt)
    val b = readLine().toCharArray.map(_.asDigit)
    val (l, r) = heater(arr, b)

    println(s"$l $r")
  }
}

object dAlenaHeater {

  import scala.io.StdIn.{readInt, readLine}
  def heater(arr: Array[Int], b: Array[Int]):(Int, Int) = {

    def change(four: List[Int], rest: List[Int], pat: List[Int], l: Int, r: Int):(Int, Int) =
      pat match {
        case 0 :: 1 :: _ if rest.isEmpty => ((l :: four).max, r)
        case 0 :: 1 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, (l :: four).max, r)
        case 1 :: 0 :: _ if rest.isEmpty => (l, (r :: four).min)
        case 1 :: 0 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, (r :: four).min)
        case _ if rest.isEmpty => (l, r)
        case Nil => (l, r)
        case _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, r)
      }

    val pair = change(arr.take(5).toList, arr.drop(5).toList, b.drop(3).toList, Int.MinValue, Int.MaxValue )
    (pair._1 + 1, pair._2 - 1)
  }

  def main(args: Array[String]):Unit = {
    val n = readInt()
    val arr: Array[Int] = readLine().split(" ").map(_.toInt)
    val b = readLine().toCharArray.map(_.toInt)
    val l, r = heater(arr, b)
    println(s"$l $r")
  }
}

object dAlenaHeater {

  import scala.io.StdIn.{readInt, readLine}
  def heater(arr: Array[Int], b: Array[Int]):(Int, Int) = {

    def change(four: List[Int], rest: List[Int], pat: List[Int], l: Int, r: Int):(Int, Int) =
      pat match {
        case 0 :: 1 :: _ if rest.isEmpty => ((l :: four).max, r)
        case 0 :: 1 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, (l :: four).max, r)
        case 1 :: 0 :: _ if rest.isEmpty => (l, (r :: four).min)
        case 1 :: 0 :: _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, (r :: four).min)
        case _ if rest.isEmpty => (l, r)
        case Nil => (l, r)
        case _ => change(four.tail :+ rest.head, rest.tail, pat.tail, l, r)
      }

    val pair = change(arr.take(5).toList, arr.drop(5).toList, b.drop(3).toList, Int.MinValue, Int.MaxValue )
    (pair._1 + 1, pair._2 - 1)
  }

  def main(args: Array[String]):Unit = {
    val n = readInt()
    val arr: Array[Int] = readLine().split(" ").map(_.toInt)
    val b = readLine().toCharArray.map(_.asDigit)
    val (l, r) = heater(arr, b)

    println(s"$l $r")
  }
}

import java.util.StringTokenizer

object D extends App {
  val INF = 1000000000

  var st: StringTokenizer = _
  def read() = { st = new StringTokenizer(readLine()) }
  def int() = st.nextToken().toInt
  def long() = st.nextToken().toLong

  read()
  val n = int()
  read()
  val a = Array.fill(n)(int())
  val b = readLine().toCharArray.map {
    case '0' => false
    case _ => true
  }

  var lmax = INF
  var lmin = -INF
  var rmax = INF
  var rmin = -INF

  for ((as, bs) <- a.sliding(5) zip b.sliding(5)) {
    bs match {
      case (Array(true, true, true, true, false)) =>
        rmax = as.min - 1
//      case (Array(true, true, true, true, true)) =>
//        rmin = as.min
//      case (Array(false, false, false, false, false)) =>
//        lmax = as.max
      case (Array(false, false, false, false, true)) =>
        lmin = as.max + 1
      case _ =>
    }
  }

  println(lmin + " " + rmax)

}


import scala.collection.mutable.ArrayBuffer
import scala.io.Source

object Main extends App {
  val input = Source.fromInputStream(System.in).getLines()
  val t = input.next().toInt
  val nList = new ArrayBuffer[Int]()
  for (i <- 0 until t) nList.append(input.next().toInt)

  val p2s = Range(1, 30).map(math.pow(2, _).toInt).toList
  def getMaxP2(n: Int) = {
    var list = p2s
    var res = list.head
    while (n >= list.head) {
      res = list.head
      list = list.tail
    }
    res
  }

  for (n <- nList) {
    if (n == 2) println("0 1")
    else {
      val mp2 = getMaxP2(n - 1)
      println((Range(1, mp2) ++ (0 +: Range(mp2, n))).mkString(" "))
    }
  }
}

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(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

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

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        var p = 1
        while (p * 2 < n) {
            p *= 2
        }
        var k = 0
        while (p + k < n) {
            if (k % 2 != n % 2)
                writer.print((p + k)+ " " + k + " ")
            else
                writer.print(k + " " + (p + k) + " ")
            k += 1
        }
        while (k < p) {
            writer.print(k + " ")
            k += 1
        }
        writer.println()

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

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val pillarCount = readInt()
    val twoPowers = 0.to(30).map(i => Math.pow(2, i).toInt)
    val theMaxTwoPower = twoPowers.filter(_ <= pillarCount - 1).last
    val answer = (1.until(theMaxTwoPower).toList :+ 0) ++
      theMaxTwoPower.until(pillarCount).toList
    println(answer.mkString(" "))
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val pillarCount = readInt()
    println(0.until(pillarCount).toList.mkString(" "))
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 1
    }
  }
}

import sun.management.counter.Counter

import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========
  val testNumber = readInt()
  1.to(testNumber).foreach { _ =>
    val pillarCount = readInt()
    val numbers = 0.until(pillarCount).toList
    val answer = numbers.zip(numbers.reverse).flatMap {
      case (a, b) => List(b, a)
    }.take(numbers.length)
    println(answer.mkString(" "))
  }

  //=====Template=========
  def readInts(): Array[Int] = readLine().split(" ").map(_.toInt)
  def readLongs(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readChars(): Array[Char] = readLine().toCharArray
  def asInt(b: Boolean) = if (b) 1 else 0

  class MutableMultiSet[T](seq: Seq[T])(implicit val ord: Ordering[T]) {
    val multiSet: mutable.TreeMap[T, Int] = new mutable.TreeMap[T, Int]()
    seq.foreach { value => add(value) }
    def contains(value: T) = multiSet.contains(value)
    def max: T = multiSet.last._1
    def min: T = multiSet.head._1
    def add(value: T) = multiSet.get(value) match {
      case None => multiSet(value) = 1
      case Some(counter) => multiSet(value) = counter + 1
    }
    def remove(value: T) = multiSet.get(value) match {
      case None => None
      case Some(1) => multiSet.remove(value)
      case Some(counter) => multiSet(value) = counter - 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(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

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

    val t = readInt()

    for (tt <- 1 to t) {
        val n = readInt()
        var p = 1
        while (p * 2 < n) {
            p *= 2
        }
        var k = 0
        while (p + k < n) {
            if (k % 2 == 0)
                writer.print((p + k)+ " " + k + " ")
            else
                writer.print(k + " " + (p + k) + " ")
            k += 1
        }
        while (k < p) {
            writer.print(k + " ")
            k += 1
        }
        writer.println()

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


import scala.io.StdIn._
import scala.collection.mutable.HashSet

object Xor extends App {

	val n = readInt()

	val numbers = Array.tabulate[Int]( n + 1 )( x => x )

	val bit1Max = ~(~0 >>> 1)		// value with leftmost bit set
	for( i <- n to 1 by -1 if numbers( i ) == i ) {
		// find lower bound with most singnificant bit set
		var bit1LB = bit1Max >>> 1
		while( bit1LB > i )
			bit1LB >>>= 1
		// get 'mirror' value arounf lower bound
		val j = bit1LB - ( i - bit1LB + 1 )
		// set both mirrored values
		numbers( i ) = j
		numbers( j ) = i
	}

	// get the beauty value
	println( 1L * n * ( n + 1 ))

	//This was too brutal - and too slow
/*
	val set = Array.fill[Boolean]( n + 1 )( false )

	var mask = ~0 >>> 1
	while( mask >> 1 > n )
		mask >>= 1

	for( i <- n to 0 by -1 ) {
		val v = ~i & mask
		var x = v
		var j = 1
		while( x > n || set( x )) {
			x = v ^ j
			j += 1
		}
		numbers( i ) = x
		set( x ) = true
	}
	def beauty( seq: Array[Int] ) = {
		seq.zipWithIndex.foldLeft( 0L )( (s,p) => s + (p._1 ^ p._2) )
	}

	println( beauty( numbers ))
*/

	println( numbers.mkString( " " ))
}

import io.Source
import java.io.PrintWriter

object CF288C {

  def solve(in: In, out: PrintWriter) {
    var n = in().toInt + 1
    val ans = Array.ofDim[Int](n)
    while (n > 1) {
      val m = 2 * Integer.highestOneBit(n - 1)
      out.flush()
      for (i <- m / 2 until n) {
        ans(i) = m - i - 1
        ans(m - i - 1) = i
      }
      n = m - n
    }
    var xor = 0L
    for (i <- 0 until ans.length) {
      xor += ans(i) ^ i
    }
    out.println(xor)
    out.println(ans.mkString(" "))
  }

  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 java.io._
import collection.immutable._
import scala.collection.mutable.ArrayBuffer

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

  def processStdInOut(): Unit = {
    val src = io.Source.fromInputStream(System.in)
    try {
      val bw = new BufferedWriter(new OutputStreamWriter(System.out));
      try {
        val lines = src.getLines()
        processLines(lines, bw)
      } finally {
        bw.flush()
        bw.close()
      }
    } finally {
      src.close();
    }
  }

  // Standard code above, custom code below

  case class Solution(bestMinBj: Int, minChangeCount: Int, newPlayList: Array[Int])

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val params = lines.next().split(' ').map(_.toInt)
    val n = params(0)
    val m = params(1)
    val performers = lines.next().split(' ').map(_.toInt)
    val solution = solve(n, m, performers)
    bw.write(s"${solution.bestMinBj} ${solution.minChangeCount}")
    bw.newLine()
    bw.write(solution.newPlayList.mkString(" "))
    bw.newLine()
  }

  def solve(n: Int, m: Int, performers: Array[Int]): Solution = {
    val target = n / m  // The maximum value for the minimum number of performances by a preferred band

    // The queues store the zero-based indexes of performances which can be replaced without decreasing the target:
    var queueA = ArrayBuffer[Int]()  // Indexes for non-preferred bands
    val queueB = ArrayBuffer[Int]()  // Indexes for preferred bands that have exceeded the target

    // Count performances by preferred bands:
    val bandCounts = Array.ofDim[Int](m)
    for (i <- 1 to n) {
      val j = performers(i - 1)
      if (j > m) {
        queueA += (i - 1)
      } else {
        val newBandCount = bandCounts(j - 1) + 1
        bandCounts(j - 1) = newBandCount
        if (newBandCount > target) {
          queueB += (i - 1)
        }
      }
    }

    val deltas = bandCounts.map(bc => if (bc >= target) 0 else target - bc)
    val minChangeCount = deltas.sum
    val replacementValues = deltas.zipWithIndex.flatMap {
      deltaAndIndex => IndexedSeq.fill(deltaAndIndex._1)(deltaAndIndex._2 + 1)
    }

    queueA ++= queueB  // Merge the queues, but replace non-preferred bands first
    val replacements = queueA.take(minChangeCount).zip(replacementValues)
    replacements.foreach{ indexAndValue:(Int, Int) => performers(indexAndValue._1) = indexAndValue._2 }

    Solution(target, minChangeCount, performers)
  }
}

import scala.collection.mutable

object C extends App {

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

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var counts = mutable.Map.empty[Int, Int].withDefaultValue(0) ++ as.groupBy(identity).map { case (key, value) => (key, value.length) }
  val sorted = (1 to m).sortBy(counts).reverse
  val max = n / m
  val needs = (sorted.take(n % m).map(a => (a, max + 1)) ++ sorted.drop(n % m).map(a => (a, max))).toMap.withDefaultValue(0)

  var changes = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (counts(a) > needs(a)) {
      (1 to m).find(a => counts(a) < max) match {
        case Some(a2) =>
          as(i) = a2
          counts(a) = counts(a) - 1
          counts(a2) = counts(a2) + 1
          changes += 1
        case _ =>
      }
    }
  }

  println(s"$max $changes")
  println(as.mkString(" "))
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val line = in.next().split(' ').map(_.toInt)
  var shouldBeAtLeast = line.length / m
  var map = line.filter(_ <= m).groupBy(i => i).map(i => i._1 -> i._2.length)
  var less = map.filter(_._2 < shouldBeAtLeast).keySet ++ (1 to m).filter(i => !map.contains(i)).toSet
  var more = map.filter(_._2 > shouldBeAtLeast).keySet
  val ans = line.map{i =>
    if (less.isEmpty || less.contains(i) || map.getOrElse(i, 0) == shouldBeAtLeast)
      i
    else {
      val ch = less.head
      map += ch -> (map.getOrElse(ch, 0) + 1)

      if (map(ch) >= shouldBeAtLeast)
        less -= ch
      if (more.contains(i)) {
        map += i -> (map.getOrElse(i, 0) - 1)
        if (map(i) <= shouldBeAtLeast)
          more -= ch
      }
      ch
    }}
  println(s"${shouldBeAtLeast} ${ans.zip(line).count(i => i._1 != i._2)}")
  println(ans.toList.mkString(" "))
}

import scala.collection.mutable

object C extends App {

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

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var counts = mutable.Map.empty[Int, Int].withDefaultValue(0) ++ as.groupBy(identity).map { case (key, value) => (key, value.length) }
  val sorted = (1 to m).sortBy(counts).reverse
  val max = n / m
  val needs = (sorted.take(n % m).map(a => (a, max + 1)) ++ sorted.drop(n % m).map(a => (a, max))).toMap.withDefaultValue(0)

  var changes = 0
  for (i <- 0 until n) {
    val a = as(i)
    if (counts(a) > needs(a)) {
      val a2 = (1 to m).find(a => counts(a) < needs(a)).get
      as(i) = a2
      counts(a) = counts(a) - 1
      counts(a2) = counts(a2) + 1
      changes += 1
    }
  }

  println(s"$max $changes")
  println(as.mkString(" "))
}


object Main {
    def main(args: Array[String]): Unit = {
        import scala.io.StdIn.readLine

        val T: Int = readLine.toInt
        for(t <- 0 until T) {
            val N: Int = readLine.toInt
            val v: Array[Int] = readLine.split(" ").map(_.toInt)
            var ans = -1;
            for(i <- 0 until (N-1) if (ans == -1))
                if(math.abs(v(i) - v(i + 1)) > 1)
                    ans = i;
            if(ans == -1)   println("NO")
            else {
                println("YES")
                println(s"${ans+1} ${ans+2}")
            }
        }
    }
}

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

  for (_ <- 1 to nextInt) {
    val n = nextInt
    val as = nextInts(n)

    var i = 1
    var ok = false
    while (i < n) {
      if (Math.abs(as(i) - as(i - 1)) >= 2) {
        out.println("YES")
        out.println(s"$i ${i + 1}")
        i = n
        ok = true
      }
      i += 1
    }
    if (!ok) out.println("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 Main {
    def main(args: Array[String]): Unit = {
        import scala.io.StdIn.readLine

        val T: Int = readLine.toInt
        for(t <- 0 until T) {
            val N: Int = readLine.toInt
            val v: Array[Int] = readLine.split(" ").map(_.toInt)
            var ans = -1;
            for(i <- 0 until (N-1) if (ans == -1))
                if(math.abs(v(i) - v(i + 1)) > 1)
                    ans = i;
            if(ans == -1)   println("NO")
            else {
                println("YES")
                println(s"$ans ${ans+1}")
            }
        }
    }
}


object Main extends App {

  def checkPoint(acc: Map[(Int, Int), Int], a: Int, b: Int): Boolean = {
    4 == acc.getOrElse((a,b), 0) + acc.getOrElse((a+1,b), 0) + acc.getOrElse((a,b+1), 0) + acc.getOrElse((a+1,b+1), 0)
  }

  def check(acc: Map[(Int, Int), Int], a: Int, b: Int): Boolean = {
    checkPoint(acc, a-1, b-1) || checkPoint(acc, a-1, b) || checkPoint(acc, a, b-1) || checkPoint(acc, a, b)
  }

  val Array(n, m, k) = readLine.split(" ").map(_.toInt)
  (1 to k).foldLeft(Map[(Int, Int), Int]())({
    case (acc, index) =>
      val Array(a, b) = readLine.split(" ").map(_.toInt)
      val updateMap = acc + ((a,b) -> 1)
      if(check(updateMap, a, b)) {
        println(index)
        System.exit(0)
        updateMap
      } else {
        updateMap
      }
  })

  println("0")
}

/**
 * Created by helfper on 27/01/2015.
 */
object PashaAndPixels {
  def main(args: Array[String]) {
    val Array(n, m, k) = io.StdIn.readLine.split(" ").map(_.toInt)
    val field = Array.fill(n, m)(false)

    println(solve(field, k))
  }

  def solve(field: Array[Array[Boolean]], k: Int): Int = {
    def iterate(m: Int): Int = {
      val Array(i, j) = io.StdIn.readLine.split(" ").map(_.toInt)
      field(i-1)(j-1) = true
      val lose = 0.to(1).exists(di =>
        0.to(1).exists(dj =>
          check(field, i-di, j-dj)
        )
      )
      if (lose) m
      else if (m >= k) 0
      else iterate(m+1)
    }

    iterate(1)
  }

  def check(field: Array[Array[Boolean]], i: Int, j: Int): Boolean =
    0 <= i-1 && i < field.length && 0 <= j-1 && j < field(i).length &&
    field(i-1)(j-1) && field(i)(j-1) && field(i-1)(j) && field(i)(j)
}

import java.util.Scanner;
import scala.util.control.Breaks._

object C508A {

    def main(args: Array[String]) {

        val in = new Scanner(System.in);
        val out = System.out;

        val n = in.nextInt()
        val m = in.nextInt()
        val k = in.nextInt()

        val matrix = Array.ofDim[Int](n + 5, m + 5)

        var x, y = 0
        var ans = 0

        breakable {
            for (i <- 0 until k) {
                x = in.nextInt()
                y = in.nextInt()
                matrix(x)(y) = 1
                if (
                    (matrix(x - 1)(y - 1) == 1 && matrix(x)(y - 1) == 1 && matrix(x - 1)(y) == 1)
                      || (matrix(x + 1)(y - 1) == 1 && matrix(x)(y - 1) == 1 && matrix(x + 1)(y) == 1)
                      || (matrix(x + 1)(y + 1) == 1 && matrix(x)(y + 1) == 1 && matrix(x + 1)(y) == 1)
                      || (matrix(x - 1)(y + 1) == 1 && matrix(x - 1)(y) == 1 && matrix(x)(y + 1) == 1)
                ) {
                    ans = i + 1
                    break
                }
            }
        }

        out.println(ans)

    }

}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m, k) = in.next().split(" ").map(_.toInt)
  var field = Array.ofDim[Boolean](n, m)
  val res = Range(1, k + 1).find{ _ =>
    val Array(a, b) = in.next().split(" ").map(_.toInt - 1)
    field(a)(b) = true
    (a > 0 && b > 0 && field(a - 1)(b - 1) &&
      field(a - 1)(b) && field(a)(b - 1)) ||
      (a < (n - 1) && b > 0 && field(a + 1)(b - 1) &&
        field(a + 1)(b) && field(a)(b - 1)) ||
      (a > 0 && b < (m - 1) && field(a - 1)(b + 1) &&
        field(a - 1)(b) && field(a)(b + 1)) ||
      (a < (n - 1) && b < (m - 1) && field(a + 1)(b + 1) &&
        field(a + 1)(b) && field(a)(b + 1))
  }
  println(res.getOrElse(0))

}

object A508 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n, m, k) = readInts(3)
    val in = Array.fill(n)(Array.fill(m)(false))
    var break = false
    for(test <- 1 to k if !break) {
      val Array(i, j) = readInts(2).map(_-1)
      in(i)(j) = true
      val rightUpper = i-1>=0 && j-1>=0 && in(i-1)(j-1) && in(i-1)(j) && in(i)(j-1)
      val leftUpper = i-1>=0 && j+1<m && in(i-1)(j+1) && in(i-1)(j) && in(i)(j+1)
      val rightLower = i+1<n && j-1>=0 && in(i+1)(j-1) && in(i+1)(j) && in(i)(j-1)
      val leftLower = i+1<n && j+1<m && in(i+1)(j+1) && in(i+1)(j) && in(i)(j+1)
      if(rightUpper || leftUpper || rightLower || leftLower) {
        println(test)
        break = true
      }
    }
    if(!break)
      println("0")
  }

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

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

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

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

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

}

import java.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 18 May 2016
 */
object A508 extends App {

  def checkPosition(n: Int, m: Int, x: Int, y: Int, occupation: Array[Array[Boolean]]): Boolean = {
    if (x >= 0 && x < n && y >= 0 && y < m && occupation(x)(y)) {
      return true
    }
    false
  }

  def checkOccupation(n: Int, m: Int, x: Int, y: Int, occupation: Array[Array[Boolean]]): Boolean = {
    if (checkPosition(n, m, x+1, y, occupation)
      && checkPosition(n, m, x+1, y+1, occupation)
      && checkPosition(n, m, x, y+1, occupation) ) {
      return true
    } else if (checkPosition(n, m, x+1, y, occupation)
      && checkPosition(n, m, x+1, y-1, occupation)
      && checkPosition(n, m, x, y-1, occupation)) {
        return true
    } else if (checkPosition(n, m, x-1, y, occupation)
      && checkPosition(n, m, x-1, y+1, occupation)
      && checkPosition(n, m, x, y+1, occupation)) {
      return true
    } else if (checkPosition(n, m, x-1, y, occupation)
      && checkPosition(n, m, x-1, y-1, occupation)
      && checkPosition(n, m, x, y-1, occupation)) {
      return true
    }
    false
  }

  def solve() = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val Array(n, m, k): Array[Int] = reader.readLine().split(" ").map(_.toInt)

    val occupation = Array.ofDim[Boolean](n, m)
    var found = false
    var step = 0
    for (i <- 0 until k) {
      val Array(x, y) = reader.readLine().split(" ").map(_.toInt)
      occupation(x-1)(y-1) = true
      if (!found && checkOccupation(n, m, x-1, y-1, occupation)) {
        found = true
        step = i + 1
      }
    }
    println(step)
  }

  solve()

  class Point(val x: Int, val y: Int) { }

}

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

object A {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val k = nextInt
    val arr = new Array[Array[Boolean]](n + 2)
    for (i <- 0 until n + 2) {
      arr(i) = new Array[Boolean](m + 2)
    }
    var ans = -1
    for (l <- 0 until k) {
      val x = nextInt
      val y = nextInt
      arr(x)(y) = true
      if(
        (ans == -1 && arr(x + 1)(y) && arr(x)(y + 1) && arr(x + 1)(y + 1)) ||
        (ans == -1 && arr(x - 1)(y) && arr(x)(y - 1) && arr(x - 1)(y - 1)) ||
        (ans == -1 && arr(x - 1)(y) && arr(x)(y + 1) && arr(x - 1)(y + 1)) ||
        (ans == -1 && arr(x + 1)(y) && arr(x)(y - 1) && arr(x + 1)(y - 1)))
      {
        ans = l
      }

    }

    if (ans == -1) {
      out.println(0)
    } else {
      out.println(ans + 1)
    }
    return 1
  }

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

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

object A {

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

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

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

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

  def solve: Int = {
    val n = nextInt
    val m = nextInt
    val k = nextInt
    val arr = new Array[Array[Boolean]](n + 2)
    for (i <- 0 until n + 2) {
      arr(i) = new Array[Boolean](m + 2)
    }
    var ans = -1
    for (l <- 0 until k) {
      val x = nextInt
      val y = nextInt
      arr(x)(y) = true
      if (ans == -1 && arr(x)(y) && arr(x + 1)(y) && arr(x)(y + 1) && arr(x + 1)(y + 1)) {
        ans = l
      }

    }

    if (ans == -1) {
      out.println(0)
    } else {
      out.println(ans + 1)
    }
    return 1
  }

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


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[Int]]): 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 N = ni()
    val ans = Array.ofDim[Int](N, N)
    REP(N / 4) { r =>
      REP(N / 4) { c =>
        REP(4) { i =>
          REP(4) { j =>
            ans(r * 4 + i)(c * 4 + j) = r * N * 4 + c * 16 + i * 4 + j
          }
        }
      }
    }

    debugDim(ans)

    REP(N) { i =>
      out.println(ans(i).mkString(" "))
    }

    DEBUG {
      val row = map(N)(i => ans(i).reduce(_^_))
      val col = Array.ofDim[Int](N)
      REP(N * N) { i =>
        col(i%N) ^= ans(i/N)(i%N)
      }
      debug(row)
      debug(col)
    }
  }
}

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(n) = readInts(1)

  val as = Array.ofDim[Int](n, n)

  var a = 0
  var r0 = 0
  while (r0 < n) {
    var c0 = 0
    while (c0 < n) {
      var r = 0
      while (r < 4) {
        var c = 0
        while (c < 4) {
          as(r0 + r)(c0 + c) = a
          a += 1
          c += 1
        }
        r += 1
      }
      c0 += 4
    }
    r0 += 4
  }

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

  as.foreach(a => println(a.mkString(" ")))

  Console.flush
}


import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt()
    for(i <- 0 until t) {
      val n = readInt()
      val sticks: Array[Int] = readLine.split(" ").map(_.toInt)
      val sortedSticks = sticks.sorted
      var ans: Long = 1e9.toLong
      for(j <- 2 until n) {
        val a = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j) - sortedSticks(j-2)
        val b = sortedSticks(j) - sortedSticks(j-2) + sortedSticks(j-1) -sortedSticks(j-2)
        val c = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j-1) -sortedSticks(j-2)
        ans = List(ans,a,b,c).min
      }

      println(ans)
    }
  }
}

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 10:08
 * @note
 * 1734A. Select Three Sticks | 难度：800
 */
object Solution1734A {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (_ <- 0 until t) {
      val _ = StdIn.readInt()
      val arr = StdIn.readLine().split(" ").map(_.toInt).sorted
      var minimum = Int.MaxValue
      for (j <- 0 until arr.length - 2) {
        minimum = minimum min (arr(j + 2) + arr(j + 1) - 2 * arr(j)) min
          (arr(j + 2) * 2 - arr(j + 1) - arr(j)) min (arr(j + 2) - arr(j))
      }
      println(minimum)
    }
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    val t = readInt()
    for(i <- 0 until t) {
      val n = readInt()
      val sticks: Array[Int] = readLine.split(" ").map(_.toInt)
      val sortedSticks = sticks.sorted
      var ans: Long = 1e9.toLong
      for(j <- 2 until n) {
        val c = sortedSticks(j) - sortedSticks(j-1) + sortedSticks(j-1) -sortedSticks(j-2)
        ans = Math.min(ans,c)
      }

      println(ans)
    }
  }
}

import scala.io.StdIn

/**
 * @author zhuxi
 * @since 2022/9/28 10:08
 * @note
 * 1734A. Select Three Sticks | 难度：800
 */
object Solution1734A {
  def main(args: Array[String]): Unit = {
    val t = StdIn.readInt()
    for (i <- 0 until t) {
      val n = StdIn.readInt()
      val arr = StdIn.readLine().split(" ").map(_.toInt).sorted
      var min = Int.MaxValue
      for (j <- 0 until arr.length - 2) {
        min = min min (arr(j+2) + arr(j+1) - 2 * arr(j))
      }
      println(min)
    }
  }
}


import scala.annotation.tailrec
import scala.collection.breakOut

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
object Main {
  // Document: http://www.scala-lang.org/api/current/#package
  // -----------------------------------------------------------------------------
  class Shelf(val books: Vector[Boolean],val inverted: Boolean, val count: Int) {
    def invert() : Shelf = new Shelf(books, !inverted, books.size - count)
    def place(j: Int) : Shelf = {
      val p = if(!inverted) true else false
      val i = if(books(j) != p) 1 else 0
      new Shelf(books.updated(j, p), inverted, count + i)
    }
    def remove(j: Int) : Shelf = {
      val p = if(!inverted) false else true
      val i = if(books(j) != p) -1 else 0
      new Shelf(books.updated(j, p), inverted, count + i)
    }
  }

  class BookCase(val shelves: Vector[Shelf], val count: Int) {
    def place(i: Int, j: Int) : BookCase = {
      val oldone = shelves(i)
      val newone = oldone.place(j)
      new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)
    }
    def remove(i: Int, j: Int) : BookCase = {
      val oldone = shelves(i)
      val newone = oldone.remove(j)
      new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)
    }
    def invert(i: Int) : BookCase = {
      val oldone = shelves(i)
      val newone = oldone.invert
      new BookCase(shelves.updated(i, newone), count - oldone.count + newone.count)
    }
  }

  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    def main() : Unit = {
      val n, m, q = nextInt()
      val logs : Array[BookCase] = Array.fill(q+1)(null)
      logs(0) = new BookCase(Vector.fill(n)(new Shelf(Vector.fill(m)(false), false, 0)), 0)
      for(qu <- 1 to q) {
        val t = nextInt()
        t match {
          case 1 => { // place
            val i, j = nextInt()-1
            logs(qu) = logs(qu-1).place(i, j)
          }
          case 2 => { // remove
            val i, j = nextInt()-1
            logs(qu) = logs(qu-1).remove(i, j)
          }
          case 3 => { // invert
            val i = nextInt()-1
            logs(qu) = logs(qu-1).invert(i)
          }
          case 4 => { // return
            val k = nextInt()
            logs(qu) = logs(k)
          }
          case _ => {
          }
        }
        println(logs(qu).count)
      }
    }
  }

  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

    def readIntVector()    : Vector[Int]    = parseLineToVector(() => nextInt)
    def readLongVector()   : Vector[Long]   = parseLineToVector(() => nextLong)
    def readStringVector() : Vector[String] = parseLineToVector(() => nextString)
    def nextInt()          : Int            = nextLong().toInt
    def nextBigInt()       : BigInt         = BigInt(nextString())
    def nextBigDecimal(  ) : BigDecimal     = BigDecimal(nextString())
    def nextDouble()       : Double         = nextString().toDouble
    def nextLong() : Long = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading long failed")
      val sgn = if(peek == '-') -1l else 1
      if(sgn == -1l) ignore(read())
      if(peek < '0' || '9' < peek)
        throw new NumberFormatException(s"readLong found only '-' or no number")
      @tailrec
      def readLong(next: Int, cur: Long) : Long =
        if('0' <= next && next <= '9'){
          ignore(read()) // is equal to next
          readLong(peek, cur*10 + next-'0')
        }
        else if(isEnd(next) || isSpaceOrControl(next))
          sgn*cur
        else
          throw new NumberFormatException(s"readLong found strange byte $next")
      val res = readLong(peek,0)
      skipTrailingSpaces()
      res
    }
    def nextString() : String = {
      if(!goNextValuable())
        throw new NoSuchElementException("Reading String failed")
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isSpaceOrControl(next)){
          builder.toString
        }else{
          builder.append(read().toChar) // here we skip.
            appendCode(peek)
        }
      }
      val res = appendCode(peek)
      skipTrailingSpaces()
      res
    }
    // TODO: refactoring to marge nextString
    def readLine() : String = {
      if(isEnd(peek))
        throw new NoSuchElementException("Reading Line failed")
      skipNewline()
      val builder = new StringBuilder
      @tailrec
      def appendCode(next: Int) : String = {
        if(isEnd(next) || isNewLine(next)){
          builder.toString
        }else{
          builder.append(next.toChar)
          appendCode(read())
        }
      }
      appendCode(read())
    }
    // helpers
    private def ignore[T](x: => T) : Unit = { x; () }
    private[this] var peeked: Option[Int] = None
    private[this] var is_first = true
    protected def read() = {
      val res = peeked match {
        case None    => in.read()
        case Some(a) => { peeked = None; a }
      }
      is_first = false
      res
    }
    private def peek() =
      peeked match {
        case None    => {
          val res = in.read()
          peeked  = Some(res)
          res
        }
        case Some(a) => a
      }
    private def isEnd(c: Int)     = c == -1
    private def isCR(c: Int)      = c == 13
    private def isLF(c: Int)      = c == 10
    private def isNewLine(c: Int) = isLF(c) || isCR(c)
    private def isThereReadable() = !isEnd(peek)
    private def isSpaceOrControl(c: Int) = (0 <= c && c <= 32) || c == 127
    @tailrec
    final private def goNextNotSpaceNorControl() : Unit =
      if(isSpaceOrControl(peek)){
        ignore(read())
        goNextNotSpaceNorControl()
      }
    final private def skipTrailingSpaces() : Unit = {
      @tailrec
      def skipTrailingSpacesAux() : Unit = {
        if(!isNewLine(peek) && isSpaceOrControl(peek)){
          ignore(read())
          skipTrailingSpacesAux()
        }
      }
      skipTrailingSpacesAux()
    }
    final private def skipNewline() : Unit =
      if(!is_first){
        if(isCR(peek))
          ignore(read())
        if(isLF(peek))
          ignore(read())
      }
    private def goNextValuable() : Boolean = {
      goNextNotSpaceNorControl()
      isThereReadable()
    }

    private def parseLineToVector[X](parser: () => X) : Vector[X] = {
      import scala.collection.immutable.VectorBuilder
      val vb = new VectorBuilder[X]()
      skipNewline()
      @tailrec
      def parseLineToVectorAux() : Vector[X] =
        if(isNewLine(peek) || isEnd(peek)) {
          vb.result
        }else{
          vb += parser()
          parseLineToVectorAux()
        }
      parseLineToVectorAux()
    }
  }

}

object Solution {

  case class State(flip: Vector[Boolean], shelves: Vector[Vector[Boolean]], cnt: Vector[Int], total: Int) {
    def existBook(i: Int, j: Int): Boolean = flip.apply(i) ^ shelves(i)(j)
    def place(i: Int, j: Int): State = {
      if (existBook(i, j)) this
      else
        State(flip, shelves.updated(i, shelves(i).updated(j, !flip(i))), cnt.updated(i, cnt(i) + 1), total + 1)
    }
    def remove(i: Int, j: Int): State = {
      if (!existBook(i, j)) this
      else
        State(flip, shelves.updated(i, shelves(i).updated(j, flip(i))), cnt.updated(i, cnt(i) - 1), total - 1)
    }
    def turn(i: Int): State =
      State(flip.updated(i, !flip(i)), shelves, cnt.updated(i, shelves(0).size - cnt(i)), total - 2*cnt(i) + shelves(0).size)
  }

  def main(args: Array[String]): Unit = {
    val tokens = scala.io.Source.stdin.getLines
      .flatMap(_ split ' ' filter (_.nonEmpty))

    def nextInt() = tokens.next().toInt

    val N, M, Q = nextInt()
    val states = Array.ofDim[State](Q + 1)
    states(0) = State(Vector.fill(N)(false), Vector.fill(N)(Vector.fill(M)(false)), Vector.fill(N)(0), 0)

    for (i <- 1 to Q) {
      states(i) = nextInt() match {
        case 1 => val s, p = nextInt() - 1; states(i - 1).place(s, p)
        case 2 => val s, p = nextInt() - 1; states(i - 1).remove(s, p)
        case 3 => states(i - 1).turn(nextInt() - 1)
        case 4 => states(nextInt())
      }
      println(states(i).total)
    }
  }
}

//package merofeev.contests.codeforces.rnd368

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
  * @author erofeev
  * @since 03.09.16
  */
//noinspection ReferenceMustBePrefixed
object DGraphPersistence {

  val MAX_COMMANDS = 100010

  val cCodes = new Array[Int](MAX_COMMANDS)
  //0 if it was step
  val cRows = new Array[Int](MAX_COMMANDS)
  //0 if not upplicable
  val cPositions = new Array[Int](MAX_COMMANDS)
  var rowSize = 0

  val book = Array.ofDim[Boolean](1000, 1000)
  val rowSums = new Array[Int](1000)
  val isRowFlipped = new Array[Boolean](1000)
  var currAnsw = 0
  val commandsTree = new Array[ArrayBuffer[Int]](MAX_COMMANDS)
  val answers = new Array[Int](MAX_COMMANDS)

  def solve(parentCmmand: Int): Unit = {
    answers(parentCmmand) = currAnsw
    for (command <- commandsTree(parentCmmand)) {
      val code: Int = cCodes(command)
      var updates = false
      val row: Int = cRows(command)
      for (rollback <- 0 to 1) {
        if (code == 3) {
          currAnsw -= rowSums(row) // rm current value
          isRowFlipped(row) = !isRowFlipped(row)
          rowSums(row) = rowSize - rowSums(row) // compute new val
          currAnsw += rowSums(row) //up new value
        } else if (code != 4) {
          val pos = cPositions(command)
          val isSet = book(row)(pos) ^ isRowFlipped(row)
          val upVal = if (code == 1) 1 else -1
          if (rollback == 0) {
            updates = isSet ^ code == 1
            if (updates) {
              book(row)(pos) = !book(row)(pos)
              rowSums(row) += upVal
              currAnsw += upVal
            }
          } else if (rollback == 1 && updates) {
            book(row)(pos) = !book(row)(pos)
            rowSums(row) -= upVal
            currAnsw -= upVal
          }
        }
        if (rollback == 0) {
          solve(command)
        }
      }
    }
  }

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

    val in = new Scanner(System.in)
    val rows = in.nextInt()
    this.rowSize = in.nextInt()
    val ops = in.nextInt()
    for (i <- 0 to ops) {
      commandsTree(i) = new ArrayBuffer()
    }

    //save every shelf as a bitset object (30b), 30b * 10000 = 3mb??
    //save every bookcase as a list of shelfs (100 * 8 + 20 = 850) * 100000 = 85mb
    var pos = 1
    while (in.hasNextInt) {
      cCodes(pos) = in.nextInt()
      cRows(pos) = in.nextInt() //step in case of 4 coe
      if (cCodes(pos) == 4) {
        commandsTree(cRows(pos)) += pos
      } else {
        cRows(pos) -= 1 //alignment
        commandsTree(pos - 1) += pos //children of previous
      }
      if (cCodes(pos) == 1 || cCodes(pos) == 2) {
        cPositions(pos) = in.nextInt() - 1 //alignment
      }
      pos += 1
    }
    solve(0)
    for (comm <- 1 to ops) {
      println(answers(comm))
    }
  }

}

object Solution {

case class State(flip: Vector[Boolean], shelves: Vector[Vector[Boolean]], cnt: Vector[Int], total: Int) {
  def existBook(i: Int, j: Int): Boolean = flip.apply(i) ^ shelves(i)(j)
  def place(i: Int, j: Int): State = {
    if (existBook(i, j)) this
    else
      State(flip, shelves.updated(i, shelves(i).updated(j, !flip.apply(i))), cnt.updated(i, cnt(i) + 1), total + 1)
  }
  def remove(i: Int, j: Int): State = {
    if (!existBook(i, j)) this
    else
      State(flip, shelves.updated(i, shelves(i).updated(j, flip.apply(i))), cnt.updated(i, cnt(i) - 1), total - 1)
  }
  def flip(i: Int): State =
    State(flip.updated(i, !flip.apply(i)), shelves, cnt.updated(i, shelves(0).size - cnt(i)), total - cnt(i) + shelves(0).size - cnt(i))
}

  def main(args: Array[String]): Unit = {
    val br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    var st: java.util.StringTokenizer = null
    val writer =  new java.io.PrintWriter(System.out)

    def nextInt(): Int = {
      while (st == null || !st.hasMoreElements())
          st = new java.util.StringTokenizer(br.readLine())
      return st.nextToken().toInt
    }

    val N, M, Q = nextInt()
    val states = Array.ofDim[State](Q + 1)
    states(0) = State(
      Vector.fill(N)(false),
      Vector.fill(N)(Vector.fill(M)(false)),
      Vector.fill(N)(0),
      0
    )

    for (i <- 1 to Q) {
      states(i) = nextInt() match {
        case 1 => val s, p = nextInt() - 1; states(i - 1).place(s, p)
        case 2 => val s, p = nextInt() - 1; states(i - 1).remove(s, p)
        case 3 => states(i - 1).flip(nextInt() - 1)
        case 4 => states(nextInt())
      }
      writer.println(states(i).total)
    }

    writer.close()
  }
}

//package merofeev.contests.codeforces.rnd368

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
  * @author erofeev
  * @since 03.09.16
  */
//noinspection ReferenceMustBePrefixed
object DGraphPersistence {

  val MAX_COMMANDS = 100000

  val cCodes = new Array[Int](MAX_COMMANDS)
  //0 if it was step
  val cRows = new Array[Int](MAX_COMMANDS)
  //0 if not upplicable
  val cPositions = new Array[Int](MAX_COMMANDS)
  var rowSize = 0

  val book = Array.ofDim[Boolean](1000, 1000)
  val rowSums = new Array[Int](1000)
  val isRowFlipped = new Array[Boolean](1000)
  var currAnsw = 0
  val commandsTree = new Array[ArrayBuffer[Int]](MAX_COMMANDS)
  val answers = new Array[Int](MAX_COMMANDS)

  def solve(parentCmmand: Int): Unit = {
    answers(parentCmmand) = currAnsw
    for (command <- commandsTree(parentCmmand)) {
      val code: Int = cCodes(command)
      var updates = false
      val row: Int = cRows(command)
      for (rollback <- 0 to 1) {
        if (code == 3) {
          currAnsw -= rowSums(row) // rm current value
          isRowFlipped(row) = !isRowFlipped(row)
          rowSums(row) = rowSize - rowSums(row) // compute new val
          currAnsw += rowSums(row) //up new value
        } else {
          val pos = cPositions(command)
          val isSet = book(row)(pos) ^ isRowFlipped(row)
          val upVal = if (code == 1) 1 else -1
          if (rollback == 0) {
            updates = isSet ^ code == 1
            if (updates) {
              book(row)(pos) = !book(row)(pos)
              rowSums(row) += upVal
              currAnsw += upVal
            }
          } else if (rollback == 1 && updates) {
            book(row)(pos) = !book(row)(pos)
            rowSums(row) -= upVal
            currAnsw -= upVal
          }
        }
        if (rollback == 0) {
          solve(command)
        }
      }
    }
  }

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

    for (i <- commandsTree.indices) {
      commandsTree(i) = new ArrayBuffer()
    }

    val in = new Scanner(System.in)
    val rows = in.nextInt()
    this.rowSize = in.nextInt()
    val ops = in.nextInt()

    //save every shelf as a bitset object (30b), 30b * 10000 = 3mb??
    //save every bookcase as a list of shelfs (100 * 8 + 20 = 850) * 100000 = 85mb
    var pos = 1
    while (in.hasNextInt) {
      cCodes(pos) = in.nextInt()
      cRows(pos) = in.nextInt()
      if (cCodes(pos) == 4) {
        commandsTree(cRows(pos)) += pos
      } else {
        cRows(pos) -= 1 //alignment
        commandsTree(pos - 1) += pos
      }
      if (cCodes(pos) == 1 || cCodes(pos) == 2) {
        cPositions(pos) = in.nextInt() - 1 //alignment
      }
      pos += 1
    }
    solve(0)
    for (comm <- 1 to ops) {
      println(answers(comm))
    }
  }

}


object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val n = in.nextLong()
      val k = in.nextLong()
      if((n-k)%2 == 0){
        val x: Long = (n-k)/2
        if(2L*x>=(k*(k-1L))){
          out.println("YES")
        }else{
          out.println("NO")
        }

      }else{
        out.println("NO")
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object Main {

	def main(arr: Array[String]): Unit = {
		var n: Int = readLine().toInt
		while (n > 0) {
			var _pairs = readLine().split(" ")
			var num1 : Long = _pairs(0).toLong
			var num2 : Long = _pairs(1).toLong
			if (num1 % 2 == num2 % 2 && num1 >= num2 * num2){
			    println("YES")
			} else {
			    println("NO")
			}
			n -= 1
		}

	}

}

object Main {

	def main(arr: Array[String]): Unit = {
		var n: Int = readLine().toInt
		while (n > 0) {
			var _pairs = readLine().split(" ")
			var num1 : Int = _pairs(0).toInt
			var num2 : Int = _pairs(1).toInt
			if (num1 % 2 == num2 % 2 && num1 >= num2 * num2){
			    println("YES")
			} else {
			    println("NO")
			}
			n -= 1
		}

	}

}

object Main {

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

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val t = in.nextInt()
    (1 to t).foreach{ _ =>
      val n = in.nextInt()
      val k = in.nextInt()
      if((n-k)%2 == 0){
        val x = (n-k)/2
        if(2*x>=(k*(k-1))){
          out.println("YES")
        }else{
          out.println("NO")
        }

      }else{
        out.println("NO")
      }
    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}


object Main extends App {
  final object InOut {
    val in =
      new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, true)
    var arr = Array[String]()
    var index: Int = 0
    def nextToken: String = {
      if (index >= arr.length) {
        index = 0
        arr = in.readLine.split(" ")
      }
      val ans = arr(index)
      index += 1
      ans
    }

    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 InOut._

  val n = nextInt
  //scala one line magic
  println(nextInts(n).sorted.foldLeft(1)({ (i, j) => if (i <= j) i+1 else i}) -1 )
}

object codeForces extends App
{
    val n=scala.io.StdIn.readInt()
    val line=scala.io.StdIn.readLine()
    val ara=scala.collection.mutable.ArrayBuffer.empty[Int]
    val input=line.split(" ").map(_.toInt)
    var i=0
    for(i<-0 until n)    {
        ara+=input(i)
    }
    val sorted=ara.sorted

    var ans=1
    for (x<-sorted)    {
        if(x>=ans)    ans+=1
    }

    println(ans-1)
}

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

  override def apply(io: IO): io.type = {
    val as = io.read[Seq[Int]].sorted
    val ans = as.foldLeft(1)({ case (i, j) => if (i <= j) i+1 else i})
    io.write(ans - 1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

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

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

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

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

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

object Main extends CodeForcesApp {

  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

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

    var i = 0
    var k = 1
    var ans = 0
    while (i < sortedContests.length) {
      if (sortedContests(i) >= k) {
        k += 1
        ans += 1
      }
      i += 1
    }
    io.writeLine(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 apply(io: IO): io.type

  def main(args: Array[String]): Unit = this (new IO(System.in, System.out)).close()
}

/** *********************************[Scala I/O] *********************************************/

import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

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

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

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)

  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)

  def readTillEndOfLine(): String = readTill("\n\r")

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

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

  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }

  def writeLine(): this.type = {
    printer.println()
    this
  }

  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }

  def writeLines(obj: Traversable[Any]): this.type = writeAll(obj, separator = "\n")

  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)

  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()

  def close() = {
    flush()
    in.close()
    printer.close()
  }
}

object IO {

  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]): Read[C[A]] = new Read(r => r.read[C, A](r.read[Int]))

    implicit val string: Read[String] = new Read(_.next())
    implicit val int: Read[Int] = string.map(_.toInt)
    implicit val long: Read[Long] = string.map(_.toLong)
    implicit val bigInt: Read[BigInt] = string.map(BigInt(_))
    implicit val double: Read[Double] = string.map(_.toDouble)
    implicit val bigDecimal: Read[BigDecimal] = string.map(BigDecimal(_))

    implicit def tuple2[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    implicit def tuple3[A: Read, B: Read, C: Read]: Read[(A, B, C)] = new Read(r => (r.read[A], r.read[B], r.read[C]))

    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]: Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))

    implicit val boolean: Read[Boolean] = string map { s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }

}

object Main extends App {
  final object InOut {
    val in =
      new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, true)
    var arr = Array[String]()
    var index: Int = 0
    def nextToken: String = {
      if (index >= arr.length) {
        index = 0
        arr = in.readLine.split(" ")
      }
      val ans = arr(index)
      index += 1
      ans
    }

    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 InOut._

  val n = nextInt
  val arr = nextInts(n).sorted

  var count = 0
  var k = 1
  for (i <- arr){
    if (i >= k){
      count += 1
      k += 1
    }
  }

  println(count)

}

import java.util.Scanner

import scala.io.StdIn

object Btask560 extends App {
  var line = new Scanner(StdIn.readLine())
  val n = line.nextInt()
  val x = StdIn.readLine().split(' ').map(_.toInt).sorted

  var day = 1

  for (i <- 0 until n) {
    if (x(i) >= day) {
      day += 1
    }
  }

  println(day-1)
}


object Solution {
  def main(args: Array[String]) {
    val r = new Reader
    val n, m = r.read[Long]
    val cl, ce = r.read[Int]
    val v = r.read[Long]
    val cls = r.read[Array[Long]](cl)
    val ces = r.read[Array[Long]](ce)
    val q = r.read[Int]
    val qs = r.read[List[(Long, Long, Long, Long)]](q)

    qs.foreach {
      case (x1, y1, x2, y2) => {
        val ds = if (cl > 0) {
          val i1 = 0.max(lb(cls(_) > y1, 0, cl-1)).min(cl-1)
          val i12 = (cl-1).min(i1+1)
          val i2 = 0.max(lb(cls(_) > y2, 0, cl-1)).min(cl-1)
          val i22 = (cl-1).min(i2+1)
          val s1 = (y1 - cls(i1)).abs + (y2 - cls(i1)).abs
          val s2 = (y1 - cls(i12)).abs + (y2 - cls(i12)).abs
          val s3 = (y1 - cls(i2)).abs + (y2 - cls(i2)).abs
          val s4 = (y1 - cls(i22)).abs + (y2 - cls(i22)).abs
          s1.min(s2.min(s3.min(s4))) + (x2 - x1).abs
        } else Long.MaxValue

        val de = if (ce > 0) {
          val j1 = 0.max(lb(ces(_) > y1, 0, ce-1)).min(ce-1)
          val j12 = (ce-1).min(j1+1)
          val j2 = 0.max(lb(ces(_) > y2, 0, ce-1)).min(ce-1)
          val j22 = (ce-1).min(j2+1)

          val e1 = (y1 - ces(j1)).abs + (y2 - ces(j1)).abs
          val e2 = (y1 - ces(j12)).abs + (y2 - ces(j12)).abs
          val e3 = (y1 - ces(j2)).abs + (y2 - ces(j2)).abs
          val e4 = (y1 - ces(j22)).abs + (y2 - ces(j22)).abs
          e1.min(e2.min(e3.min(e4))) + ((x2 - x1).abs - 1) / v + 1
        } else Long.MaxValue

        val dx = if (x1 == x2) (y2 - y1).abs else Long.MaxValue

        println(ds.min(de.min(dx)))
      }
    }
  }

  def lb(test: (Int => Boolean), from: Int, to: Int) = {
    import annotation.tailrec
    @tailrec
    def go(l: Int, r: Int): Int =
      if (l <= r) {
        val m = (r + l) / 2
        if (test(m)) go(l, m - 1) else go(m + 1, r)
      } else r

    go(from, to)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)

    implicit def tuple[A: Read]: Read[(A, A, A, A)] = new Read(r => (r.read[A], r.read[A], r.read[A], r.read[A]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}

import scala.collection.mutable

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, m, cl, ce, v) = readInts(5)
  val ls, es = new java.util.TreeSet[Integer]

  val _ls = readInts(cl)
  for (x <- _ls) ls.add(x)

  val _es = readInts(ce)
  for (x <- _es) es.add(x)

  val Array(q) = readInts(1)

  val res = new mutable.ArrayBuilder.ofInt

  for (_ <- 0 until q) {
    val Array(y1, x1, y2, x2) = readInts(4)
    var min = Int.MaxValue

    def elev(x: Int): Int = {
      (Math.abs(y1 - y2) + v - 1) / v + Math.abs(x1 - x) + Math.abs(x2 - x)
    }

    def stair(x: Int): Int = {
      Math.abs(y1 - y2) + Math.abs(x1 - x) + Math.abs(x2 - x)
    }

    if (y1 == y2) min = Math.abs(x1 - x2)
    else {

      val eLeft = es.floor(x1)
      val eRight = es.ceiling(x1)
      val lLeft = ls.floor(x1)
      val lRight = ls.ceiling(x1)

      if (eLeft != null && elev(eLeft) < min) min = elev(eLeft)
      if (eRight != null && elev(eRight) < min) min = elev(eRight)

      if (lLeft != null && stair(lLeft) < min) min = stair(lLeft)
      if (lRight != null && stair(lRight) < min) min = stair(lRight)
    }

    res += min
  }

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

  println(res.result.mkString("\n"))

  Console.flush
}

object Solution {
  def main(args: Array[String]) {
    val r = new Reader
    val n, m = r.read[Long]
    val cl, ce = r.read[Int]
    val v = r.read[Long]
    val cls = r.read[Array[Long]](cl)
    val ces = r.read[Array[Long]](ce)
    val q = r.read[Int]
    val qs = r.read[List[(Long, Long, Long, Long)]](q)

    qs.foreach {
      case (x1, y1, x2, y2) => {
        val ds = if (cl > 0) {
          val i1 = 0.max(lb(cls(_) > y1, 0, cl-1)).min(cl-1)
          val i12 = (cl-1).min(i1+1)
          val i2 = 0.max(lb(cls(_) > y2, 0, cl-1)).min(cl-1)
          val i22 = (cl-1).min(i2+1)
          val s1 = (y1 - cls(i1)).abs + (y2 - cls(i1)).abs
          val s2 = (y1 - cls(i12)).abs + (y2 - cls(i12)).abs
          val s3 = (y1 - cls(i2)).abs + (y2 - cls(i2)).abs
          val s4 = (y1 - cls(i22)).abs + (y2 - cls(i22)).abs
          s1.min(s2.min(s3.min(s4))) + (x2 - x1).abs
        } else Long.MaxValue

        val de = if (ce > 0) {
          val j1 = 0.max(lb(ces(_) > y1, 0, ce-1)).min(ce-1)
          val j12 = (ce-1).min(j1+1)
          val j2 = 0.max(lb(ces(_) > y2, 0, ce-1)).min(ce-1)
          val j22 = (ce-1).min(j2+1)

          val e1 = (y1 - ces(j1)).abs + (y2 - ces(j1)).abs
          val e2 = (y1 - ces(j12)).abs + (y2 - ces(j12)).abs
          val e3 = (y1 - ces(j2)).abs + (y2 - ces(j2)).abs
          val e4 = (y1 - ces(j22)).abs + (y2 - ces(j22)).abs
          e1.min(e2.min(e3.min(e4))) + ((x2 - x1).abs - 1) / v + 1
        } else Long.MaxValue

        println(ds.min(de))
      }
    }
  }

  def lb(test: (Int => Boolean), from: Int, to: Int) = {
    import annotation.tailrec
    @tailrec
    def go(l: Int, r: Int): Int =
      if (l <= r) {
        val m = (r + l) / 2
        if (test(m)) go(l, m - 1) else go(m + 1, r)
      } else r

    go(from, to)
  }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))
  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)

    implicit def tuple[A: Read]: Read[(A, A, A, A)] = new Read(r => (r.read[A], r.read[A], r.read[A], r.read[A]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine).takeWhile(_ != null).filter(_ != "").map(new StringTokenizer(_)).buffered
}


import java.util.Scanner

object Main {

	def main(args: Array[String]): Unit = {
		val scanner = new Scanner (System.in)
		val t = scanner.nextInt()
		for (i <- 1 to t) {
			val n = scanner.nextLong()
				println (solve (n))
		}
	}

	def solve(n: Long): Long = {
		4*n / gcd(4*n, n+1) + 1
	}

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

}

import scala.io.StdIn

object Square {

  def solve(n:Long):Long={
    //find min k: 4*n*k/(n+1)+1
    if ((n+1)%4==0){
      n+1
    }else if ((n+1)%2==0){
      2*n+1
    }else{
      4*n+1
    }
  }

  def solveSquare(in:List[Long]):List[Long]={
    in.map { x => solve(x)}
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val l = StdIn.readLine().split(" ").map { x => x.toLong }
    println(solveSquare(l.toList).mkString("\n"))
  }
}

object Main {
	def main(args: Array[String]) {
		def gcd(a: Long, b: Long):Long = {
			if (a == b) a
			else if (a == 0) b
			else if (b == 0) a
			else if (a > b) gcd(a%b, b)
			else gcd(b%a, a)
		}
		def lcm(a: Long, b: Long) = a/gcd(a,b)*b
		val calc = (size: Long) => {
			val count = size * 4
			lcm(count, size + 1) / (size + 1) + 1
		}
		val t = Integer.parseInt(readLine())
		val result = readLine().split(' ')
			.map(java.lang.Long.parseLong)
			.map(calc)
		result.foreach(println)
	}
}

import scala.io.StdIn

object Square {

  def solveSquare(in:List[Long]):List[Long]={
    in.map { x =>
      if (x==1) 1
      else if (x==2) 4
      else if (x==3) 4
      else (4*x)+1
    }
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val l = StdIn.readLine().split(" ").map { x => x.toLong }
    println(solveSquare(l.toList).mkString("\n"))
  }
}

import java.util.Scanner

object Main {

	def main(args: Array[String]): Unit = {
		val scanner = new Scanner (System.in)
		val t = scanner.nextInt()
		for (i <- 1 to t) {
			val n = scanner.nextInt()
				println (solve (n))
		}
	}

	def solve(n: Int): Int = {
		4*n / gcd(4*n, n+1) + 1
	}

	def gcd(x: Int, y: Int): Int = {
		if (y == 0) x else gcd (y, x % y)
	}

}

import scala.io.StdIn

object Square {

  def solveSquare(in:List[Int]):List[Int]={
    in.map { x =>
      if (x==1) 1
      else if (x==2) 4
      else if (x==3) 4
      else (4*x)+1
    }
  }

  def main(args:Array[String]){
    val n = StdIn.readLine().toInt
    val l = StdIn.readLine().split(" ").map { x => x.toInt }
    println(solveSquare(l.toList).mkString("\n"))
  }
}


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

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val t  = sn.reduce(_ ^ _)
    val m  = 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)

    val k = (if (t == 0) (1 to m) else (t to t))
      .view
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

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

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val t  = sn.reduce(_ ^ _)
    val m  = 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)

    val k = (if (t == 0) (1 to m) else (t to t))
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

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

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

    val k = (if (t == 0) (1 to 1 << (1 + (math.log10(sn.max) / math.log10(2)).toInt)) else (t to t))
      .view
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

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

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

    val ans = sn match {
      case Array(s1, s2, _*) =>
        (sn.reduce(_ ^ _) to 1024)
          .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }
          .getOrElse(-1)
      case _ => -1
    }

    println(ans)
  }
}

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

  (0 until t).foreach { _ =>
    val n  = scala.io.StdIn.readInt()
    val sn = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val s  = sn.reduce(_ ^ _)

    val k = (if (s == 0) (1 to 1024) else (s to s))
      .collectFirst { case k if sn.diff(sn.map(_ ^ k)).isEmpty => k }
      .getOrElse(-1)

    println(k)
  }
}

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

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

    val ans = sn match {
      case Array(s1, s2, _*) =>
        (sn.reduce(_ ^ _) to 1024)
          .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }
          .getOrElse(-1)
      case _ => -1
    }

    println(ans)
  }
}

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

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

    val ans = sn match {
      case Array(s1, s2, _*) =>
        List(sn.reduce(_ ^ _), s1, s2)
          .collectFirst { case k if k > 0 && sn.diff(sn.map(_ ^ k)).isEmpty => k }
          .getOrElse(-1)
      case _ => -1
    }

    println(ans)
  }
}

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

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

    val ans =
      if (sn.length == 1) -1
      else {
        val k = List(sn.reduce(_ ^ _), sn.head, sn.tail.head).filter(_ > 0).head

        if (sn.diff(sn.map(_ ^ k)).nonEmpty) -1
        else k
      }

    println(ans)
  }
}