Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the whole pile, and Bob gets nothing from it.After taking the candies from the piles, if Alice has more candies than Bob, she discards some candies so that the number of candies she has is equal to the number of candies Bob has. Of course, Bob does the same if he has more candies.Alice and Bob want to have as many candies as possible, and they plan the process of dividing candies accordingly. Please calculate the maximum number of candies Alice can have after this division process (of course, Bob will have the same number of candies).You have to answer $$$q$$$ independent queries.Let's see the following example: $$$[1, 3, 4]$$$. Then Alice can choose the third pile, Bob can take the second pile, and then the only candy from the first pile goes to Bob — then Alice has $$$4$$$ candies, and Bob has $$$4$$$ candies.Another example is $$$[1, 10, 100]$$$. Then Alice can choose the second pile, Bob can choose the first pile, and candies from the third pile can be divided in such a way that Bob takes $$$54$$$ candies, and Alice takes $$$46$$$ candies. Now Bob has $$$55$$$ candies, and Alice has $$$56$$$ candies, so she has to discard one candy — and after that, she has $$$55$$$ candies too.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. Then $$$q$$$ queries follow. The only line of the query contains three integers $$$a, b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 10^{16}$$$) — the number of candies in the first, second and third piles correspondingly.

Print $$$q$$$ lines. The $$$i$$$-th line should contain the answer for the $$$i$$$-th query — the maximum number of candies Alice can have after the division, if both Alice and Bob act optimally (of course, Bob will have the same number of candies).

object Main extends App {
  var q: Int = readInt()
  for (_ <- 0 until q) {
    println(readLine().split("\\s+").map(_.toLong).sum / 2)
  }
}

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

  override def apply(io: IO): io.type = {
    val input = io.read[Seq[(Long, Long, Long)]]
    val ans = input.map({case (a, b, c) => (a + b + c)/2})
    io.writeLines(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

object Main {
  import scala.util.control.Breaks.{breakable,break}
  import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue}
  import java.io._

  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  def main (args: Array[String]){
    val q = in.next().toInt
    for (_ <- 1 to q) {
      val a, b, c = in.next().toLong
      val l = List(a, b, c).sorted
      val sum = l.sum

      val x = l(0)
      val y = l(1)
      val z = l(2)

      var ans = 0L
      if (x + z < y)
        ans = x + z
      else {
        val hoge = z - (y - x)
        ans = y + hoge / 2
      }

      pw.println(ans)
    }

    pw.flush()
  }
}
import java.io._
class InputReader(stream: InputStream) {

  import java.util.StringTokenizer

  private val reader = new BufferedReader(new InputStreamReader(stream))
  private var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}

object Main extends App {
  var q: Int = readInt()
  for (_ <- 0 until q) {
    println(readLine().split("\\s").map(_.toLong).sum / 2)
  }
}


Shubham has a binary string $$$s$$$. A binary string is a string containing only characters "0" and "1".He can perform the following operation on the string any amount of times:   Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. A string is called good if it does not contain "010" or "101" as a subsequence  — for instance, "1001" contains "101" as a subsequence, hence it is not a good string, while "1000" doesn't contain neither "010" nor "101" as subsequences, so it is a good string.What is the minimum number of operations he will have to perform, so that the string becomes good? It can be shown that with these operations we can make any string good.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.

The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$ — the number of test cases. Each of the next $$$t$$$ lines contains a binary string $$$s$$$ $$$(1 \le |s| \le 1000)$$$.

For every string, output the minimum number of operations required to make it good.

NoteIn test cases $$$1$$$, $$$2$$$, $$$5$$$, $$$6$$$ no operations are required since they are already good strings.For the $$$3$$$rd test case: "001" can be achieved by flipping the first character  — and is one of the possible ways to get a good string.For the $$$4$$$th test case: "000" can be achieved by flipping the second character  — and is one of the possible ways to get a good string.For the $$$7$$$th test case: "000000" can be achieved by flipping the third and fourth characters  — and is one of the possible ways to get a good string.

//package codeforces.contests._1363

object SubsequenceHate {

  def main(args: Array[String]): Unit = {
    for (_ <- 1 to io.StdIn.readInt) {
      val s = io.StdIn.readLine()

      val ones = {
        val arr = new Array[Int](s.length)
        arr(0) = if (s(0) == '1') 1 else 0
        (1 until s.length).foreach(i => arr(i) = (if (s(i) == '1') 1 else 0) + arr(i - 1))
        arr
      }

      def onesInRange(x: Int, y: Int): Int =
        if (x > y) 0 else if (x == 0) ones(y) else ones(y) - ones(x - 1)

      def zeroesInRange(x: Int, y: Int): Int =
        if (x > y) 0 else y - x + 1 - onesInRange(x, y)

      def makeZeroCost(x: Int, y: Int): Int = onesInRange(x, y)

      def makeOneCost(x: Int, y: Int): Int = zeroesInRange(x, y)

      val last = s.length - 1

      println {
        (0 to last).foldLeft(Int.MaxValue)((acc, i) =>
          acc min (makeOneCost(0, i) + makeZeroCost(i + 1, last)) min (makeZeroCost(0, i) + makeOneCost(i + 1, last)))
      }
    }
  }

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val arr = readLine().map(_ == '1').toList
      val ans = minNum(arr)
      println(ans)
    }
//          println(minNum(List[Boolean](false, false, true)))
  }

  def minNum(list: List[Boolean]): Int = {
    def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {
      case Nil => Math.min(min, left + right)
      case b :: bs => zeroOne(bs, Math.min(min, left + right),
        if (b) left + 1 else left, if (b) right else right - 1)
    }

    Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),
      zeroOne(list.map(i => !i), list.count(i => i), 0, list.count(i => i)))
  }

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

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

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

}

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

