PolandBall has such a convex polygon with n veritces that no three of its diagonals intersect at the same point. PolandBall decided to improve it and draw some red segments. He chose a number k such that gcd(n, k) = 1. Vertices of the polygon are numbered from 1 to n in a clockwise way. PolandBall repeats the following process n times, starting from the vertex 1: Assume you've ended last operation in vertex x (consider x = 1 if it is the first operation). Draw a new segment from vertex x to k-th next vertex in clockwise direction. This is a vertex x + k or x + k - n depending on which of these is a valid index of polygon's vertex.Your task is to calculate number of polygon's sections after each drawing. A section is a clear area inside the polygon bounded with drawn diagonals or the polygon's sides.

There are only two numbers in the input: n and k (5 ≤ n ≤ 106, 2 ≤ k ≤ n - 2, gcd(n, k) = 1).

You should print n values separated by spaces. The i-th value should represent number of polygon's sections after drawing first i lines.

NoteThe greatest common divisor (gcd) of two integers a and b is the largest positive integer that divides both a and b without a remainder.For the first sample testcase, you should output "2 3 5 8 11". Pictures below correspond to situations after drawing lines.

import java.io._

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.Source

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

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

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val nk = line.split(" ").map(_.toInt)
    val (n, k) = (nk(0), nk(1))
    if (k > n / 2)
      writeSolution(bw, n, n - k)  // always cycle around in increasing order, as the algorithm assumes this
    else
      writeSolution(bw, n, k)
    bw.newLine()
  }

  def writeSolution(bw: BufferedWriter, n: Int, k: Int): Unit = {

    @tailrec
    def writeVertices(currTotal: Long, currCrossings: Long, currX: Long): Unit = {
      val newX = (currX + k - 1) % n + 1
      val crossingAdjustment = if (newX > 1 && newX <= k) 1 else 0
      val newCrossings = currCrossings + crossingAdjustment
      val newTotal = currTotal + 2 * newCrossings + 1 - crossingAdjustment
      bw.write(newTotal.toString)
      bw.write(" ")
      if (newX != 1) {
        writeVertices(newTotal, newCrossings, newX)
      }
    }

    writeVertices(1L, 0L, 1L)
  }

}

import java.io._

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.Source

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

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

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val nk = line.split(" ").map(_.toInt)
    val (n, k) = (nk(0), nk(1))
    writeSolution(bw, n, k)
    bw.newLine()
  }

  def writeSolution(bw: BufferedWriter, n: Int, k: Int): Unit = {

    @tailrec
    def writeVertices(currTotal: Long, currCrossings: Long, currX: Long): Unit = {
      val newX = (currX + k - 1) % n + 1
      val crossingAdjustment = if (newX > 1 && newX <= k) 1 else 0
      val newCrossings = currCrossings + crossingAdjustment
      val newTotal = currTotal + 2 * newCrossings + 1 - crossingAdjustment
      bw.write(newTotal.toString)
      bw.write(" ")
      if (newX != 1) {
        writeVertices(newTotal, newCrossings, newX)
      }
    }

    writeVertices(1L, 0L, 1L)
  }

}

import java.io._

import scala.annotation.tailrec
import scala.collection.mutable
import scala.io.Source

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

  def processStdInOut(): Unit = {
    val src = Source.fromInputStream(System.in)
    processFromSource(src)
  }

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

  // Standard code above, custom code below

  def processLines(lines: Iterator[String], bw: BufferedWriter): Unit = {
    val line = lines.next()
    val nk = line.split(" ").map(_.toInt)
    val (n, k) = (nk(0), nk(1))
    writeSolution(bw, n, k)
    bw.newLine()
  }

  def writeSolution(bw: BufferedWriter, n: Int, k: Int): Unit = {

    @tailrec
    def writeVertices(currTotal: Long, currCrossings: Long, currX: Int): Unit = {
      val newX = (currX + k - 1) % n + 1
      val crossingAdjustment = if (newX > 1 && newX <= k) 1 else 0
      val newCrossings = currCrossings + crossingAdjustment
      val newTotal = currTotal + 2 * newCrossings + 1 - crossingAdjustment
      bw.write(newTotal.toString)
      bw.write(" ")
      if (newX != 1) {
        writeVertices(newTotal, currCrossings + crossingAdjustment, newX)
      }
    }

    writeVertices(1L, 0L, 1)
  }

}


There are n parliamentarians in Berland. They are numbered with integers from 1 to n. It happened that all parliamentarians with odd indices are Democrats and all parliamentarians with even indices are Republicans.New parliament assembly hall is a rectangle consisting of a × b chairs — a rows of b chairs each. Two chairs are considered neighbouring if they share as side. For example, chair number 5 in row number 2 is neighbouring to chairs number 4 and 6 in this row and chairs with number 5 in rows 1 and 3. Thus, chairs have four neighbours in general, except for the chairs on the border of the hallWe know that if two parliamentarians from one political party (that is two Democrats or two Republicans) seat nearby they spent all time discussing internal party issues.Write the program that given the number of parliamentarians and the sizes of the hall determine if there is a way to find a seat for any parliamentarian, such that no two members of the same party share neighbouring seats.

The first line of the input contains three integers n, a and b (1 ≤ n ≤ 10 000, 1 ≤ a, b ≤ 100) — the number of parliamentarians, the number of rows in the assembly hall and the number of seats in each row, respectively.

If there is no way to assigns seats to parliamentarians in a proper way print -1. Otherwise print the solution in a lines, each containing b integers. The j-th integer of the i-th line should be equal to the index of parliamentarian occupying this seat, or 0 if this seat should remain empty. If there are multiple possible solution, you may print any of them.

