You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells:   $$$(i - 1, j - 1)$$$;  $$$(i - 1, j)$$$;  $$$(i - 1, j + 1)$$$;  $$$(i, j - 1)$$$;  $$$(i, j + 1)$$$;  $$$(i + 1, j - 1)$$$;  $$$(i + 1, j)$$$;  $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n < 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).

For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.

//package codeforces.contests._1353

object BoardMoves {
  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val n = io.StdIn.readLong / 2

      println {
        (n * (n + 1) * (2 * n + 1) * 8) / 6
      }
    }
  }
}

import scala.io.StdIn.readLine

object C {

  def solution(n: Int): Long = {
    val k: Long = (n - 1) / 2
    k * (k + 1) * (2 * k + 1) / 6 * 8
  }

  def main(args: Array[String]): Unit = {
    for {_ <- 0 until readLine.toInt} {
      val n = readLine.toInt
      println(solution(n))
    }
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

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("problem.in"))),
						new PrintWriter(new File("problem.out"))
					)
				}
			new CF644(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 CF644 (fScanner: Main.FastScanner, out: java.io.PrintWriter) {

	import Main._
	import fScanner._

	// def solve(): Unit = {
	// 	val T = ni()
	// 	for(i <- 0 until T){
	// 	var ans : Int = 1000
	// 		val n = ni()
	// 		var list: List[Int] = List()
	// 		for(j <- 0 until n){
	// 			val cu:Int = ni()
	// 			for( x <- list)
	// 				ans = ans.min( ( cu - x ).max(x - cu) )
	// 			list = cu::	list
	// 		}
	// 		out.println(ans)
	// 	}
	// }

	def solve(): Unit ={
		val T = ni()
		for(i <- 0 until T){
			val n:Long = nl()
			val lm:Long = n-1
			var ans:Long = (n/2)*(n)*(n)
			for(j:Long <- 1.toLong until lm){
				if(j%2 == 1) ans = ans - (j*j)

			}
			println(ans)
		}
	}
}

object C extends App {

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

  (0 until t).foreach { _ =>
    val n = scala.io.StdIn.readInt()

    val ans = 1.to(n, 2).foldLeft(0L)((s, i) => s + i / 2L * (4L + 4L * (i - 2L)))

    println(ans)
  }
}

object ProblemC 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()

  val resultArr = new Array[BigInt](500000)
  resultArr(1) = 0
  for (i <- 3 until resultArr.length) {
    if (i % 2 == 1) {
      resultArr(i) = resultArr(i - 2) + (i * 2 + (i - 2) * 2).toLong * (i / 2)
    }
  }

  for (_ <- 1 to t) {
    println(resultArr(in.nextInt()))
  }

}

object ProblemC 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()

  val resultArr = new Array[Long](500000)
  resultArr(1) = 0
  for (i <- 3 until resultArr.length) {
    if (i % 2 == 1) {
      resultArr(i) = resultArr(i - 2) + (i * 2 + (i - 2) * 2) * (i / 2)
    }
  }

  for (_ <- 1 to t) {
    println(resultArr(in.nextInt()))
  }

}


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Each $$$a_i$$$ is one of the six following numbers: $$$4, 8, 15, 16, 23, 42$$$.Your task is to remove the minimum number of elements to make this array good.An array of length $$$k$$$ is called good if $$$k$$$ is divisible by $$$6$$$ and it is possible to split it into $$$\frac{k}{6}$$$ subsequences $$$4, 8, 15, 16, 23, 42$$$.Examples of good arrays:  $$$[4, 8, 15, 16, 23, 42]$$$ (the whole array is a required sequence);  $$$[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$$$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements);  $$$[]$$$ (the empty array is good). Examples of bad arrays:   $$$[4, 8, 15, 16, 42, 23]$$$ (the order of elements should be exactly $$$4, 8, 15, 16, 23, 42$$$);  $$$[4, 8, 15, 16, 23, 42, 4]$$$ (the length of the array is not divisible by $$$6$$$);  $$$[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$$$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is one of the following numbers: $$$4, 8, 15, 16, 23, 42$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum number of elements you have to remove to obtain a good array.

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

}

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

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

}