import scala.reflect.ClassTag

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

  private[this] val isOnlineJudge = true

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

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

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

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

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

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = next()

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

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

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

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

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

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

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

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

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

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

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

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

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

  import Main._
  import fScanner._

  def solve(): Unit = {
    val T = ni()
    REP(T) { _ =>
      val s = ns()
      val cnt0 = Array.ofDim[Int](s.length+1)
      val cnt1 = Array.ofDim[Int](s.length+1)
      cnt0(0) = 0
      cnt1(0) = 0

      s.zipWithIndex.foreach { f =>
        cnt0(f._2 + 1) = cnt0(f._2) + (if(f._1 - '0' == 0) 1 else 0)
        cnt1(f._2 + 1) = cnt1(f._2) + (if(f._1 - '0' == 1) 1 else 0)
      }
//      println(cnt0.mkString(","))
//      println(cnt1.mkString(","))
      var ans = Int.MaxValue
      REP(s.length) { i =>
        val c1 = cnt1(i+1) + (cnt0(s.length) - cnt0(i+1))
        val c0 = cnt0(i+1) + (cnt1(s.length) - cnt1(i+1))
//        println(c0 + " " + c1)
        ans = Math.min(ans, Math.min(c0, c1))
      }

      out.println(ans)
    }
  }
}

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

  override def solve(io: IO) = io.repeat {
    val a = io.read[String].toList

    def count(what: Char, left: Boolean) = {
      if (left) {
        a.scanLeft(0)({case (c, d) => if (d == what) c+1 else c})
      } else {
        a.scanRight(0)({case (d, c) => if (d == what) c+1 else c})
      }
    }.drop(1)

    val r0 = count('0', left = false)
    val l1 = count('1', left = true)
    val l0 = count('0', left = true)
    val r1 = count('1', left = false)

    val ans = (l1.zip(r0) ++ l0.zip(r1)).map({case (x, y) => x + y})

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val arr = readLine().map(_ == '1').toList
      val ans = minNum(arr)
      println(ans)
    }
//          println(minNum(List[Boolean](false, false, true, true, false, false)))
  }

  def minNum(list: List[Boolean]): Int = {
    def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {
      case Nil => Math.min(min, left + right)
      case b :: bs => zeroOne(bs, Math.min(min, left + right),
        if (b) left + 1 else left, if (b) right else right + 1)
    }

    Math.min(zeroOne(list, list.count(i => i), 0, list.count(i => i)),
      zeroOne(list.map(i => !i), list.count(i => !i), 0, list.count(i => !i)))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val arr = readLine().map(_ == '1').toList
      val ans = minNum(arr)
      println(ans)
    }
//          println(minNum(List[Boolean](false, false, true, true, false, false)))
  }

  def minNum(list: List[Boolean]): Int = {
    def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {
      case Nil => Math.min(min, left + right)
      case b :: bs => zeroOne(bs, Math.min(min, left + right),
        if (b) left + 1 else left, if (b) right else right + 1)
    }

    Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),
      zeroOne(list.map(i => !i), list.count(i => !i), 0, list.count(i => !i)))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val arr = readLine().map(_ == '1').toList
      val ans = minNum(arr)
      println(ans)
    }
//          println(minNum(List[Boolean](false, false, true, true, false, false)))
  }

  def minNum(list: List[Boolean]): Int = {
    def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {
      case Nil => Math.min(min, left + right)
      case b :: bs => zeroOne(bs, Math.min(min, left + right),
        if (b) left + 1 else left - 1, if (b) right + 1 else right - 1)
    }

    Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),
      zeroOne(list.map(i => !i), list.count(i => !i), 0, list.count(i => !i)))
  }

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

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

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

}

import scala.io.StdIn.readLine

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

  def main(args: Array[String]): Unit = {
    val t = readLine().toInt
    for (i <- 1 to t) {
      val arr = readLine().map(_ == '1').toList
      val ans = minNum(arr)
      println(ans)
    }
//          println(minNum(List[Boolean](false, false, true, true, false, false)))
  }

  def minNum(list: List[Boolean]): Int = {
    def zeroOne(l: List[Boolean], min: Int, left: Int, right: Int): Int = l match {
      case Nil => Math.min(min, left + right)
      case b :: bs => zeroOne(bs, Math.min(min, left + right),
        if (b) left + 1 else left, if (b) right else right + 1)
    }

    Math.min(zeroOne(list, list.count(i => !i), 0, list.count(i => !i)),
      zeroOne(list.map(i => !i), list.count(i => i), 0, list.count(i => i)))
  }

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

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

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

}