NoteIn the first sample there are many other possible solutions. For example, 3 20 1and 2 13 0The following assignment 3 21 0is incorrect, because parliamentarians 1 and 3 are both from Democrats party but will occupy neighbouring seats.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, a, b) = in.next().split(' ').map(_.toInt)
  if (n > a * b)
    println(-1)
  else {
    val ans = Array.ofDim[Int](a, b)
    var odd = 1
    var even = 2
    (0 until a).foreach{ i =>
      (0 until b).foreach { j =>
        if ((i + j) % 2 == 0 && odd <= n) {
          ans(i)(j) = odd
          odd += 2
        }
        else if (even <= n) {
          ans(i)(j) = even
          even += 2
        }
      }
    }
    println(ans.map(_.mkString(" ")).mkString("\n"))
  }

}

object A extends App {

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

  val Array(n, a, b) = readInts(3)

  var even = n / 2
  var odd = n - even

  val grid = Array.fill(a, b){ 0 }
  var oddI = 1
  var evenI = 2

  for {
    i <- 0 until a
    j <- 0 until b
  } {
    if ((i + j) % 2 == 0) {
      if (odd > 0) {
        odd -= 1
        grid(i)(j) = oddI
        oddI += 2
      }
    } else {
      if (even > 0) {
        even -= 1
        grid(i)(j) = evenI
        evenI += 2
      }
    }
  }

  if (even == 0 && odd == 0) {
    grid.foreach { row => println(row.mkString(" ")) }
  } else println(-1)
}

import java.io._
import java.util.StringTokenizer
import java.util.TreeMap
import scala.collection.mutable

object A {

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

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

  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 nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
    * Segment tree for any commutative function
    * @param values Array of Int
    * @param commutative function like min, max, sum
    * @param zero zero value - e.g. 0 for sum, Inf for min, max
    */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val n = nextInt
    val a = nextInt
    val b = nextInt
    if (a * b < n) {
      out.println(-1)
      return 0
    }
    var flag = true
    var fst = Stream.from(1, 2)
    var snd = Stream.from(2, 2)
    var cnt = n
    for (i <- 0 until a) {
      for (j <- 0 until b) {
        if (cnt > 0) {
          if (flag && fst.head <= n) {
            out.print(s"${fst.head} ")
            fst = fst.tail
            cnt -= 1
          } else if (!flag && snd.head <= n) {
            out.print(s"${snd.head} ")
            snd = snd.tail
            cnt -= 1
          } else {
            out.print("0 ")
          }
        } else {
          out.print("0 ")
        }
        if (j == b - 1 && b % 2 == 0) {
          flag = flag
        } else {
          flag = !flag
        }
      }
      out.println()
    }
    return 0
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _644A extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, a, b = io[Int]
    var (d, r) = (1, 2)

    val t = Array.tabulate(a, b) {
      case (i, j) if (i + j)%2 == 0 =>
        val x = d
        d += 2
        x
      case _ =>
        val x = r
        r += 2
        x
    }

    val ans = Array.tabulate(a, b) {
      case (i, j) => if (t(i)(j) > n) 0 else t(i)(j)
    }