You are given a string $$$s$$$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $$$s$$$ such that it contains each of these three characters at least once.A contiguous substring of string $$$s$$$ is a string that can be obtained from $$$s$$$ by removing some (possibly zero) characters from the beginning of $$$s$$$ and some (possibly zero) characters from the end of $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 20000$$$) — the number of test cases. Each test case consists of one line containing the string $$$s$$$ ($$$1 \le |s| \le 200000$$$). It is guaranteed that each character of $$$s$$$ is either 1, 2, or 3. The sum of lengths of all strings in all test cases does not exceed $$$200000$$$.

For each test case, print one integer — the length of the shortest contiguous substring of $$$s$$$ containing all three types of characters at least once. If there is no such substring, print $$$0$$$ instead.

NoteConsider the example test:In the first test case, the substring 123 can be used.In the second test case, the substring 213 can be used.In the third test case, the substring 1223 can be used.In the fourth test case, the substring 3221 can be used.In the fifth test case, there is no character 3 in $$$s$$$.In the sixth test case, there is no character 1 in $$$s$$$.In the seventh test case, the substring 3112 can be used.

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)

  }

}


Bessie is out grazing on the farm, which consists of $$$n$$$ fields connected by $$$m$$$ bidirectional roads. She is currently at field $$$1$$$, and will return to her home at field $$$n$$$ at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has $$$k$$$ special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field $$$1$$$ to field $$$n$$$. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!

The first line contains integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le 2 \cdot 10^5$$$, $$$2 \le k \le n$$$)  — the number of fields on the farm, the number of roads, and the number of special fields.  The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$1 \le a_i \le n$$$)  — the special fields. All $$$a_i$$$ are distinct. The $$$i$$$-th of the following $$$m$$$ lines contains integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), representing a bidirectional road between fields $$$x_i$$$ and $$$y_i$$$.  It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.

Output one integer, the maximum possible length of the shortest path from field $$$1$$$ to $$$n$$$ after Farmer John installs one road optimally.

NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields $$$3$$$ and $$$5$$$, and the resulting shortest path from $$$1$$$ to $$$5$$$ is length $$$3$$$.     The graph for the second example is shown below. Farmer John must add a road between fields $$$2$$$ and $$$4$$$, and the resulting shortest path from $$$1$$$ to $$$5$$$ is length $$$3$$$.

object Main {
                    // extends App {
  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 n = in.nextInt()
    val m = in.nextInt()
    val k = in.nextInt()

    val edges = Array.fill(n+1)(ListBuffer.empty[Int])
    val visited = Array.fill(n+1)(false)
    def buildShortesPat(a: Array[Int],node: Int): Unit = {
      val q = mutable.Queue.empty[Int]
      q.enqueue(node)
      //a.indices.foreach(i => a(i) = Int.MaxValue)
      a(node) = 0
      visited(node) = true
      while(q.nonEmpty){
        val x = q.dequeue()
        edges(x).filter(u => !visited(u)).foreach{ u =>
          a(u) = a(x) +1
          visited(u) = true
          q.enqueue(u)
        }

      }

    }
    val specialFields = (1 to k).map(_ => in.nextInt())
    (1 to m).foreach{ _ =>
      val (x,y) = (in.nextInt(),in.nextInt())
      edges(x).append(y)
      edges(y).append(x)
    }

    val toEnd = Array.fill(n+1)(0)
    val fromBegin = Array.fill(n+1)(0)
    buildShortesPat(toEnd,n)
    visited.indices.foreach(i => visited(i) = false)
    buildShortesPat(fromBegin,1)

    val gs = specialFields.map(f => (f,fromBegin(f))).sortBy(_._2).toList.map(_._1)
    val minLength = fromBegin(n)
    val res = gs.zip(gs.tail).map{
      case (f,g) => {
        if(fromBegin(f) +1 + toEnd(g) <= minLength){
          fromBegin(f) +1 + toEnd(g)
        }else{
          minLength
        }
      }
    }.max

    out.println(res)
  }

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


"We've tried solitary confinement, waterboarding and listening to Just In Beaver, to no avail. We need something extreme.""Little Alena got an array as a birthday present..."The array b of length n is obtained from the array a of length n and two integers l and r (l ≤ r) using the following procedure:b1 = b2 = b3 = b4 = 0.For all 5 ≤ i ≤ n:   bi = 0 if ai, ai - 1, ai - 2, ai - 3, ai - 4 > r and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 1  bi = 1 if ai, ai - 1, ai - 2, ai - 3, ai - 4 < l and bi - 1 = bi - 2 = bi - 3 = bi - 4 = 0  bi = bi - 1 otherwise You are given arrays a and b' of the same length. Find two integers l and r (l ≤ r), such that applying the algorithm described above will yield an array b equal to b'.It's guaranteed that the answer exists.