Qpwoeirut has taken up architecture and ambitiously decided to remodel his city.Qpwoeirut's city can be described as a row of $$$n$$$ buildings, the $$$i$$$-th ($$$1 \le i \le n$$$) of which is $$$h_i$$$ floors high. You can assume that the height of every floor in this problem is equal. Therefore, building $$$i$$$ is taller than the building $$$j$$$ if and only if the number of floors $$$h_i$$$ in building $$$i$$$ is larger than the number of floors $$$h_j$$$ in building $$$j$$$.Building $$$i$$$ is cool if it is taller than both building $$$i-1$$$ and building $$$i+1$$$ (and both of them exist). Note that neither the $$$1$$$-st nor the $$$n$$$-th building can be cool.To remodel the city, Qpwoeirut needs to maximize the number of cool buildings. To do this, Qpwoeirut can build additional floors on top of any of the buildings to make them taller. Note that he cannot remove already existing floors.Since building new floors is expensive, Qpwoeirut wants to minimize the number of floors he builds. Find the minimum number of floors Qpwoeirut needs to build in order to maximize the number of cool buildings.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The first line of each test case contains the single integer $$$n$$$ ($$$3 \le n \le 10^5$$$) — the number of buildings in Qpwoeirut's city. The second line of each test case contains $$$n$$$ integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le 10^9$$$) — the number of floors in each of the buildings of the city. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the minimum number of additional floors Qpwoeirut needs to build in order to maximize the number of cool buildings.

NoteIn the first test case, it is optimal for Qpwoeirut to make the second building cool by building $$$2$$$ additional floors on top of it, making it taller than both of its adjacent buildings. The final heights of buildings will be $$$[2, \underline{3}, 2]$$$.  In the second test case, the number of cool buildings is already maximized, so Qpwoeirut does not need to do anything.In the third test case, it is optimal for Qpwoeirut to make the third and fifth buildings cool by building $$$2$$$ additional floors onto the third building and $$$1$$$ additional floor onto the fifth building. The final heights of buildings will be $$$[3, 1, \underline{6}, 5, \underline{6}, 2]$$$.  It can be shown that it is impossible to make more than $$$2$$$ of the buildings cool, or to make $$$2$$$ buildings cool using fewer than $$$3$$$ additional floors.In the fourth test case, Qpwoeirut can either make the second building cool, or he can make the third building cool. Either way, he will be building $$$3$$$ additional floors and maximizing the number of cool buildings. The final heights of buildings will be $$$[4, 2, \underline{4}, 3, 5, 3, 6, 1]$$$ or $$$[4, \underline{5}, 1, 3, 5, 3, 6, 1]$$$.

object prob2 {
  def main(args: Array[String]) = {
    new Resolver3(Console.in, Console.out).run()
  }
}

class Resolver3(input: java.io.BufferedReader, output: java.io.PrintStream) {

  import java.util.StringTokenizer
  import scala.collection.mutable
  import scala.collection.mutable._
  import scala.math.{abs,pow,min,max}
  import scala.collection.mutable.ListBuffer

  def run() {
    var tokenizer = new StringTokenizer(input.readLine())
    val q = tokenizer.nextToken().toInt
    for (sss <- 0 until q) {
      tokenizer = new StringTokenizer(input.readLine())
      val n = tokenizer.nextToken().toInt
      val A = new Array[Int](n)
      tokenizer = new StringTokenizer(input.readLine())
      for (i <- 0 until n) {
        A(i) = tokenizer.nextToken().toInt
      }
      var count: Long = 0
      var count2: Long = 0
      if ((n % 2) == 1) {
        for {i <- A.indices
             if ((i %2) == 1)} {
          count+= max(0, max(A(i-1) - A(i) + 1, A(i+1) - A(i) + 1))
        }
        println(count)
      }
      else {
        val L = new Array[Long](n/2)
        val R = new Array[Long](n/2)
        val S = new Array[Long](n/2)
        L(0) = 0
        R((n/2) - 1) = 0
        for {i <- A.indices
             if (((i %2) == 1) && (i < (n-1)))} {
          count+= max(0, max(A(i-1) - A(i) + 1, A(i+1) - A(i) + 1))
          L(1+((i-1) / 2)) = count
        }
        for {i <- A.indices
             if (((i %2) == 1) && (i < (n-1)))} {
          count2+= max(0, max(A(n-1-i+1) - A(n-1-i) + 1, A(n-1-i-1) - A(n-1-i) + 1))
          R(n/2 - 2 - ((i-1) / 2)) = count2
        }
        for (i <- S.indices) {
          S(i) = L(i) + R(i)
        }
        println(S.min)
      }
    }
  }
}


One fine October day a mathematics teacher Vasily Petrov went to a class and saw there n pupils who sat at the  desks, two people at each desk. Vasily quickly realized that number n is even. Like all true mathematicians, Vasily has all students numbered from 1 to n.But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.

The first input line contains a single even integer n (4 ≤ n ≤ 100) — the number of students in the class. The second line contains exactly n capital English letters "L" and "R". If the i-th letter at the second line equals "L", then the student number i is a lefthander, otherwise he is a righthander.

Print  integer pairs, one pair per line. In the i-th line print the numbers of students that will sit at the i-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.

import scala.io.Source
import java.io.PrintWriter
import java.io.File

object Olymp{
  def main(args: Array[String]): Unit = {
    val it = Source.fromFile("input.txt").getLines
    val writer = new PrintWriter(new File("output.txt" ))
    val n = it.next.toInt
    val orientation = it.next.trim()

    def PRINT(a: Int, b: Int) = if (orientation.charAt(a) == 'R' && orientation.charAt(b) == 'L') writer.println((b+1)+" "+(a+1))
                                         else writer.println((a+1)+" "+(b+1))

    def solve(xs: List[Int]):Unit = xs match {
      case List(a, b) => PRINT(a, b)
      case a :: b :: c :: tail => PRINT(a, c); solve(b :: tail)
    }

    solve(0 to n-1 toList)
    writer.close()
  }
}