    if (n > a*b) {
      io += -1
    } else {
      ans foreach {row =>
        io ++= row
        io.appendLine()
      }
    }
    io
  }
}
/****************************[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()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A](val t: Traversable[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates: Traversable[A] = {
      val elems = mutable.Set.empty[A]
      t collect {case i if !elems.add(i) => i}
    }
    def zipWith[B](f: A => B): Traversable[(A, B)] = t map {i => i -> f(i)}
    def mapTo[B](f: A => B): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class IndexedSeqExtensions[A](val s: IndexedSeq[A]) extends AnyVal {
    def withOffset(offset: Int): IndexedSeq[A] = Iterator.fill(offset)(null.asInstanceOf[A]) ++: s
  }
  implicit class PairsExtensions[A, B](val t: Traversable[(A, B)]) extends AnyVal {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap: Map[A, Traversable[B]] = t.groupBy(_._1).mapValues(_.map(_._2))
    def swap: Traversable[(B, A)] = t.map(_.swap)
  }
  implicit class MapExtensions[K, V](val m: Map[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.swap.toMultiMap.mapValues(_.toSet)
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def ^^(i: Int): A = if (i == 0) n.one else {
      val h = x ^^ (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x) //e.g. students.indexOf("Greg").nonNegative
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def  asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default
  }
  def memoize[I] = new {
    def apply[O](f: I => O): I => O = new mutable.HashMap[I, O]() {
      override def apply(key: I) = getOrElseUpdate(key, f(key))
    }
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat(n: Int)(f: => Unit): Unit = (1 to n).foreach(_ => f)
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.{Growable, CanBuild}

class IO(in: BufferedReader, out: BufferedWriter) extends PrintWriter(out, true) with Iterator[String] with Growable[Any] {
  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

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

  def apply[A](implicit parse: IO.Parser[A]): A = parse.apply(this)
  def apply[C[_], A: IO.Parser](n: Int)(implicit builder: CanBuild[A, C[A]]): C[A] = (builder() ++= Iterator.fill(n)(apply)).result()

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  override def +=(obj: Any) = {
    if (isNewLine) isNewLine = false else print(separator)
    print(obj)
    this
  }
  def ++=(t: TraversableOnce[_], ifEmpty: => Any): this.type = if (t.isEmpty) this += ifEmpty else this ++= t

  def appendLine(): this.type = {
    println()
    isNewLine = true
    this
  }

  override def clear() = flush()
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}

object IO {
  class Parser[A](val apply: IO => A) {
    def map[B](f: A => B): Parser[B] = new Parser(apply andThen f)
  }
  implicit def collection[C[_], A: Parser](implicit cbf: CanBuild[A, C[A]])  : Parser[C[A]]            = new Parser(r => r[C, A](r[Int]))
  implicit val string                                                        : Parser[String]          = new Parser(_.next())
  implicit val char                                                          : Parser[Char]            = string.map(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val boolean                                                       : Parser[Boolean]         = string.map(_.toBoolean)
  implicit val int                                                           : Parser[Int]             = string.map(_.toInt)
  implicit val long                                                          : Parser[Long]            = string.map(_.toLong)
  implicit val bigInt                                                        : Parser[BigInt]          = string.map(BigInt(_))
  implicit val double                                                        : Parser[Double]          = string.map(_.toDouble)
  implicit val bigDecimal                                                    : Parser[BigDecimal]      = string.map(BigDecimal(_))
  implicit def tuple2[A: Parser, B: Parser]                                  : Parser[(A, B)]          = new Parser(r => (r[A], r[B]))
  implicit def tuple3[A: Parser, B: Parser, C: Parser]                       : Parser[(A, B, C)]       = new Parser(r => (r[A], r[B], r[C]))
  implicit def tuple4[A: Parser, B: Parser, C: Parser, D: Parser]            : Parser[(A, B, C, D)]    = new Parser(r => (r[A], r[B], r[C], r[D]))
  implicit def tuple5[A: Parser, B: Parser, C: Parser, D: Parser, E: Parser] : Parser[(A, B, C, D, E)] = new Parser(r => (r[A], r[B], r[C], r[D], r[E]))
}


Reminder: the median of the array $$$[a_1, a_2, \dots, a_{2k+1}]$$$ of odd number of elements is defined as follows: let $$$[b_1, b_2, \dots, b_{2k+1}]$$$ be the elements of the array in the sorted order. Then median of this array is equal to $$$b_{k+1}$$$.There are $$$2n$$$ students, the $$$i$$$-th student has skill level $$$a_i$$$. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the $$$2$$$ classes such that each class has odd number of students (not divisible by $$$2$$$). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of students halved. The second line of each test case contains $$$2n$$$ integers $$$a_1, a_2, \dots, a_{2 n}$$$ ($$$1 \le a_i \le 10^9$$$) — skill levels of students. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.

NoteIn the first test, there is only one way to partition students — one in each class. The absolute difference of the skill levels will be $$$|1 - 1| = 0$$$.In the second test, one of the possible partitions is to make the first class of students with skill levels $$$[6, 4, 2]$$$, so that the skill level of the first class will be $$$4$$$, and second with $$$[5, 1, 3]$$$, so that the skill level of the second class will be $$$3$$$. Absolute difference will be $$$|4 - 3| = 1$$$.Note that you can't assign like $$$[2, 3]$$$, $$$[6, 5, 4, 1]$$$ or $$$[]$$$, $$$[6, 5, 4, 1, 2, 3]$$$ because classes have even number of students.$$$[2]$$$, $$$[1, 3, 4]$$$ is also not possible because students with skills $$$5$$$ and $$$6$$$ aren't assigned to a class.In the third test you can assign the students in the following way: $$$[3, 4, 13, 13, 20], [2, 5, 8, 16, 17]$$$ or $$$[3, 8, 17], [2, 4, 5, 13, 13, 16, 20]$$$. Both divisions give minimal possible absolute difference.

import java.io.PrintWriter
import util.control.Breaks._

object SolutionB {
    val reader = scala.io.StdIn
    def readInt = reader.readLine().toInt
    def readArrayInt = reader.readLine().split(" ").map(_.toInt)

    def multiTest(f: () => Unit): Unit = {
        var t = readInt
        while (t > 0) {
            f()
            t -= 1
        }
    }

    def solve(): Unit = {
        val n = readInt
        val a = readArrayInt.sorted
        println(math.abs(a(n) - a(n-1)))
    }

    def main(args: Array[String]) {
        multiTest(solve)
        //solve()
    }
}


Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are $$$n$$$ cards with $$$k$$$ features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with $$$k = 4$$$.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.

The first line of each test contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1500$$$, $$$1 \le k \le 30$$$) — number of cards and number of features. Each of the following $$$n$$$ lines contains a card description: a string consisting of $$$k$$$ letters "S", "E", "T". The $$$i$$$-th character of this string decribes the $$$i$$$-th feature of that card. All cards are distinct.

Output a single integer — the number of ways to choose three cards that form a set.

NoteIn the third example test, these two triples of cards are sets:  "SETT", "TEST", "EEET"  "TEST", "ESTE", "STES"

import scala.util.Random

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val Array(n, k) = stdin.next().split(' ').map(_.toInt)
//  val n = 1001
//  val k = 11
//  val r = new Random(10)
  val cards = stdin.take(n).map(_.toCharArray.toSeq).toArray
//  val cards = (0 to n).map(_ => rString(r, k).toCharArray.toSeq).toArray
  val set = cards.zipWithIndex.toMap
  val lSet = List[Char] ('S', 'E', 'T')

//  println("start measure")
//  val t0 = System.nanoTime()

  var res = 0
  for (i <- 0 until n - 2; j <- i + 1 until n - 1) {
    val str = (0 until k).map(z => nextL(cards(i)(z), cards(j)(z)))
    res = res + set.get(str).count(x => x > j)
  }
  println(res)
//  val t1 = System.nanoTime()
//  println("Elapsed time: " + (t1 - t0) / 1000000000d + "s")

  def nextL(ch1: Char, ch2: Char) = {
    if (ch1 == ch2) ch1
    else if (ch1 == 'S') {
      if (ch2 == 'E') 'T'
      else 'E'
    }
    else if (ch1 == 'E') {
      if (ch2 == 'S') 'T'
      else 'S'
    }
    else if (ch2 == 'S') 'E'
    else 'S'
  }

  def rString(r: Random, length: Int) = {
    (0 to n).map(_ => r.nextInt(3)).map{
      case 0 => 'S'
      case 1 => 'E'
      case 2 => 'T'
    }.mkString("")
  }

}

import scala.util.Random

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val Array(n, k) = stdin.next().split(' ').map(_.toInt)
//  val n = 1001
//  val k = 11
//  val r = new Random(10)
  val cards = stdin.take(n).map(_.toCharArray.toSeq).toArray
//  val cards = (0 to n).map(_ => rString(r, k).toCharArray.toSeq).toArray
  val set = cards.zipWithIndex.toMap
  val lSet = List[Char] ('S', 'E', 'T')

//  println("start measure")
//  val t0 = System.nanoTime()

  var res = 0
  for (i <- 0 until n - 2; j <- i + 1 until n - 1) {
    val str = (0 until k).map(z => nextL(cards(i)(z), cards(j)(z)))
    res = res + set.get(str).count(x => x > j)
  }
//  println(res)
//  val t1 = System.nanoTime()
//  println("Elapsed time: " + (t1 - t0) / 1000000000d + "s")

  def nextL(ch1: Char, ch2: Char) = {
    if (ch1 == ch2) ch1
    else if (ch1 == 'S') {
      if (ch2 == 'E') 'T'
      else 'E'
    }
    else if (ch1 == 'E') {
      if (ch2 == 'S') 'T'
      else 'S'
    }
    else if (ch2 == 'S') 'E'
    else 'S'
  }

  def rString(r: Random, length: Int) = {
    (0 to n).map(_ => r.nextInt(3)).map{
      case 0 => 'S'
      case 1 => 'E'
      case 2 => 'T'
    }.mkString("")
  }

}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val Array(n, k) = stdin.next().split(' ').map(_.toInt)
  val cards = stdin.take(n).toArray
  val set = cards.toSet
  val lSet = List[Char] ('S', 'E', 'T')
  if (n < 3) {
    println(0)
  }
  else {
    var r = 0
    for (i <- Range(0, n - 2); j <- Range(i + 1, n - 1))
        r = r + (if (set.contains(cards(i).zip(cards(j)).map{case(a, b) => if (a == b) a else lSet.find(p => p != a && p != b).get}.toString()) )1 else 0)
    println(r)
  }
}

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val Array(n, k) = stdin.next().split(' ').map(_.toInt)
  val cards = stdin.take(n).toArray
  val set = cards.toSet
  val lSet = List[Char] ('S', 'E', 'T')
  if (n < 3) {
    println(0)
  }
  else {
    var r = 0
    for (i <- Range(0, n - 2); j <- Range(i + 1, n - 1)) {
        r = r + (if (set.contains(cards(i).zip(cards(j)).map{case(a, b) => if (a == b) a else lSet.find(p => p != a && p != b).get}.mkString("")) )1 else 0)
    }
    println(r)
  }
}

import scala.collection.mutable

object Main extends App {
  val stdin = scala.io.Source.stdin.getLines()
  val Array(n, k) = stdin.next().split(' ').map(_.toInt)
  val cards = stdin.take(n).toArray
  if (n < 3) {
    println(0)
  }
  else {
    var r = 0
    for (i <- Range(0, n - n - 2); j <- Range(i + 1, n - 1); z <- Range(j + 1, n))
        r = r + (if (solution(i, j, z)) 1 else 0)
    println(r)
  }

  def solution(i: Int, j: Int, z: Int): Boolean = {
    cards(i).zip(cards(j)).zip(cards(z)).forall{case ((a, b), c) => (a == b && b == c) || (a != b && b != c && a != c) }
  }
}

// 5 11 2
// 2 3 4 5 7


ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.Chris tried filling in random numbers but it didn't work. ZS the Coder realizes that they need to fill in a positive integer such that the numbers in the grid form a magic square. This means that he has to fill in a positive integer so that the sum of the numbers in each row of the grid (), each column of the grid (), and the two long diagonals of the grid (the main diagonal —  and the secondary diagonal — ) are equal. Chris doesn't know what number to fill in. Can you help Chris find the correct positive integer to fill in or determine that it is impossible?

The first line of the input contains a single integer n (1 ≤ n ≤ 500) — the number of rows and columns of the magic grid. n lines follow, each of them contains n integers. The j-th number in the i-th of them denotes ai, j (1 ≤ ai, j ≤ 109 or ai, j = 0), the number in the i-th row and j-th column of the magic grid. If the corresponding cell is empty, ai, j will be equal to 0. Otherwise, ai, j is positive. It is guaranteed that there is exactly one pair of integers i, j (1 ≤ i, j ≤ n) such that ai, j = 0.

Output a single integer, the positive integer x (1 ≤ x ≤ 1018) that should be filled in the empty cell so that the whole grid becomes a magic square. If such positive integer x does not exist, output  - 1 instead. If there are multiple solutions, you may print any of them.

NoteIn the first sample case, we can fill in 9 into the empty cell to make the resulting grid a magic square. Indeed, The sum of numbers in each row is:4 + 9 + 2 = 3 + 5 + 7 = 8 + 1 + 6 = 15.The sum of numbers in each column is:4 + 3 + 8 = 9 + 5 + 1 = 2 + 7 + 6 = 15.The sum of numbers in the two diagonals is:4 + 5 + 6 = 2 + 5 + 8 = 15.In the third sample case, it is impossible to fill a number in the empty square such that the resulting grid is a magic square.

object B extends App {

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

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLongs(n) }

  val row0 = as.indexWhere(_.contains(0))
  val col0 = as(row0).indexOf(0)

  if (n == 1) println(1)
  else {
    val goal = as.map(_.sum).max
    val row0Sum = as(row0).sum
    val delta = goal - row0Sum
    as(row0)(col0) = delta
    val tas = as.transpose

    val rowSums = as.map(_.sum)
    val colSums = tas.map(_.sum)
    val diagIIsum = (0 until n).map(i => as(i)(i)).sum
    val diagIJsum = (0 until n).map(i => as(i)(n - i - 1)).sum

    if (delta > 0 && rowSums.forall(_ == goal) && colSums.forall(_ == goal) && diagIIsum == goal && diagIJsum == goal) println(delta)
    else println(-1)
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _711B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val n = read[Int]
    val grid = mutable.ArrayBuffer.fill(n, n)(read[Long])

    val z = for {
      i <- grid.indices
      j <- grid(i).indices
      if grid(i)(j) == 0
    } yield (i, j)
    val (x, y) = z.head

    val ans = grid.find(g => !g.contains(0)).map(g => g.sum - grid(x).sum) getOrElse 1L

    grid(x)(y) = ans

    val sums = map[Long] to 0

    var d1, d2 = 0L
    for(i <- until(n)) {
      d1 += grid(i)(i)
      d2 += grid(i)(n - i - 1)
      var r, c = 0L
      for(j <- until(n)) {
        r += grid(i)(j)
        c += grid(j)(i)
      }
      sums(r) += 1
      sums(c) += 1
    }

    sums(d1) += 1
    sums(d2) += 1

    write(if (sums.size == 1 && ans > 0) ans else -1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)

  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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    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 java.util.Scanner

object Main{
  def main (args: Array[String]){
    val sc = new Scanner(System.in)

    val n = sc.nextInt()
    val a = Array.ofDim[Long](n, n)

    var zerop = (-1, -1)  // (y, x)

    for(i <- 0 until n){
      for(j <- 0 until n){
        val tmp = sc.nextLong()
        a(i)(j) = tmp
        if(tmp == 0)
          zerop = (i, j)
      }
    }

    if(n == 1)
      println(1)
    else{
      var ans = -1L
      var flag = true

      // row
      var sum = -1L
      if(zerop._1 == 0)
        sum = a(1).sum
      else
        sum = a(0).sum

      for(i <- 0 until n){
        if(i == zerop._1){
          ans = sum - a(i).sum
          if(ans < 1)
            flag = false
        }
        else{
          if(a(i).sum != sum)
            flag = false
        }
      }

      // column
      sum = -1L

      def count(x: Int): Long = {
        var res = 0L
        for(k <- 0 until n)
          res += a(k)(x)
        res
      }

      /* process */
      if(zerop._2 == 0)
        sum = count(1)
      else
        sum = count(0)

      for(i <- 0 until n){
        if(i == zerop._2){
          if(sum != count(i) + ans)
            flag = false
        }
        else{
          if(count(i) != sum)
            flag = false
        }
      }

      // cross

      if(zerop._1 == zerop._2 && n % 2 == 1 && zerop._1 == n/2){ // including empty grid double
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR + ans != sum || crossL + ans != sum)
          flag = false
      }
      else if(zerop._1 == zerop._2){  // R
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR + ans != sum || crossL != sum)
          flag = false
      }
      else if(zerop._1 + zerop._2 == n - 1){ // L
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR != sum || crossL + ans != sum)
          flag = false
      }
      else{
        var crossR = 0L
        var crossL = 0L
        for(i <- 0 until n){
          crossR += a(i)(i)
          crossL += a(i)((n-1)-i)
        }
        if(crossR != sum || crossL != sum)
          flag = false
      }

      // output
      if(flag)
        println(ans)
      else
        println(-1)
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)
    println(-1)
  else {
    val candidate = sumsH.head - sumH
    val diagonal1 = lines.indices.map{ i =>
      val el = lines(i)(i)
      if (el == 0) candidate else el
    }.sum
    val diagonal2 = lines.indices.map { i =>
      val el = lines(i)(n - i - 1)
      if (el == 0) candidate else el
    }.sum
    if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)
      println(candidate)
    else
      println(-1)
  }
}