The first line of input contains a single integer n (5 ≤ n ≤ 105) — the length of a and b'. The second line of input contains n space separated integers a1, ..., an ( - 109 ≤ ai ≤ 109) — the elements of a. The third line of input contains a string of n characters, consisting of 0 and 1 — the elements of b'. Note that they are not separated by spaces.

Output two integers l and r ( - 109 ≤ l ≤ r ≤ 109), conforming to the requirements described above. If there are multiple solutions, output any of them. It's guaranteed that the answer exists.

NoteIn the first test case any pair of l and r pair is valid, if 6 ≤ l ≤ r ≤ 109, in that case b5 = 1, because a1, ..., a5 < l.

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

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

}


It has finally been decided to build a roof over the football field in School 179. Its construction will require placing $$$n$$$ consecutive vertical pillars. Furthermore, the headmaster wants the heights of all the pillars to form a permutation $$$p$$$ of integers from $$$0$$$ to $$$n - 1$$$, where $$$p_i$$$ is the height of the $$$i$$$-th pillar from the left $$$(1 \le i \le n)$$$.As the chief, you know that the cost of construction of consecutive pillars is equal to the maximum value of the bitwise XOR of heights of all pairs of adjacent pillars. In other words, the cost of construction is equal to $$$\max\limits_{1 \le i \le n - 1}{p_i \oplus p_{i + 1}}$$$, where $$$\oplus$$$ denotes the bitwise XOR operation.Find any sequence of pillar heights $$$p$$$ of length $$$n$$$ with the smallest construction cost.In this problem, a permutation is an array consisting of $$$n$$$ distinct integers from $$$0$$$ to $$$n - 1$$$ in arbitrary order. For example, $$$[2,3,1,0,4]$$$ is a permutation, but $$$[1,0,1]$$$ is not a permutation ($$$1$$$ appears twice in the array) and $$$[1,0,3]$$$ is also not a permutation ($$$n=3$$$, but $$$3$$$ is in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The only line for each test case contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of pillars for the construction of the roof. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case print $$$n$$$ integers $$$p_1$$$, $$$p_2$$$, $$$\ldots$$$, $$$p_n$$$ — the sequence of pillar heights with the smallest construction cost. If there are multiple answers, print any of them.

NoteFor $$$n = 2$$$ there are $$$2$$$ sequences of pillar heights:   $$$[0, 1]$$$ — cost of construction is $$$0 \oplus 1 = 1$$$.  $$$[1, 0]$$$ — cost of construction is $$$1 \oplus 0 = 1$$$. For $$$n = 3$$$ there are $$$6$$$ sequences of pillar heights:   $$$[0, 1, 2]$$$ — cost of construction is $$$\max(0 \oplus 1, 1 \oplus 2) = \max(1, 3) = 3$$$.  $$$[0, 2, 1]$$$ — cost of construction is $$$\max(0 \oplus 2, 2 \oplus 1) = \max(2, 3) = 3$$$.  $$$[1, 0, 2]$$$ — cost of construction is $$$\max(1 \oplus 0, 0 \oplus 2) = \max(1, 2) = 2$$$.  $$$[1, 2, 0]$$$ — cost of construction is $$$\max(1 \oplus 2, 2 \oplus 0) = \max(3, 2) = 3$$$.  $$$[2, 0, 1]$$$ — cost of construction is $$$\max(2 \oplus 0, 0 \oplus 1) = \max(2, 1) = 2$$$.  $$$[2, 1, 0]$$$ — cost of construction is $$$\max(2 \oplus 1, 1 \oplus 0) = \max(3, 1) = 3$$$.

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 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 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 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()
}


Little penguin Polo has got a tree — a non-directed connected acyclic graph, containing n nodes and n - 1 edges. We will consider the tree nodes numbered by integers from 1 to n.Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of groups of four integers a, b, c and d such that:  1 ≤ a < b ≤ n;  1 ≤ c < d ≤ n;  there's no such node that lies on both the shortest path from node a to node b and from node c to node d. The shortest path betweem two nodes is the path that is shortest in the number of edges.Help Polo solve this problem.

The first line contains integer n (1 ≤ n ≤ 80000) — the number of tree nodes. Each of the following n - 1 lines contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) — the i-th edge of the tree. It is guaranteed that the given graph is a tree.