Alica and Bob are playing a game.Initially they have a binary string $$$s$$$ consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string $$$s$$$ and delete them. For example, if $$$s = 1011001$$$ then the following moves are possible:   delete $$$s_1$$$ and $$$s_2$$$: $$$\textbf{10}11001 \rightarrow 11001$$$;  delete $$$s_2$$$ and $$$s_3$$$: $$$1\textbf{01}1001 \rightarrow 11001$$$;  delete $$$s_4$$$ and $$$s_5$$$: $$$101\textbf{10}01 \rightarrow 10101$$$;  delete $$$s_6$$$ and $$$s_7$$$: $$$10110\textbf{01} \rightarrow 10110$$$. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.

First line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Only line of each test case contains one string $$$s$$$ ($$$1 \le |s| \le 100$$$), consisting of only characters 0 and 1.

For each test case print answer in the single line. If Alice can win print DA (YES in Russian) in any register. Otherwise print NET (NO in Russian) in any register.

NoteIn the first test case after Alice's move string $$$s$$$ become empty and Bob can not make any move.In the second test case Alice can not make any move initially.In the third test case after Alice's move string $$$s$$$ turn into $$$01$$$. Then, after Bob's move string $$$s$$$ become empty and Alice can not make any move.

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val s = readLine()

    val t1 = s.count(_ == '1')
    val t2 = s.length - t1

    if ((t1 min t2) % 2 == 0) println("NET")
    else println("DA")
  }
}


You are given an array $$$a_1, a_2, \dots, a_n$$$ where all $$$a_i$$$ are integers and greater than $$$0$$$. In one operation, you can choose two different indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$). If $$$gcd(a_i, a_j)$$$ is equal to the minimum element of the whole array $$$a$$$, you can swap $$$a_i$$$ and $$$a_j$$$. $$$gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$. Now you'd like to make $$$a$$$ non-decreasing using the operation any number of times (possibly zero). Determine if you can do this. An array $$$a$$$ is non-decreasing if and only if $$$a_1 \le a_2 \le \ldots \le a_n$$$.

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

For each test case, output "YES" if it is possible to make the array $$$a$$$ non-decreasing using the described operation, or "NO" if it is impossible to do so.

Note In the first and third sample, the array is already non-decreasing. In the second sample, we can swap $$$a_1$$$ and $$$a_3$$$ first, and swap $$$a_1$$$ and $$$a_5$$$ second to make the array non-decreasing. In the forth sample, we cannot the array non-decreasing using the operation.

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

  val t = readInt()

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

    // format: off
    val ans = (an zip an.sorted).forall {
      case (x, y) if x == y     => true
      case (x, y) if x % a == 0 => true
      case _                    => false
    }
    // format: on

    if (ans) println("YES") else println("NO")
  }
}

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

  private def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)

  val t = readInt()

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

    val ans = (an zip an.sorted).forall {
      case (x, y) if x == y               => true
      case (x, y) if gcd(x, amin) == amin => true
      case _                              => false
    }

    if (ans) println("YES") else println("NO")
  }
}

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

  private def gcd(a: Int, b: Int): Int =
    if (b == 0) a else gcd(b, a % b)

  val t = readInt()

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

    val ans = (an zip an.sorted).forall {
      case (x, y) if x == y               => true
      case (x, y) if gcd(x, amin) == amin => true
      case _                              => false
    }

    println(ans)
  }
}


According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open.You are given a jacket with n buttons. Determine if it is fastened in a right way.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of buttons on the jacket. The second line contains n integers ai (0 ≤ ai ≤ 1). The number ai = 0 if the i-th button is not fastened. Otherwise ai = 1.

In the only line print the word "YES" if the jacket is fastened in a right way. Otherwise print the word "NO".

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val buttons = in.next().count(_ == '1')
  if (buttons == 0 || (n != 1 && (n - buttons) != 1))
    println("NO")
  else
    println("YES")
}

import scala.io.StdIn._

object A extends App {
  val n = readInt()
  val B = readLine().split(" ").map(_ == "1")

  if (B.length == 1) {
    if (B.head == true) println("YES") else println("NO")
  } else {
    if (B.count(_ == false) == 1) println("YES") else println("NO")
  }

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val n = in.next().toInt
  val buttons = in.next().count(_ == '1')
  if (buttons == 0 || (n - buttons) != 1)
    println("NO")
  else
    println("YES")
}


People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects.Alis is among these collectors. Right now she wants to get one of k-special tables. In case you forget, the table n × n is called k-special if the following three conditions are satisfied:  every integer from 1 to n2 appears in the table exactly once;  in each row numbers are situated in increasing order;  the sum of numbers in the k-th column is maximum possible. Your goal is to help Alice and find at least one k-special table of size n × n. Both rows and columns are numbered from 1 to n, with rows numbered from top to bottom and columns numbered from left to right.

The first line of the input contains two integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n) — the size of the table Alice is looking for and the column that should have maximum possible sum.

First print the sum of the integers in the k-th column of the required table. Next n lines should contain the description of the table itself: first line should contains n elements of the first row, second line should contain n elements of the second row and so on. If there are multiple suitable table, you are allowed to print any.