object B711 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    if(n == 1) {
      println("1")
    }
    else {
      val in = Array.fill(n)(readLongs(n))
      var x = -1
      var y = -1
      for(i <- 0 until n; j <- 0 until n if in(i)(j) == 0) {
        x = i
        y = j
      }
      val sum = if(x == 0) {
        in(1).sum
      } else {
        in(0).sum
      }
      if(sum - in(x).sum <= 0)
        println("-1")
      else {
        in(x)(y) = sum - in(x).sum
        if(isValid(in, sum)) {
          println(in(x)(y))
        } else {
          println("-1")
        }
      }
    }
  }

  def isValid(in: Array[Array[Long]], sum: Long): Boolean = {
    in.indices.forall(in(_).sum == sum) && {
      val cols = Array.fill(in.length)(0L)
      for(i <- in.indices; j <- in.indices)
        cols(j) += in(i)(j)
      cols.forall(_ == sum)
    } && {
      var sumd = 0L
      for(i <- in.indices; j <- in.indices if i == j)
        sumd += in(i)(j)
      sumd == sum
    } && {
      var sumd = 0L
      for(i <- in.indices; j <- in.indices if j == in.length-i-1)
        sumd += in(i)(j)
      sumd == sum
    }
  }

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

}

object B extends App {

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