In a single line print a single integer — the answer to the problem. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator.

import collection.mutable.ArrayBuffer
import io.Source
import java.io.PrintWriter

object CF288D {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val edges = Array.fill(n)(ArrayBuffer.empty[Int])
    for (it <- 0 until n - 1) {
      val u, v = in().toInt - 1
//      val u = it
//      val v = it + 1
      edges(u) += v
      edges(v) += u
    }
    var ans = BigInt(0)
    def dfs(u: Int, p: Int): Long = {
      var size = 1L
      val d = Array.fill(2, 5)(0L)
      d(0)(0) = 1
      def regSubtree(s: Long) {
        for (i <- 1.to(0, -1); j <- 4.to(0, -1)) {
          if (i < 1) {
            d(i + 1)(j) += d(i)(j) * s * s
          }
          if (j < 4) {
            d(i)(j + 1) += d(i)(j) * s
          }
        }
      }
      var it = 0
      while (it < edges(u).size) {
        val v = edges(u)(it)
        if (v != p) {
          val sub = dfs(v, u)
          size += sub
          regSubtree(sub)
        }
        it += 1
      }
      if (p != -1) {
        regSubtree(n - size)
      }
//      out.println(u, d(1)(2), d(0)(4), d(1)(1), d(0)(3), d(1)(0), d(0)(2))
      ans += d(1)(2) * BigInt(2) + d(0)(4) * BigInt(12) + d(1)(1) * 2 + d(0)(3) * 12 + d(1)(0) + d(0)(2) * 4
      size
    }
    dfs(0, -1)
    assert(ans % 2 == 0)
    ans = BigInt(n.toLong * (n - 1) / 2) * (n.toLong * (n - 1) / 2) - ans / 2
    out.println(ans)
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "thread", 64000000).run()
  }

  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 collection.mutable.ArrayBuffer
import io.Source
import java.io.PrintWriter

object CF288D {

  def solve(in: In, out: PrintWriter) {
    val n = in().toInt
    val edges = Array.fill(n)(ArrayBuffer.empty[Int])
    for (it <- 0 until n - 1) {
      val u, v = in().toInt - 1
//      val u = it
//      val v = it + 1
      edges(u) += v
      edges(v) += u
    }
    var ans = BigInt(0)
    def dfs(u: Int, p: Int): Long = {
      var size = 1L
      val d = Array.fill(2, 5)(0L)
      d(0)(0) = 1
      def regSubtree(s: Long) {
        for (i <- 1.to(0, -1); j <- 4.to(0, -1)) {
          if (i < 1) {
            d(i + 1)(j) += d(i)(j) * s * s
          }
          if (j < 4) {
            d(i)(j + 1) += d(i)(j) * s
          }
        }
      }
      var it = 0
      while (it < edges(u).size) {
        val v = edges(u)(it)
        if (v != p) {
          val sub = dfs(v, u)
          size += sub
          regSubtree(sub)
        }
        it += 1
      }
      if (p != -1) {
        regSubtree(n - size)
      }
//      out.println(u, d(1)(2), d(0)(4), d(1)(1), d(0)(3), d(1)(0), d(0)(2))
      ans += d(1)(2) * 2 + d(0)(4) * 12 + d(1)(1) * 2 + d(0)(3) * 12 + d(1)(0) + d(0)(2) * 2 * 2
      size
    }
    dfs(0, -1)
    assert(ans % 2 == 0)
    ans = BigInt(n.toLong * (n - 1) / 2) * (n.toLong * (n - 1) / 2) - ans / 2
    out.println(ans)
  }