/**
  * Created by octavian on 07/02/2016.
  */
object KSpecial {

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

    //System.setIn(new FileInputStream("./src/kspecial.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/kspecial.out")))

    var Array(n, k) = readLine().split(" ").map(_.toInt)
    var r :Array[Array[Int]] = Array.ofDim[Int](n + 1, n + 1)
    var sum = 0

    var current = 1
    for(i <- 1 to n) {
      for(j <- 1 until k) {
        r(i)(j) = current
        current += 1
      }
    }

    for(i <- 1 to n) {
      for(j <- k to n) {
        r(i)(j) = current
        if(j == k) {
          sum += current
        }

        current += 1
      }
    }

    println(sum)
    for(i <- 1 to n) {
      println(r(i).tail.mkString(" "))
    }

  }

}

object A {
  def main(args: Array[String]) {
    val Array(n, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    var l = 0
    var r = n*(k-1)+1
    val s = (r + n*n - n + k) * n /2
    println(s)
    (1 to n).foreach(x => {
      println(((l+1 until l + k) ++ (r until r + n - k + 1)).mkString(" "))
      l += k - 1
      r += n - k + 1
    })
  }
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, k) = in.next().split(' ').map(_.toInt)
  val start = n * (k - 1) + 1
  val kColumn = start * n + (n - k + 1) * (n - 1) * n / 2
  var first = 1
  var second = start
  println(kColumn)
  println((0 until n).map{ i =>
    (0 until n).map { j =>
      if (j % n < k - 1) {
        first += 1
        first - 1
      } else {
        second += 1
        second - 1
      }
    }.mkString(" ")
  }.mkString("\n"))
}

import scala.annotation.tailrec
object Main {
  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    def main() : Unit = {
      val n, k = nextInt()

      val buf = new StringBuilder()
      var retc = 0
      for(i <- 0 until n) {
        val lefts  = (k-1) * i + 1
        val rights = ((k-1) * n + 1) + i*(n-k+1)
        retc += rights
        val left  = lefts  until (lefts  + k - 1)
        val right = rights to (rights + n-k)
        buf ++= (left ++ right).mkString(" ") + "\n"
        // println((left ++ right).mkString(" "))
      }
      println(retc)
      print(buf.toString)

      // val a = n * (k-1) + 1
      // var c = 0L
      // for(i <- (0L until n)) {
      //   val m = if(n != k) Seq(a + k * i) else Seq(a + i)
      //   c += m.head
      // }
      // val ca= (k to (n*n) by n).sum
      // if(ca >= c){
      //   println(ca)
      //   for(line <- (1L to (n*n)).grouped(n.toInt)){
      //     println(line.mkString(" "))
      //   }
      // }else{
      //   println(c)
      //   for(i <- (0L until n)) {
      //     val left_f = (k-1) * i + 1
      //     val l = left_f until (left_f + k-1)
      //     val m = if(n != k) Seq(a + k * i) else Seq(a + i)
      //     val r = (m.head + 1) to (m.head + (n-k))
      //     println((l ++ m ++ r).mkString(" "))
      //   }
      // }
    }
  }
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

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

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

// object Main
import java.io.{IOException, InputStream, PrintWriter}
import java.util.InputMismatchException

object Main {

    def solveCase(caseNo: Int, in: InputReader, out: PrintWriter): Unit = {
        val n = in.nextInt()
        val k = in.nextInt() - 1
        var t = n * n
        val table = Array.ofDim[Int](n, n)
        var answer = 0
        for (i <- (0 until n).reverse) {
            for (j <- (k until n).reverse) {
                table(i)(j) = t
                if (j == k) answer += t
                t -= 1
            }
        }
        for (j <- (0 until k).reverse) {
            for (i <- (0 until n).reverse) {
                table(i)(j) = t
                t -= 1
            }
        }
        out.println(answer)
        for (line <- table) {
            out.println(line.mkString(" "))
        }
    }

    def solve(in: InputReader, out: PrintWriter): Unit = {
        solveCase(1, in, out)
//        val caseCount = in.nextInt()
//        for (caseNo <- 1 to caseCount) {
//            solveCase(caseNo, in, out)
//        }
    }

    def main(args: Array[String]) {
        val in = new InputReader(System.in)
        val out = new PrintWriter(System.out)

        solve(in, out)

        in.close()
        out.close()
    }
}

class InputReader(val inputStream: InputStream) {
    val buf = new Array[Byte](1 << 16)
    var curChar = 0
    var numChars = 0