  val Array(n) = readInts(1)
  val as = Array.fill(n){ readLongs(n) }

  val row0 = as.indexWhere(_.contains(0))
  val col0 = as(row0).indexOf(0)

  if (n == 1) println(1)
  else {
    val goal = as.map(_.sum).max
    val row0Sum = as(row0).sum
    val delta = goal - row0Sum
    as(row0)(col0) = delta
    val tas = as.transpose

    val rowSums = as.map(_.sum)
    val colSums = tas.map(_.sum)
    val diagIIsum = (0 until n).map(i => as(i)(i)).sum
    val diagIJsum = (0 until n).map(i => as(i)(n - i - 1)).sum

    if (rowSums.forall(_ == goal) && colSums.forall(_ == goal) && diagIIsum == goal && diagIJsum == goal) println(delta)
    else println(-1)
  }
}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._, collection.Searching._

object _711B extends CodeForcesApp {
  override def apply(io: IO) = {import io.{read, write, writeAll}
    val n = read[Int]
    val grid = mutable.ArrayBuffer.fill(n, n)(read[Long])

    val z = for {
      i <- grid.indices
      j <- grid(i).indices
      if grid(i)(j) == 0
    } yield (i, j)
    val (x, y) = z.head

    val ans = grid.find(g => !g.contains(0)).map(_.sum) match {
      case None => 1
      case Some(target) => target - grid(x).sum
    }

    grid(x)(y) = ans

    val sums = map[Long] to 0

    grid foreach {row => sums(row.sum) += 1}
    val g1 = Vector.tabulate(n, n){case (i, j) => grid(j)(i)}
    g1 foreach {row => sums(row.sum) += 1}

    val d1 = Vector.tabulate(n)(i => grid(i)(i))
    val d2 = Vector.tabulate(n)(i => grid(i)(n - i - 1))

    sums(d1.sum) += 1
    sums(d2.sum) += 1

    write(if (sums.size == 1) ans else -1)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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()
    when(tokenizers.nonEmpty)(tokenizers.head)
  }

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

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

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