  def main(args: Array[String]) {
    new Thread(null, new Runnable {
      def run() {
        val in: In = new In(Source.fromInputStream(System.in))
        val out: PrintWriter = new PrintWriter(System.out)
        solve(in, out)
        out.close()
      }
    }, "thread", 64000000).run()
  }

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


Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p = p0, p1, ..., pn, Polo has defined its beauty — number .Expression  means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal — as "xor".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.

The single line contains a positive integer n (1 ≤ n ≤ 106).

In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m. If there are several suitable permutations, you are allowed to print any of them.

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


A sequence $$$a = [a_1, a_2, \ldots, a_l]$$$ of length $$$l$$$ has an ascent if there exists a pair of indices $$$(i, j)$$$ such that $$$1 \le i < j \le l$$$ and $$$a_i < a_j$$$. For example, the sequence $$$[0, 2, 0, 2, 0]$$$ has an ascent because of the pair $$$(1, 4)$$$, but the sequence $$$[4, 3, 3, 3, 1]$$$ doesn't have an ascent.Let's call a concatenation of sequences $$$p$$$ and $$$q$$$ the sequence that is obtained by writing down sequences $$$p$$$ and $$$q$$$ one right after another without changing the order. For example, the concatenation of the $$$[0, 2, 0, 2, 0]$$$ and $$$[4, 3, 3, 3, 1]$$$ is the sequence $$$[0, 2, 0, 2, 0, 4, 3, 3, 3, 1]$$$. The concatenation of sequences $$$p$$$ and $$$q$$$ is denoted as $$$p+q$$$.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has $$$n$$$ sequences $$$s_1, s_2, \ldots, s_n$$$ which may have different lengths. Gyeonggeun will consider all $$$n^2$$$ pairs of sequences $$$s_x$$$ and $$$s_y$$$ ($$$1 \le x, y \le n$$$), and will check if its concatenation $$$s_x + s_y$$$ has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs ($$$x, y$$$) of sequences $$$s_1, s_2, \ldots, s_n$$$ whose concatenation $$$s_x + s_y$$$ contains an ascent.

The first line contains the number $$$n$$$ ($$$1 \le n \le 100\,000$$$) denoting the number of sequences. The next $$$n$$$ lines contain the number $$$l_i$$$ ($$$1 \le l_i$$$) denoting the length of $$$s_i$$$, followed by $$$l_i$$$ integers $$$s_{i, 1}, s_{i, 2}, \ldots, s_{i, l_i}$$$ ($$$0 \le s_{i, j} \le 10^6$$$) denoting the sequence $$$s_i$$$.  It is guaranteed that the sum of all $$$l_i$$$ does not exceed $$$100\,000$$$.

Print a single integer, the number of pairs of sequences whose concatenation has an ascent.

NoteFor the first example, the following $$$9$$$ arrays have an ascent: $$$[1, 2], [1, 2], [1, 3], [1, 3], [1, 4], [1, 4], [2, 3], [2, 4], [3, 4]$$$. Arrays with the same contents are counted as their occurences.

import java.util

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

  val n = nextInt
  val xs = Array.fill(n) {
    val l = nextInt
    nextInts(l)
  }

  val mins = xs.map(_.min)
  val maxs = xs.map(_.max)

  def isAsc(as: Array[Int]): Boolean = {
    var min = as.head
    var res = false
    for (i <- 1 until as.length) {
      if (as(i) < min) min = as(i)
      else if (as(i) > min) res = true
    }
    res
  }

  val asc = xs.map(isAsc)
  val ascCount: Long = asc.count(identity)
  val maxNonAsc = ((for {
    i <- 0 until n
    if !asc(i)
  } yield maxs(i) * 10000000L + i) :+ 10000000L * 10000000L).toArray.sorted

  var res: Long = ascCount * n + (n - ascCount) * ascCount
//println(ascCount, res)
  @annotation.tailrec
  def binSearch(low: Int, hi: Int, x: Long): Int = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (maxNonAsc(mid) >= x) binSearch(low, mid - 1, x)
      else binSearch(mid + 1, hi, x)
    }
  }
//println(maxNonAsc.mkString(" "))
  for (i <- 0 until n) {
    if (!asc(i)) {
      val c = maxNonAsc.length - binSearch(0, maxNonAsc.length, (mins(i) + 1) * 10000000L) - 1
     // println(mins(i), c)
      res += c
    }
  }

  out.println(res)
  out.flush()

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

import java.util

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

  val n = nextInt
  val xs = Array.fill(n) {
    val l = nextInt
    nextInts(l)
  }

  val mins = xs.map(_.min)
  val maxs = xs.map(_.max)

  def isAsc(as: Array[Int]): Boolean = {
    var min = as.head
    var res = false
    for (i <- 1 until as.length) {
      if (as(i) < min) min = as(i)
      else if (as(i) > min) res = true
    }
    res
  }

  val asc = xs.map(isAsc)
  val ascCount = asc.count(identity)
  val maxNonAsc = ((for {
    i <- 0 until n
    if !asc(i)
  } yield maxs(i) * 10000000L + i) :+ 10000000L * 10000000L).toArray.sorted

  var res: Long = ascCount * n + (n - ascCount) * ascCount