    def read(): Int = {
        if (numChars == -1) {
            throw new InputMismatchException()
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => throw new InputMismatchException()
            }
            if (numChars <= 0)
                return -1
        }
        curChar += 1
        buf(curChar - 1)
    }

    def peek(): Int = {
        if (numChars == -1) {
            return -1
        }
        if (curChar >= numChars) {
            curChar = 0
            try {
                numChars = inputStream.read(buf)
            } catch {
                case _: IOException => return -1
            }
            if (numChars <= 0)
                return -1
        }
        buf(curChar)
    }

    def isSpaceChar(c: Int): Boolean = c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1

    def nextInt(): Int = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def nextLong(): Long = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        var sgn = 1
        if (c == '-') {
            sgn = -1
            c = read()
        }
        var res = 0l
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException()
            res *= 10
            res += c & 15
            c = read()
        } while (!isSpaceChar(c))
        res * sgn
    }

    def next(): String = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        val res = new StringBuilder()
        do {
            res += c.toChar
            c = read()
        } while (!isSpaceChar(c))
        res.toString()
    }

    def nextChar(): Char = {
        var c = read()
        while (isSpaceChar(c)) c = read()
        c.toChar
    }

    //noinspection AccessorLikeMethodIsEmptyParen
    def hasNext(): Boolean = {
        var value = peek()
        do {
            read()
            value = peek()
        } while (isSpaceChar(value) && value != -1)
        value != -1
    }

    def rawNextLine(): String = {
        val builder = new StringBuilder
        var c = read()
        while (c != '\n' && c != -1) {
            if (c != '\r')
                builder += c.toChar
            c = read()
        }
        builder.toString()
    }

    def nextLine(): String = {
        var s = rawNextLine()
        while (s.trim().length == 0) s = rawNextLine()
        s
    }

    def nextDouble(): Double = {
        next().toDouble
    }

    def close(): Unit = {
        inputStream.close()
    }
}

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

import scala.annotation.implicitNotFound
import scala.reflect.ClassTag

/**
  * Created by nimas on 2/4/16.
  */
object A extends App{

  class Template(val delim: String = " ") {

    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    val it = Iterator.iterate(new StringTokenizer(""))(tok => if (tok.hasMoreTokens) tok else new StringTokenizer(in.readLine(), delim))

    def nextTs[T: ParseAble](n: Int)(delim: String = " ")(implicit ev: ClassTag[T]) = (Array fill n) {
      nextT[T](delim)
    }

    def nextT[T](delim: String = " ")(implicit parser: ParseAble[T]) = {
      val x = it.find(_.hasMoreTokens)
      parser parse (x get)
    }

    def close(): Unit = {
      in.close()
      out.close()
    }

    @implicitNotFound("No member of type class ParseAble in scope for ${T}")
    trait ParseAble[T] {
      def parse(strTok: StringTokenizer): T
    }

    object ParseAble {

      implicit object ParseAbleString extends ParseAble[String] {
        override def parse(strTok: StringTokenizer): String = strTok nextToken()
      }

      implicit object ParseAbleInt extends ParseAble[Int] {
        override def parse(strTok: StringTokenizer): Int = strTok nextToken() toInt
      }

      implicit object ParseAbleLong extends ParseAble[Long] {
        override def parse(strTok: StringTokenizer): Long = strTok nextToken() toLong
      }

      implicit object ParseAbleDouble extends ParseAble[Double] {
        override def parse(strTok: StringTokenizer): Double = strTok nextToken() toDouble
      }

      implicit object ParseAbleBigInt extends ParseAble[BigInt] {
        override def parse(strTok: StringTokenizer): BigInt = BigInt(strTok nextToken())
      }

    }

  }

  val io = new Template()

  import io._

  val (n, k) = (nextT[Int](), nextT[Int]())

  val xs = Array.fill(n + 1, n + 1) {0}

  var minLast = 1

  var em = n - k

  var highLast = (n * n) - em

  var curow = 1
  var max = 0

  while(curow <= n) {

    var curHigh = highLast
    for (c <- k to n) {
      xs(curow)(c) = curHigh
      curHigh = curHigh + 1
    }

    max = max + xs(curow)(k)

    highLast = highLast  - em - 1

    for (c <- 1 until k) {
      xs(curow)(c) = minLast
      minLast = minLast + 1
    }

    curow = curow + 1
  }

  out println max
  for (r <- 1 to n) {
    out.print(xs(r) drop 1 mkString " ")
    out println()
  }

  close()

}

/**
 * @author pvasilyev
 * @since 27 Aug 2016
 */
object C625 extends App {

  def solve() = {
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val a: Array[Array[Int]] = Array.ofDim[Int](n, n)
    var value = 1
    for (i <- 0 until n) {
      for (j <- 0 until k - 1) {
        a(i)(j) = value
        value += 1
      }
    }
    for (i <- 0 until n) {
      for (j <- k - 1 until n) {
        a(i)(j) = value
        value += 1
      }
    }

    println((0 until n).map(i => a(i)(k-1)).sum)

    val sb = StringBuilder.newBuilder

    for (i <- 0 until n) {
      for (j <- 0 until n) {
        sb append a(i)(j).toString append " "
      }
      sb append "\n"
    }
    println(sb)
  }

  solve()

}

import scala.io.Source

object round_342_div2_C {
    def main(args: Array[String]){
        val in = Source.stdin.getLines()
        val ln = in.next().split(" ")
        val n = ln(0).toInt
        val k = ln(1).toInt

        var tot = 0
        for (i <- 1 to n) {
            tot += 1+n*(k-1) + (i-1)*(n-k+1)
        }
        println(tot)

        for (i <- 1 to n) {
            var res = ""
            for (j <- 1 to (k - 1)) {
                res = res + "%d ".format(j+(i-1)*(k-1))
            }
            for (j <- 1 to (n - k + 1)) {
                res = res + "%d ".format(j + n*(k-1) + (i-1)*(n-k+1))
            }
            println(res.trim)
        }
    }
}

import scala.io.Source