  def write(obj: Any, more: Any*): this.type = {
    printer.print(obj)
    more foreach {i =>
      printer.print(' ')
      printer.print(i)
    }
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = "\n"): this.type = write(obj mkString separator)

  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: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)
    println(-1)
  else
    println(sumsH.head - sumH)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)
    println(-1)
  else
    println(sumsH.head - sumH)
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV || sumsH.head <= sumH)
    println(-1)
  else {
    val candidate = sumsH.head - sumH
    val diagonal1 = lines.indices.map{ i =>
      val el = lines(i)(i)
      if (el == 0) candidate else el
    }.sum
    val diagonal2 = lines.indices.map { i =>
      val el = lines(n - i - 1)(n - i - 1)
      if (el == 0) candidate else el
    }.sum
    if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)
      println(candidate)
    else
      println(-1)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (n == 1)
    println(1)
  else if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)
    println(-1)
  else {
    val candidate = sumsH.head - sumH
    val diagonal1 = lines.indices.map{ i =>
      val el = lines(i)(i)
      if (el == 0) candidate else el
    }.sum
    val diagonal2 = lines.indices.map { i =>
      val el = lines(n - i - 1)(n - i - 1)
      if (el == 0) candidate else el
    }.sum
    if (diagonal2 == diagonal1 && diagonal1 == sumsH.head)
      println(candidate)
    else
      println(-1)
  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val lines = in.take(n).map(_.split(' ').map(_.toLong)).toList
  val line = lines.find(_.contains(0)).get
  val sumH = line.sum
  val index = line.indexOf(0)
  val sumV = lines.map(_(index)).sum
  val sumsH = lines.filterNot(_.contains(0)).map(_.sum).distinct
  val sumsV = lines.indices.filterNot(_ == index).map(i => lines.map(_(i)).sum).distinct
  if (sumsV.length != 1 || sumsH.length != 1 || sumsH.head != sumsV.head || sumH != sumV)
    println(-1)
  else
    println(sumsH.head - sumH)
}


At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly $$$k$$$ flowers.The work material for the wreaths for all $$$n$$$ citizens of Shortriver is cut from the longest flowered liana that grew in the town that year. Liana is a sequence $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$, where $$$a_i$$$ is an integer that denotes the type of flower at the position $$$i$$$. This year the liana is very long ($$$m \ge n \cdot k$$$), and that means every citizen will get a wreath.Very soon the liana will be inserted into a special cutting machine in order to make work material for wreaths. The machine works in a simple manner: it cuts $$$k$$$ flowers from the beginning of the liana, then another $$$k$$$ flowers and so on. Each such piece of $$$k$$$ flowers is called a workpiece. The machine works until there are less than $$$k$$$ flowers on the liana.Diana has found a weaving schematic for the most beautiful wreath imaginable. In order to weave it, $$$k$$$ flowers must contain flowers of types $$$b_1$$$, $$$b_2$$$, ..., $$$b_s$$$, while other can be of any type. If a type appears in this sequence several times, there should be at least that many flowers of that type as the number of occurrences of this flower in the sequence. The order of the flowers in a workpiece does not matter.Diana has a chance to remove some flowers from the liana before it is inserted into the cutting machine. She can remove flowers from any part of the liana without breaking liana into pieces. If Diana removes too many flowers, it may happen so that some of the citizens do not get a wreath. Could some flowers be removed from the liana so that at least one workpiece would conform to the schematic and machine would still be able to create at least $$$n$$$ workpieces?