//println(ascCount, res)
  @annotation.tailrec
  def binSearch(low: Int, hi: Int, x: Long): Int = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (maxNonAsc(mid) >= x) binSearch(low, mid - 1, x)
      else binSearch(mid + 1, hi, x)
    }
  }
//println(maxNonAsc.mkString(" "))
  for (i <- 0 until n) {
    if (!asc(i)) {
      val c = maxNonAsc.length - binSearch(0, maxNonAsc.length, (mins(i) + 1) * 10000000L) - 1
     // println(mins(i), c)
      res += c
    }
  }

  out.println(res)
  out.flush()

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

import java.util

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

  val n = nextInt
  val xs = Array.fill(n) {
    val l = nextInt
    nextInts(l)
  }

  val mins = xs.map(_.min)
  val maxs = xs.map(_.max)

  def isAsc(as: Array[Int]): Boolean = {
    var min = as.head
    var res = false
    for (i <- 1 until as.length) {
      if (as(i) < min) min = as(i)
      else if (as(i) > min) res = true
    }
    res
  }

  val asc = xs.map(isAsc)
  val ascCount = asc.count(identity)
  val maxNonAsc = ((for {
    i <- 0 until n
    if !asc(i)
  } yield maxs(i) * 10000000L + i) :+ 10000000L * 10000000L).toArray.sorted

  var res = ascCount * n + (n - ascCount) * ascCount
//println(ascCount, res)
  @annotation.tailrec
  def binSearch(low: Int, hi: Int, x: Long): Int = {
    if (hi < low) low
    else {
      val mid = (low + hi) / 2
      if (maxNonAsc(mid) >= x) binSearch(low, mid - 1, x)
      else binSearch(mid + 1, hi, x)
    }
  }
//println(maxNonAsc.mkString(" "))
  for (i <- 0 until n) {
    if (!asc(i)) {
      val c = maxNonAsc.length - binSearch(0, maxNonAsc.length, (mins(i) + 1) * 10000000L) - 1
     // println(mins(i), c)
      res += c
    }
  }

  out.println(res)
  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
  }
}


Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others. We define as bj the number of songs the group j is going to perform tomorrow. Polycarp wants to change the playlist in such a way that the minimum among the numbers b1, b2, ..., bm will be as large as possible.Find this maximum possible value of the minimum among the bj (1 ≤ j ≤ m), and the minimum number of changes in the playlist Polycarp needs to make to achieve it. One change in the playlist is a replacement of the performer of the i-th song with any other group.

The first line of the input contains two integers n and m (1 ≤ m ≤ n ≤ 2000). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109), where ai is the performer of the i-th song.

In the first line print two integers: the maximum possible value of the minimum among the bj (1 ≤ j ≤ m), where bj is the number of songs in the changed playlist performed by the j-th band, and the minimum number of changes in the playlist Polycarp needs to make. In the second line print the changed playlist. If there are multiple answers, print any of them.

NoteIn the first sample, after Polycarp's changes the first band performs two songs (b1 = 2), and the second band also performs two songs (b2 = 2). Thus, the minimum of these values equals to 2. It is impossible to achieve a higher minimum value by any changes in the playlist. In the second sample, after Polycarp's changes the first band performs two songs (b1 = 2), the second band performs three songs (b2 = 3), and the third band also performs two songs (b3 = 2). Thus, the best minimum value is 2.

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

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


Given an array $$$a$$$ of $$$n$$$ elements, print any value that appears at least three times or print -1 if there is no such value.

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2\cdot10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq n$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print any value that appears at least three times or print -1 if there is no such value.

NoteIn the first test case there is just a single element, so it can't occur at least three times and the answer is -1.In the second test case, all three elements of the array are equal to $$$2$$$, so $$$2$$$ occurs three times, and so the answer is $$$2$$$.For the third test case, $$$2$$$ occurs four times, so the answer is $$$2$$$.For the fourth test case, $$$4$$$ occurs three times, so the answer is $$$4$$$.For the fifth test case, $$$1$$$, $$$2$$$ and $$$3$$$ all occur at least three times, so they are all valid outputs.For the sixth test case, all elements are distinct, so none of them occurs at least three times and the answer is -1.

import scala.io.StdIn