object round_342_div2_C {
    def main(args: Array[String]){
        val in = Source.stdin.getLines()
        val ln = in.next().split(" ")
        val n = ln(0).toInt
        val k = ln(1).toInt

        var tot = 0
        for (i <- 1 to n) {
            tot += 1+n*(k-1) + (i-1)*(n-k+1)
        }
        println(tot)

        for (i <- 1 to n) {
            //for (j <- 1 to (k - 1)) {
            //    res = res + "%d ".format(j+(i-1)*(k-1))
            //}
            val left = 1+(i-1)*(k-1) to (k-1)+(i-1)*(k-1)
            //for (j <- 1 to (n - k + 1)) {
            //   res = res + "%d ".format(j + n*(k-1) + (i-1)*(n-k+1))
            //}
            val right = 1+n*(k-1)+(i-1)*(n-k+1) to (n-k+1) + n*(k-1)+(i-1)*(n-k+1)

            println((left++right).mkString(" ").trim)
        }
    }
}

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

object _625C extends CodeForcesApp {
  override type Result = (Int, Array[Array[Int]])

  override def solve(read: InputReader) = {
    val (n, k) = (read[Int], read[Int])
    val table = Array.ofDim[Int](n, n)
    var i = 0
    for {
      r <- 0 until n
      c <- 0 until (k-1)
    } {
      i = i + 1
      table(r)(c) = i
    }
    var sum = 0
    for {
      r <- 0 until n
      c <- 0 until n if table(r)(c) == 0
    } {
      i = i + 1
      table(r)(c) = i
      if (c == k-1) sum += i
    }
    sum -> table
  }

  override def format(result: Result) = {
    val (t, m) = result
    s"$t\n${m.map(_ mkString " ") mkString "\n"}"
  }
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(next())

  def tillEndOfLine(): String = tokenizer().get.nextToken("\n\r")
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

trait Parser[A] {
  def apply(s: String): A
}
object Parser {
  def apply[A](f: String => A) = new Parser[A] {
    override def apply(s: String) = f(s)
  }
  implicit val stringParser: Parser[String] = Parser(identity)
  implicit val charParser: Parser[Char] = Parser(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val booleanParser: Parser[Boolean] = Parser(_.toBoolean)
  implicit val intParser: Parser[Int] = Parser(_.toInt)
  implicit val longParser: Parser[Long] = Parser(_.toLong)
  implicit val bigIntParser: Parser[BigInt] = Parser(BigInt(_))
  implicit val doubleParser: Parser[Double] = Parser(_.toDouble)
  implicit val bigDecimalParser: Parser[BigDecimal] = Parser(BigDecimal(_))
}

object A {
  def main(args: Array[String]) {
    val Array(n, k) = scala.io.StdIn.readLine.split(" ").map(_.toInt)
    var l = 0
    var r = n*(k-1)+1
    val s = (r + n*n - n + k) * n /2
    println(s)
    (1 to n).foreach(x => {
      println((l+1 until l + k) ++ (r until r + n - k + 1))
      l += k - 1
      r += n - k + 1
    })
  }
}

import scala.annotation.tailrec
object Main {
  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    def main() : Unit = {
      val n, k = nextLong()

      val a = n * (k-1) + 1
      // val b = a + k * (n-1)
      // val c = (a+b)* n / 2
      var c = 0L
      var output = ""
      for(i <- (0L until n)) {
        val left_f = (k-1) * i + 1
        val l = left_f until (left_f + k-1)
        assert(l.length == (k-1))
        val m = Seq(a + n * i)
        c += m.head
        val r = (m.head + 1) to (m.head + (n-k))
        assert(r.length == n-k)
        output += ((l ++ m ++ r).mkString(" ")) + "\n"
      }
      println(c)
      print(output)
    }
  }
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

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

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

import scala.annotation.tailrec
object Main {
  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    def main() : Unit = {
      val n, k = nextLong()

      val a = n * (k-1) + 1
      var c = 0L
      for(i <- (0L until n)) {
        val m = if(n != k) Seq(a + k * i) else Seq(a + i)
        c += m.head
      }
      val ca= (k to (n*n) by n).sum
      if(ca >= c){
        println(ca)
        for(line <- (1L to (n*n)).grouped(n.toInt)){
          println(line.mkString(" "))
        }
      }else{
        println(c)
        for(i <- (0L until n)) {
          val left_f = (k-1) * i + 1
          val l = left_f until (left_f + k-1)
          val m = if(n != k) Seq(a + k * i) else Seq(a + i)
          val r = (m.head + 1) to (m.head + (n-k))
          println((l ++ m ++ r).mkString(" "))
        }
      }
    }
  }
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

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

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

import scala.annotation.tailrec
object Main {
  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    def main() : Unit = {
      val n, k = nextLong()

      if(k != 1) {
        val a = n * (k-1) + 1
        // val b = a + k * (n-1)
        // val c = (a+b)* n / 2
        var c = 0L
        var output = ""
        for(i <- (0L until n)) {
          val left_f = (k-1) * i + 1
          val l = left_f until (left_f + k-1)
          assert(l.length == (k-1))
          val m = Seq(a + k * i)
          c += m.head
          val r = (m.head + 1) to (m.head + (n-k))
          assert(r.length == n-k)
          output += ((l ++ m ++ r).mkString(" ")) + "\n"
        }
        println(c)
        print(output)
      } else {
        println((1L to (n*n) by n).sum)
        for(line <- (1L to (n*n)).grouped(n.toInt)){
          println(line.mkString(" "))
        }
      }
    }
  }
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

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

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

import scala.annotation.tailrec
object Main {
  def main(args: Array[String]) : Unit = {
    val console = new MyConsole(Console.in, Console.out, Console.err)
    val solver  = new Solver(console)
    solver.main()
    console.flush()
  }
  class Solver(val stdio: MyConsole){
    import stdio._ // shadow Console.~
    def main() : Unit = {
      val n, k = nextLong()

      val a = n * (k-1) + 1
      var c = 0L
      var output = ""
      for(i <- (0L until n)) {
        val left_f = (k-1) * i + 1
        val l = left_f until (left_f + k-1)
        assert(l.length == (k-1))
        val m = Seq(a + k * i)
        c += m.head
        val r = (m.head + 1) to (m.head + (n-k))
        assert(r.length == n-k)
        output += ((l ++ m ++ r).mkString(" ")) + "\n"
      }
      val ca= (k to (n*n) by n).sum
      if(ca >= c){
        println(ca)
        for(line <- (1L to (n*n)).grouped(n.toInt)){
          println(line.mkString(" "))
        }
      }else{
        println(c)
        print(output)
      }
    }
  }
  import java.io.{BufferedReader, PrintWriter, PrintStream, PushbackReader}
  class MyConsole(val in: BufferedReader, val _out: PrintStream,
                  val err: PrintStream) {
    // PrintWriter do not flush automatically
    val out = new PrintWriter(_out,false)
    // If argument is null, there are ambiguous which function will be called
    def print(obj: Any)                  = out.print(if(obj == null) "null" else obj.toString)
    def println()                        = out.println()
    def println(obj: Any)                = out.println(obj)
    def printf(text: String, args: Any*) = out.printf(text.format(args : _*))
    // NOTE: YOU MUST FLUSH BEFORE END OF MAIN
    def flush()                          = out.flush()
    def debugln(obj: Any)                = err.println("\u001b[36m" + obj + "\u001b[0m")

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

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


You are given two integers $$$a$$$ and $$$b$$$, and $$$q$$$ queries. The $$$i$$$-th query consists of two numbers $$$l_i$$$ and $$$r_i$$$, and the answer to it is the number of integers $$$x$$$ such that $$$l_i \le x \le r_i$$$, and $$$((x \bmod a) \bmod b) \ne ((x \bmod b) \bmod a)$$$. Calculate the answer for each query.Recall that $$$y \bmod z$$$ is the remainder of the division of $$$y$$$ by $$$z$$$. For example, $$$5 \bmod 3 = 2$$$, $$$7 \bmod 8 = 7$$$, $$$9 \bmod 4 = 1$$$, $$$9 \bmod 9 = 0$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$q$$$ ($$$1 \le a, b \le 200$$$; $$$1 \le q \le 500$$$). Then $$$q$$$ lines follow, each containing two integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le 10^{18}$$$) for the corresponding query.

For each test case, print $$$q$$$ integers — the answers to the queries of this test case in the order they appear.

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

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