The first line contains four integers $$$m$$$, $$$k$$$, $$$n$$$ and $$$s$$$ ($$$1 \le n, k, m \le 5 \cdot 10^5$$$, $$$k \cdot n \le m$$$, $$$1 \le s \le k$$$): the number of flowers on the liana, the number of flowers in one wreath, the amount of citizens and the length of Diana's flower sequence respectively. The second line contains $$$m$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_m$$$ ($$$1 \le a_i \le 5 \cdot 10^5$$$)  — types of flowers on the liana. The third line contains $$$s$$$ integers $$$b_1$$$, $$$b_2$$$, ..., $$$b_s$$$ ($$$1 \le b_i \le 5 \cdot 10^5$$$)  — the sequence in Diana's schematic.

If it's impossible to remove some of the flowers so that there would be at least $$$n$$$ workpieces and at least one of them fullfills Diana's schematic requirements, output $$$-1$$$. Otherwise in the first line output one integer $$$d$$$  — the number of flowers to be removed by Diana. In the next line output $$$d$$$ different integers  — the positions of the flowers to be removed. If there are multiple answers, print any.

NoteIn the first example, if you don't remove any flowers, the machine would put out two workpieces with flower types $$$[1, 2, 3]$$$ and $$$[3, 2, 1]$$$. Those workpieces don't fit Diana's schematic. But if you remove flower on $$$4$$$-th place, the machine would output workpieces $$$[1, 2, 3]$$$ and $$$[2, 1, 2]$$$. The second workpiece fits Diana's schematic.In the second example there is no way to remove flowers so that every citizen gets a wreath and Diana gets a workpiece that fits here schematic.In the third example Diana is the only citizen of the town and that means she can, for example, just remove all flowers except the ones she needs.

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

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

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

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

  def solve(): Unit = {
    val M, K, N, S = ni()
    val A = na(M)
    val B = na(S)

    val cnt = Array.ofDim[Int](5e5.toInt + 1)
    val needs = Array.ofDim[Int](5e5.toInt + 1)
    REP(S) { i =>
      needs(B(i)) += 1
    }
    var matched = 0

    var r = -1
    REP(M) { l =>
      while(r + 1 < M && (matched < S || r - l + 1 < K)) {
        r += 1
        if (needs(A(r)) > 0) {
          cnt(A(r)) += 1
          if (cnt(A(r)) <= needs(A(r))) matched += 1
        }
      }

      debug(s"[$l,$r] matched:$matched")

      if (matched == S && r - l + 1 >= K) {
        val lim = M - K * N
        val minus_cur = (r - l + 1) - K
        val minus_l = l % K
        val minus = minus_cur + minus_l
        val cond1 = lim >= minus

        val cnt_l = l / K
        val cnt_r = (M - r - 1) / K
//        debug(s"cnt_r:$cnt_r")
        val cond2 = cnt_l + cnt_r + 1 >= N
        if (cond1 && cond2) {
          out.println(minus)
          // 左側の人たちはmod調節のためなのでだれを消してもいい   R
          REP(minus_l) { i =>
            out.print(i + 1)
          }

          Arrays.fill(cnt, 0)
          var deleted = 0
          TO(l, r) { i =>
            if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {
              cnt(A(i)) += 1
            } else if (deleted < minus_cur) {
              if (deleted > 0 || minus_l > 0) out.print(" ")
              out.print(i + 1)
              deleted += 1
            }
          }
          out.println()

          return
        }
      }

      if (needs(A(l)) > 0) {
        if (cnt(A(l)) <= needs(A(l))) matched -= 1
        cnt(A(l)) -= 1
      }
    }

    out.println(-1)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val M, K, N, S = ni()
    val A = na(M)
    val B = na(S)

    val cnt = Array.ofDim[Int](5e5.toInt + 1)
    val needs = Array.ofDim[Int](5e5.toInt + 1)
    REP(S) { i =>
      needs(B(i)) += 1
    }
    var matched = 0

    var r = -1
    REP(M) { l =>
      while(r + 1 < M && matched < S) {
        r += 1
        if (needs(A(r)) > 0) {
          cnt(A(r)) += 1
          if (cnt(A(r)) <= needs(A(r))) matched += 1
        }
      }

      if (matched == S) {
        val lim = M - K * N
        val minus_cur = (r - l + 1) - K
        val minus_l = l % K
        val minus = minus_cur + minus_l
        val cond1 = lim >= minus

        val cnt_l = l / K
        val cnt_r = (M - r - 1) / K
//        debug(s"cnt_r:$cnt_r")
        val cond2 = cnt_l + cnt_r + 1 >= N
        if (cond1 && cond2) {
          out.println(minus)
          // 左側の人たちはmod調節のためなのでだれを消してもいい   R
          REP(minus_l) { i =>
            out.print(i + 1)
          }

          Arrays.fill(cnt, 0)
          var deleted = 0
          TO(l, r) { i =>
            if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {
              cnt(A(i)) += 1
            } else if (deleted < minus_cur) {
              if (deleted > 0 || minus_l > 0) out.print(" ")
              out.print(i + 1)
              deleted += 1
            }
          }
          out.println()

          return
        }
      }

      if (needs(A(l)) > 0) {
        if (cnt(A(l)) <= needs(A(l))) matched -= 1
        cnt(A(l)) -= 1
      }
    }

    out.println(-1)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val M, K, N, S = ni()
    val A = na(M)
    val B = na(S)

    val cnt = Array.ofDim[Int](5e5.toInt + 1)
    val needs = Array.ofDim[Int](5e5.toInt + 1)
    REP(S) { i =>
      needs(B(i)) += 1
    }
    var matched = 0

    var r = 0
    REP(M) { l =>
      while(r + 1 < M && matched < S) {
        r += 1
        if (needs(A(r)) > 0) {
          cnt(A(r)) += 1
          if (cnt(A(r)) <= needs(A(r))) matched += 1
        }
      }

      if (matched == S) {
        val lim = M - K * N
        val minus_cur = (r - l + 1) - K
        val minus_l = l % K
        val minus = minus_cur + minus_l
        val cond1 = lim >= minus

        val cnt_l = l / K
        val cnt_r = (M - r - 1) / K
//        debug(s"cnt_r:$cnt_r")
        val cond2 = cnt_l + cnt_r + 1 >= N
        if (cond1 && cond2) {
          out.println(minus)
          // 左側の人たちはmod調節のためなのでだれを消してもいい   R
          REP(minus_l) { i =>
            out.print(i + 1)
          }

          Arrays.fill(cnt, 0)
          var deleted = 0
          TO(l, r) { i =>
            if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {
              cnt(A(i)) += 1
            } else if (deleted < minus_cur) {
              if (deleted > 0 || minus_l > 0) out.print(" ")
              out.print(i + 1)
              deleted += 1
            }
          }
          out.println()

          return
        }
      }

      if (needs(A(l)) > 0) {
        if (cnt(A(l)) <= needs(A(l))) matched -= 1
        cnt(A(l)) -= 1
      }
    }

    out.println(-1)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val M, K, N, S = ni()
    val A = na(M)
    val B = na(S)

    val cnt = Array.ofDim[Int](5e5.toInt + 1)
    val needs = Array.ofDim[Int](5e5.toInt + 1)
    REP(S) { i =>
      needs(B(i)) += 1
    }
    var matched = 0

    var r = 0
    REP(M) { l =>
      while(r + 1 < M && matched < S) {
        r += 1
        if (needs(A(r)) > 0) {
          cnt(A(r)) += 1
          if (cnt(A(r)) <= needs(A(r))) matched += 1
        }
      }

      if (matched == S) {
        val lim = M - K * N
        val minus_cur = (r - l + 1) - K
        val minus_l = l % K
        val minus = minus_cur + minus_l
        val cond1 = lim >= minus

        val cnt_l = l / K
        val cnt_r = (M - r - 1) / K
//        debug(s"cnt_r:$cnt_r")
        val cond2 = cnt_l + cnt_r + 1 >= N
        if (cond1 && cond2) {
          out.println(minus)
          // 左側の人たちはmod調節のためなのでだれを消してもいい   R
          REP(minus_l) { i =>
            out.println(i + 1)
          }

          Arrays.fill(cnt, 0)
          var deleted = 0
          TO(l, r) { i =>
            if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {
              cnt(A(i)) += 1
            } else if (deleted < minus_cur) {
              if (deleted > 0) out.print(" ")
              out.print(i + 1)
              deleted += 1
            }
          }
          out.println()

          return
        }
      }

      if (needs(A(l)) > 0) {
        if (cnt(A(l)) <= needs(A(l))) matched -= 1
        cnt(A(l)) -= 1
      }
    }

    out.println(-1)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val M, K, N, S = ni()
    val A = na(M)
    val B = na(S)

    val cnt = Array.ofDim[Int](5e5.toInt + 1)
    val needs = Array.ofDim[Int](5e5.toInt + 1)
    REP(S) { i =>
      needs(B(i)) += 1
    }
    var matched = 0

    var r = 0
    REP(M) { l =>
      while(r + 1 < M && matched < S) {
        r += 1
        if (needs(A(r)) > 0) {
          cnt(A(r)) += 1
          if (cnt(A(r)) <= needs(A(r))) matched += 1
        }
      }

      if (matched == S) {
        val lim = M - K * N
        val minus_cur = (r - l + 1) - K
        val minus_l = l % K
        val minus = minus_cur + minus_l
        val cond1 = lim >= minus

        val cnt_l = l / K
        val cnt_r = (M - r) / K
        val cond2 = cnt_l + cnt_r + 1 >= N
        if (cond1 && cond2) {
          out.println(minus)
          // 左側の人たちはmod調節のためなのでだれを消してもいい
          REP(minus_l) { i =>
            out.println(i + 1)
          }

          Arrays.fill(cnt, 0)
          var deleted = 0
          TO(l, r) { i =>
            if (needs(A(i)) > 0 && cnt(A(i)) < needs(A(i))) {
              cnt(A(i)) += 1
            } else if (deleted < minus_cur) {
              if (deleted > 0) out.print(" ")
              out.print(i + 1)
              deleted += 1
            }
          }
          out.println()

          return
        }
      }

      if (needs(A(l)) > 0) {
        if (cnt(A(l)) <= needs(A(l))) matched -= 1
        cnt(A(l)) -= 1
      }
    }

    out.println(-1)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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