/**
 *
 * Вам задан массив 𝑎 из 𝑛 элементов. Найдите любое число, которое встречается в этом массиве хотя бы три раза, или выведите -1, если таких чисел нет.
 *
 * Входные данные
 * В первой строке задано целое число 𝑡 (1≤𝑡≤104) — количество наборов входных данных.
 *
 * Первая строка набора входных данных содержит одно целое число 𝑛 (1≤𝑛≤2⋅105) — количество элементов в массиве.
 *
 * Вторая строка набора входных данных содержит 𝑛 целых чисел 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤𝑛) — элементы массива.
 *
 * Гарантируется, что сумма 𝑛 по всем наборам входных данных не превосходит 2⋅105.
 *
 * Выходные данные
 * Для каждого набора входных данных выведите любое целое число, которое встречается в массиве хотя бы три раза, или -1, если такого числа нет.
 */

object Task2 extends App {

  def getNextNum = StdIn.readLine().toInt

  def createResultMap = scala.collection.mutable.Map[Int, Int]().withDefaultValue(0)

  val inputSize = getNextNum

  for (_ <- 0 until inputSize) {
    getNextNum
    val array = StdIn.readLine().split(" ").map(_.toInt)
    val counterMap = createResultMap
    var gotResult = false
    var pos = 0

    do {
      counterMap(array(pos)) += 1
      if (counterMap(array(pos)) == 3) {
        println(array(pos))
        gotResult = true
      }
      pos += 1
    } while (!gotResult && pos < array.length)

    if (!gotResult) {
      println(-1)
    }

  }

}


You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that:  First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals . The operation x mod y means that we take the remainder of the division of number x by number y.  Then we write the contents of the array s to the array a. Element number i (1 ≤ i ≤ n) of the array s becomes the i-th element of the array a (ai = si). You task is to find array a after exactly k described operations are applied.

The first line contains two space-separated integers n and k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 109). The next line contains n space-separated integers a1, a2, ..., an — elements of the array a (0 ≤ ai ≤ 109).

Print n integers  — elements of the array a after the operations are applied to it. Print the elements in the order of increasing of their indexes in the array a. Separate the printed numbers by spaces.

// CodeForces 223C ToDo
object PartSums extends App {
  val MOD: Long = 1000000007L
  var kkf:Vector[Long] = Vector()

  def mull(a:Long, b:Long):Long = (a * b) % MOD
  def addl(a:Long, b:Long):Long = (a + b) % MOD
  def divl(a:Long, n:Int):Long = {
    val lst = for {
      i <- Range(0, n)
      if (a+i*MOD) % n == 0
    } yield ((a+i*MOD) / n)
    lst(0)
  }

  def koefs(n:Int, k:Int): Vector[Long] = {
    var vc = Vector[Long]()
    var cf:Long = 1
    for (i <- 0 until n) {
      vc = vc :+ cf
      cf = mull(cf, (k+i))
      cf = divl(cf, i+1)
    }
    vc
  }

  def sum(n:Int,  aa:Vector[Long]):Long = {
    var sm:Long = 0
    val kfs = kkf;  // koefs(n+1, k)
    for (i <- 0 to n) {
      sm = addl(sm, mull(aa(i), kfs(n-i)))
    }
    sm
  }

  def work() = {
	  var ss = (Console.readLine.split(" ")) map (_.toInt)
	  val n = ss(0)
	  val k = ss(1)
	  val aa = (Console.readLine.split(" ") map (_.toLong)) toList;
	  var vaa:Vector[Long] = Vector()
	  vaa = vaa ++ aa
	  kkf = koefs(n+5, k)
	  val smaa = for (i <- 0 until n)
	    yield sum(i, vaa)

	  println( smaa mkString " " )
  }
  def printSums(kk:Int) = {
      kkf = koefs(20, kk)
	  print("kk = " + kk + " sums: ")
	  for (i <- Range(0,5))
	    print(" " + sum(i, Vector(1,2,4,8, 10)))
	  println()
  }
  def testPrint() = {
	  println("MOD = " + MOD)
	  println("mul29 = " + mull(2,9))
	  println("add29 = " + addl(1000000000L,14))
	  println("divl = " + divl(1000000000L, 1000))
	  println(koefs(4,4))  // expect 1, 4
	  println(koefs(10,3))  // expect 1, 4
	  println(koefs(0,4))  // expect 1, 4
	  kkf = koefs(20,4)
	  printSums(0)
	  printSums(1)
	  printSums(100000)
  }
  // testPrint()
  work()
}