  def lcm(a: Long, b: Long): Long = a / gcd(a, b) * b

  for (_ <- 1 to nextInt) {
    val a, b, q = nextLong
    val res = Array.ofDim[Long](q.toInt)
    val g = lcm(a, b)
    val m = a max b

    def count(i: Long): Long = {
      i / g * (g - m) + Math.max(i % g - m + 1, 0L)
    }

    for (i <- 0 until q.toInt) {
      val l, r = nextLong
      res(i) = count(r) - count(l - 1)
    }

    out.println(res.mkString(" "))
  }

  out.flush()

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

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

  (0 until t).foreach { _ =>
    val Array(a, b, q) = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

    val m   = a.max(b)
    val lcm = a / a.gcd(b) * b

    def prefix(p: BigInt): BigInt = {
      val i = p / lcm
      i * m + p.min(i * lcm + m - 1) - i * lcm + 1
    }

    val ans = (0 until q.toInt).map { _ =>
      val Array(l, r) = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

      val (i, j) = (l / lcm, r / lcm)

      r - l + 1 - prefix(r) + prefix(l - 1)
    }

    println(ans.mkString(" "))
  }
}

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

  (0 until t).foreach { _ =>
    val Array(a, b, q) = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

    val m   = a.max(b)
    val lcm = a / a.gcd(b) * b

    (0 until q.toInt).foreach { _ =>
      val Array(l, r) = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

      val (i, j) = (l / lcm, r / lcm)

      val ans = List(i, j).distinct.foldLeft(r - l + 1 - (j - i - 1).max(0) * m) { (s, k) =>
        val t = k * lcm

        if (t + m - 1 < l) s
        else s - r.min(t + m - 1) + l.max(t) - 1
      }

      print(s"$ans ")
    }

    println()
  }
}

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

  (0 until t).foreach { _ =>
    val Array(a, b, q) = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

    val m   = a.max(b)
    val lcm = a / a.gcd(b) * b

    (0 until q.toInt).foreach { _ =>
      val Array(l, r) = scala.io.StdIn.readLine().split(" ").map(BigInt(_))

      val (p, q) = (l / lcm, r / lcm)

      val ans = (p to q).foldLeft(r - l + 1) { (s, i) =>
        val t = r.min(l.max(i * lcm + m - 1)) - l.max(i * lcm)

        if (t == 0) s
        else s - t - 1
      }

      print(s"$ans ")
    }

    println()
  }
}