During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check.Each participant is identified by some unique positive integer k, and each sent solution A is characterized by two numbers: x — the number of different solutions that are sent before the first solution identical to A, and k — the number of the participant, who is the author of the solution. Consequently, all identical solutions have the same x.It is known that the data in the testing system are stored in the chronological order, that is, if the testing system has a solution with number x (x > 0) of the participant with number k, then the testing system has a solution with number x - 1 of the same participant stored somewhere before.During the competition the checking system crashed, but then the data of the submissions of all participants have been restored. Now the jury wants to verify that the recovered data is in chronological order. Help the jury to do so.

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the number of solutions. Each of the following n lines contains two integers separated by space x and k (0 ≤ x ≤ 105; 1 ≤ k ≤ 105) — the number of previous unique solutions and the identifier of the participant.

A single line of the output should contain «YES» if the data is in chronological order, and «NO» otherwise.

object Main {
  def main(args: Array[String]) {
    val n = readLine().toInt
    val versions = new Array[Int](100001)
    for (i <- 1 to 100000) {
      versions(i) = -1
    }
    for (i <- 1 to n) {
      val Array(x, k) = readLine().split(" ").map(_.toInt)
      if (!(x  <= versions(k) || x == versions(k) + 1)) {
          println("NO")
          return
      }
      if (x == versions(k) + 1) {
        versions(k) += 1
      }
    }
    println("YES")
  }
}


For an array $$$a$$$ of integers let's denote its maximal element as $$$\max(a)$$$, and minimal as $$$\min(a)$$$. We will call an array $$$a$$$ of $$$k$$$ integers interesting if $$$\max(a) - \min(a) \ge k$$$. For example, array $$$[1, 3, 4, 3]$$$ isn't interesting as $$$\max(a) - \min(a) = 4 - 1 = 3 < 4$$$ while array $$$[7, 3, 0, 4, 3]$$$ is as $$$\max(a) - \min(a) = 7 - 0 = 7 \ge 5$$$.You are given an array $$$a$$$ of $$$n$$$ integers. Find some interesting nonempty subarray of $$$a$$$, or tell that it doesn't exist.An array $$$b$$$ is a subarray of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.

The first line contains integer number $$$t$$$ ($$$1 \le t \le 10\,000$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n \le 2\cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0\le a_i \le 10^9$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output "NO" in a separate line if there is no interesting nonempty subarray in $$$a$$$.  Otherwise, output "YES" in a separate line. In the next line, output two integers $$$l$$$ and $$$r$$$ ($$$1\le l \le r \le n$$$) — bounds of the chosen subarray. If there are multiple answers, print any. You can print each letter in any case (upper or lower).

NoteIn the second test case of the example, one of the interesting subarrays is $$$a = [2, 0, 1, 9]$$$: $$$\max(a) - \min(a) = 9 - 0 = 9 \ge 4$$$.

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+1} ${ans+2}")
            }
        }
    }
}

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


Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2 × 2 square consisting of black pixels is formed. Pasha has made a plan of k moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers i and j, denoting respectively the row and the column of the pixel to be colored on the current move.Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2 × 2 square consisting of black pixels is formed.

The first line of the input contains three integers n, m, k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 105) — the number of rows, the number of columns and the number of moves that Pasha is going to perform.  The next k lines contain Pasha's moves in the order he makes them. Each line contains two integers i and j (1 ≤ i ≤ n, 1 ≤ j ≤ m), representing the row number and column number of the pixel that was painted during a move.

If Pasha loses, print the number of the move when the 2 × 2 square consisting of black pixels is formed. If Pasha doesn't lose, that is, no 2 × 2 square consisting of black pixels is formed during the given k moves, print 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
  }
}

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

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


Let us define a magic grid to be a square matrix of integers of size $$$n \times n$$$, satisfying the following conditions.   All integers from $$$0$$$ to $$$(n^2 - 1)$$$ inclusive appear in the matrix exactly once.  Bitwise XOR of all elements in a row or a column must be the same for each row and column. You are given an integer $$$n$$$ which is a multiple of $$$4$$$. Construct a magic grid of size $$$n \times n$$$.

The only line of input contains an integer $$$n$$$ ($$$4 \leq n \leq 1000$$$). It is guaranteed that $$$n$$$ is a multiple of $$$4$$$.

Print a magic grid, i.e. $$$n$$$ lines, the $$$i$$$-th of which contains $$$n$$$ space-separated integers, representing the $$$i$$$-th row of the grid. If there are multiple answers, print any. We can show that an answer always exists.

NoteIn the first example, XOR of each row and each column is $$$13$$$.In the second example, XOR of each row and each column is $$$60$$$.

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
}