/**
 * @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()

}

/**
  * 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()

}

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


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

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


object A489 {

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val res = cu.ArrayBuffer.empty[(Int, Int)]
    for(i <- 0 until n){
      val sl = in.slice(i, n)
      val min = sl.min
      val idx = sl.indexOf(min)
      if(idx != 0) {
        res.append((i, i+idx))
        val temp = in(i+idx)
        in(i+idx) = in(i)
        in(i) = temp
      }
    }
    println(res.length)
    println(res.map{case (x, y) => s"$x $y"}.mkString("\n"))
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    @inline def read: String = input.readLine()

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

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import java.util.StringTokenizer
import scala.collection.mutable.ArrayBuffer

object _489A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => next.toInt).toArray
  val buffer = new ArrayBuffer[(Int, Int)]

  def doit(i: Int): Unit = {
    if (i < n) {
      val min = (i until n).minBy(i => a(i))
      if (i != min) {
        buffer.append((i, min))
        val cb = a(i)
        a(i) = a(min)
        a(min) = cb
      }
      doit(i + 1)
    }
  }

  doit(0)

  val ans = buffer.result
  println(ans.length)
  ans.foreach(pair => println(pair._1 + " " + pair._2))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  var data = in.next().split(" ").map(_.toInt)
  println(data.length - 1)
  println((0 until n - 1).map { i =>
    val index = data.indexOf(data.min) + i
    data(index - i) = data(0)
    data = data.tail
    s"$i $index"
  }.mkString("\n"))
}

object SB_1 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    val arr:Array[Int]=new Array[Int](n)

    val m=readLine()
    val line:Array[String]=m.split(" ")
    for(i<-0 until arr.length){
      arr(i)=line(i).toInt
    }

    var re:List[Array[Int]]=List()

    for(i<-0 until arr.length-1){
      var index:Int=i+1
      var sub:Int=arr(i)-arr(i+1)
      var flag:Boolean=false
      for(j<-i+1 until arr.length) {
        if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {
          sub = arr(i) - arr(j)
          index = j
          flag=true
        }
      }

      if(flag==true){
        val temp: Int = arr(i)
        arr(i) = arr(index)
        arr(index) = temp
        re = re ++ List(Array(i, index))
      }
    }
    println(re.length)
    if(re.length>0)
      for(l<-re)
        println(l(0)+" "+l(1))
  }

}

import scala.io.StdIn.readLine
import scala.io.StdIn.readInt

object SwapSort {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def readLongs() : Array[Long] =
      readLine.split(' ').map(_.toLong)

   def readTuple() : (Int,Int) = {
     val line = readInts
     (line(0),line(1))
   }
   def readTupleLong() : (Long,Long) = {
     val line = readLongs
     (line(0),line(1))
   }

   def readTriple() : (Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2))
   }
   def readQuad() : (Int,Int,Int,Int) = {
     val line = readInts
     (line(0),line(1),line(2),line(3))
   }

   def findSwaps(xs: IndexedSeq[Int]) : List[(Int,Int)] = {
     def go(xs: IndexedSeq[Int], acc: List[(Int,Int)]) : List[(Int,Int)] = {
       if (xs.size == 1) acc.reverse
       else {
         val maxIndex = xs.indexOf(xs.max)
         if (maxIndex == xs.size - 1) go(xs.init,acc)
         else {
         val (first,second) = xs.splitAt(maxIndex)
         go ( (first ++ (xs.last +: second.tail)).init,
             (maxIndex, xs.size - 1) :: acc)
         }
       }

     }
     go(xs,List())
   }

   def main(args: Array[String]) : Unit = {
     val n = readInt
     val xs = readInts
     val swaps = findSwaps(xs)
     println(swaps.length)
     swaps.foreach{
       case (i,j) => println(s"$i $j")
     }
   }

}

object A {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    if (n == 0) {
      println(0)
    } else {
      val a = readLine().split(" ").toList.map(_.toInt)
      val steps = find(a, 0, List()).reverse
      println(steps.size)
      steps.foreach(x => println(x._1 + " " + x._2))
    }
  }

  def find(a: List[Int], pos: Int, steps: List[(Int, Int)]): List[(Int, Int)] = a match {
    case Nil => steps
    case x :: xs => {
      val min = a.min
      if (x == min) find(xs, pos + 1, steps)
      else {
        val p = xs.indexOf(min)
        find(xs.updated(p, x), pos + 1, (pos, pos + p + 1) :: steps)
      }
    }
  }
}

object A {
  def main(args: Array[String]): Unit = {
    val n = readInt()
    if (n == 0) {
      println(0)
    } else {
      val a = readLine().split(" ").toList.map(_.toInt)
      val steps = find(a, 0, List()).reverse
      println(steps.size)
      steps.foreach(x => println(x._1 + " " + x._2))
    }
  }

  def find(a: List[Int], pos: Int, steps: List[(Int, Int)]): List[(Int, Int)] = a match {
    case Nil => steps
    case x :: xs => {
      val min = a.min
      if (x == min) find(xs, pos + 1, steps)
      else {
        val p = xs.indexOf(min)
        val split0 = xs.splitAt(p)
        val split1 = xs.splitAt(p + 1)
        find(List(split0._1, List(x), split1._2).flatten, pos + 1, (pos, pos + p + 1) :: steps)
      }
    }
  }
}

object SB_1 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    val arr:Array[Int]=new Array[Int](n)

    val m=readLine()
    val line:Array[String]=m.split(" ")
    for(i<-0 until arr.length){
      arr(i)=line(i).toInt
    }

//    var re:List[Array[Int]]=List()
//
//    for(i<-0 until arr.length-1){
//      var index:Int=i+1
//      var sub:Int=arr(i)-arr(i+1)
//      for(j<-i+1 until arr.length) {
//        if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {
//          sub = arr(i) - arr(j)
//          index = j
//
//          val temp: Int = arr(i)
//          arr(i) = arr(j)
//          arr(j) = temp
//          re = re ++ List(Array(i, j))
//        }
//      }
//    }

    var re:List[Array[Int]]=List()

    for(i<-0 until arr.length-1){
      for (j<-0 until arr.length - 1 - i)
        if (arr(j)>arr(i)) {
                    val temp: Int = arr(i)
                    arr(i) = arr(j)
                    arr(j) = temp
                    re = re ++ List(Array(i, j))
                  }
    }

    println(re.length)
    if(re.length>0)
      for(l<-re)
        println(l(0)+" "+l(1))
  }

}

object SB_1 {
  def main(args:Array[String]):Unit={
    val n:Int=readInt()
    val arr:Array[Int]=new Array[Int](n)

    val m=readLine()
    val line:Array[String]=m.split(" ")
    for(i<-0 until arr.length){
      arr(i)=line(i).toInt
    }

    var re:List[Array[Int]]=List()

    for(i<-0 until arr.length-1){
      var index:Int=i+1
      var sub:Int=arr(i)-arr(i+1)
      for(j<-i+1 until arr.length) {
        if (arr(i) - arr(j) >= sub && arr(i) > arr(j)) {
          sub = arr(i) - arr(j)
          index = j

          val temp: Int = arr(i)
          arr(i) = arr(j)
          arr(j) = temp
          re = re ++ List(Array(i, j))
        }
      }
    }

    println(re.length)
    if(re.length>0)
      for(l<-re)
        println(l(0)+" "+l(1))
  }

}


import java.io.FileInputStream
import java.util.Scanner
import scala.annotation.tailrec

object Main extends App {

  val sc = new Scanner(System.in)
//  val sc = new Scanner( new FileInputStream("src/input.txt") )

  val n,t,c = sc.nextInt
  val list = List.fill(n)(sc.nextInt)

  @tailrec
  def work(l: List[Int], res: List[List[Int]]): List[List[Int]] = {
    l match {
      case Nil =>
        res
      case xs =>
        val r = xs.span(_ <= t)
        if( r._1.size == 0 )
          work( r._2.dropWhile(_ > t), res )
        else
          work(r._2, r._1 :: res)
    }
  }

  val res = work(list, List.empty[List[Int]])
//  println(res)
  val ans = res.map(l => l.size - c + 1).filter(_>0).sum
  println(ans)
}

import java.util
import java.util.StringTokenizer

object _427B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val t = next.toInt
  val c = next.toInt
  val a = (1 to n).map(i => next.toInt)
  val queue = new util.ArrayDeque[Int]
  var ans = 0

  {
    var i = 0
    while(i < c) {
      while(!queue.isEmpty && a(queue.getLast) <= a(i)) queue.pollLast()
      queue.addLast(i)
      i += 1
    }
    if (a(queue.getFirst) <= t) ans += 1

    while(i < n) {
      while(!queue.isEmpty && a(queue.getLast) <= a(i)) queue.pollLast()
      queue.addLast(i)
      if (queue.getLast - queue.getFirst + 1 > c) queue.pollFirst()
      if (a(queue.getFirst) <= t) ans += 1

      i += 1
    }
  }
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val Array(n, t, c) = in.next().split(" ").map(_.toInt)
  val data = in.next().split(" ").map(_.toInt)
  val r = data.foldLeft(0, 0) {
    case ((soFar, l), el) if el > t => (soFar + (if (l >= c) l - c + 1 else 0), 0)
    case ((soFar, l), el) => (soFar, l + 1)
  }
  println(r._1 + (if (r._2 >= c) r._2 - c + 1 else 0))
}

object B427 {

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

  def main(args: Array[String]): Unit = {
    val Array(n, t, c) = readInts(3)
    val in = readInts(n)
    var res = 0
    var curr = 0
    var i = 0
    while(i < n) {
      if(in(i) > t) curr = 0
      else {
        curr += 1
        if(curr >= c)
          res += 1
      }
      i += 1
    }
    println(res)
  }

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

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

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

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

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

}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

object P427B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // N prisoners
  // C of prisoners to be transfered to another city
  // the severity of the crime
  // contiguous segment
  // crime level should not be greater then T

  def solve(): Int = {
    val N, T, C = sc.nextInt

    @tailrec
    def loop(acc: Int, p: Int, n: Int): Int = {
      val w = (p - C + 1) max 0
      if (n == N) acc + w
      else if (sc.nextInt > T) loop(acc + w, 0, n + 1)
      else loop(acc, p + 1, n + 1)
    }

    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.PriorityQueue
import scala.util.Random
import scala.util.control.Breaks._

object B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Long = {
    val N, T, C = sc.nextInt

    @tailrec
    def loop(acc: Long, i: Int, j: Int): Long = {

      @inline
      def ways(k: Int): Int = 0 max (k - C + 1)

      if (j == N) acc + ways(i)
      else if (sc.nextInt <= T) loop(acc, i + 1, j + 1)
      else loop(acc + ways(i), 0, j + 1)
    }

    loop(0, 0, 0)
  }

  out.println(solve)
  out.close
}

import scala.io.StdIn._

object _427_B extends App {
  val input = readLine().split(" ").map(_.toInt)
  val n = input(0)
  val t = input(1)
  val c = input(2)

  val prisoners = readLine().split(" ").map(_.toInt)

  var answer = 0
  var counter = 0
  for (i <- 0 until n) {
    if (prisoners(i) <= t) counter += 1
    else counter = 0

    if (counter == c) {
      answer += 1
      counter -= 1
    }
  }

  println(answer)
}

object Transfer extends App {
	val Array(n, t, c) = readLine.split(' ').map(_.toInt)
	val ok = readLine.split(' ').map(_.toInt).map(_ <= t)
	var (ans, i, j) = (0, 0, 0)
	while (i < n) {
		if (ok(i)) {
			j = i
			while (j < n && ok(j)) j += 1
			if (j - i >= c) ans += j - i - c + 1
			i = j
		} else i += 1
	}
	print(ans)
}

object B extends App {
  val sc = new java.util.Scanner(System.in)
  val n, t, c = sc.nextInt()
  val al = Array.fill(n)(sc.nextInt())
  def func(p:Int, ct:Int):List[Int] = {
    if (p == al.length) List[Int]()
    else al(p) match {
        case x if x >  t => 0 :: func(p+1, 0)
        case _ => ct+1 :: func(p+1, ct+1)
    }
  }
  println(func(0, 0).count(_ >= c))
}


import scala.io.StdIn._

object TaskB extends App {
  val l = readLine.takeRight(2).toInt
  val p = (1 :: Nil) :: (6 :: 2 :: 4 :: 8 :: Nil) :: (1 :: 3 :: 9 :: 7 :: Nil) :: (6 :: 4 :: Nil) :: Nil

  println(if (l == 0) 4 else (p.map(_.toArray).map(a => a(l % a.length)).sum) % 5)
}

import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 08.08.14.
 */
object B extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt

  def nextLong = in.nextLong

  def nextDouble = in.nextDouble

  def nextString = in.next

  def solve() = {
    val n = nextString
    if (n.takeRight(2).toInt % 4 == 0) {
      out.println(4)
    } else {
      out.println(0)
    }
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

import java.util.StringTokenizer

object _456B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val _1 = Array(1, 1, 1, 1)
  val _2 = Array(1, 2, 4, 3)
  val _3 = Array(1, 3, 4, 2)
  val _4 = Array(1, 4, 1, 4)

  val n = next.takeRight(2).toInt % 4
  val ans = (_1(n) + _2(n) + _3(n) + _4(n)) % 5
  println(ans)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val n = str.takeRight(2).toInt
  if (n % 4 == 0) println("4")
  else println("0")

}

object B456 {

  import IO._

  def powMod(a: Int, pow: Int, mod: Int): Int = {
    if(pow == 0L) 1
    else {
      val half = powMod(a, pow/2, mod)
      if(pow%2 == 0) {
        (half*half)%mod
      } else {
        (a * (half*half)%mod)%mod
      }
    }
  }

  def main(args: Array[String]): Unit = {
    var x = read.takeRight(2).toInt
    println((powMod(1, x%4, 5) + powMod(2, x%4, 5) + powMod(3, x%4, 5) + powMod(4, x%4, 5))%5)
  }

  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 Main {
  val cin = scala.io.Source.stdin.getLines()
  def main(args: Array[String]) = {
    println(if(BigInt(cin.next().takeRight(2).toInt) % 4 > 0) 0 else 4)
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    val ln = io.StdIn.readLine()
    print(if (Integer.parseInt(if (ln.length < 3) ln else ln.substring(ln.length - 2)) % 4 == 0) 4 else 0)
  }
}

import scala.io.StdIn._

object TaskB extends App {
  val l = readLine.last - '0'
  val p = (1 :: Nil) :: (6 :: 2 :: 4 :: 8 :: Nil) :: (1 :: 3 :: 9 :: 7 :: Nil) :: (6 :: 4 :: Nil) :: Nil

  println(if (l == 0) 4 else (p.map(_.toArray).map(a => a(l % a.length)).sum) % 5)
}


import scala.collection._
import scala.collection.mutable.TreeSet
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn._
import scala.util._

object z {
  def main(args: Array[String]): Unit = {
    val t = readInt()

    for (i <- 1 to t) {
      readLine()
      val line = readLine()

      val seen = Array.ofDim[Boolean](200)
      var lastchar = 0.toChar
      var done = false
      line.foreach(c => {
        if (c != lastchar) {
          seen(lastchar.toInt) = true;
        }

        if (seen(c) && !done) {
          println("NO")
          done = true
        }
        lastchar = c
      })

      if (!done) {
        println("YES")
      }
    }
  }
}

import sun.management.counter.Counter

import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.util.StringTokenizer
import scala.:+
import scala.+:
import scala.annotation.tailrec
import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.Source
import scala.io.StdIn.readLong
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine
import scala.util.Random

object Solution extends App {

  //=====Solution=========

  val lines = Source.fromInputStream(System.in).getLines()
  val writer = new PrintWriter(System.out)

  val testNumber = lines.next().toInt
  1.to(testNumber).foreach { _ =>
    val size = lines.next().toInt
    val string = lines.next()

    def findAnswer(index: Int, restrictedChars: Set[Char]): Boolean =
      if (index == size) true
      else if (restrictedChars.contains(string(index))) false
      else if (index + 1 < size && string(index + 1) != string(index)) findAnswer(index + 1, restrictedChars + string(index))
      else findAnswer(index + 1, restrictedChars)

    val answer = if (findAnswer(0, Set.empty)) "YES" else "NO"
    writer.append(StringBuilder.newBuilder.append(answer).append("\n"))
  }
  writer.close()

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

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


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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(l, r, m) = readLine().split(" ").map(_.toLong)

    val (p, q) = (m + l - r, m + r - l)

    (l to r).view.map(a => (q / a, a)).collectFirst {
      case (n, a) if n > 0 && n * a >= p && n * a <= q =>
        if (n * a - m < 0) (a, l + m - n * a, l)
        else (a, r + m - n * a, r)
    } match {
      case Some((a, b, c)) => println(s"$a $b $c")
      case None            => throw new Error("unexpeted exception")
    }
  }
}

object B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        var n = math.max(1, m / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else {
          n = math.max(1, (m + d) / a)
          if (a * n - d <= m && a * n >= m) {
            val c = r
            val b = m - a * n + c
            out.println(s"$a $b $c")
            a = r
          }
        }
        a += 1
      }
    }

    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 B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        val n = math.max(1, (m + (d + 1) / 2) / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else if (a * n - d <= m && a * n >= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        }
        a += 1
      }
    }

    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 B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        val n = math.max(1, m / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else if (a * n - d <= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        }
        a += 1
      }
    }

    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 B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      var n = math.max(1, m / a)
//            println(n)
      if (a * n <= m && a * n + d >= m) {
        val c = l
        val b = m - a * n + c
        out.println(s"$a $b $c")
      } else {
        //n += 1 //math.max(1, m / a)
        if (a * n - d <= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
        }
      }
    }

    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 B {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val l, r, m = nextLong
      val d = r - l
      var a = l
      while (a <= r) {
        val n = math.max(1, (m + d / 2) / a)
        if (a * n <= m && a * n + d >= m) {
          val c = l
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        } else if (a * n - d <= m && a * n >= m) {
          val c = r
          val b = m - a * n + c
          out.println(s"$a $b $c")
          a = r
        }
        a += 1
      }
    }

    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 B extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(l, r, m) = readLine().split(" ").map(_.toLong)

    val (p, q) = (m + l - r, m + r - l)

    (l to r).collectFirst {
      case a if q / a > 0 && q / a * a >= p && q / a * a <= q => (a, l, r)
    } match {
      case Some((a, b, c)) => println(s"$a $b $c")
      case None => throw new Error("unexpeted exception")
    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(l, r, m) = readLine().split(" ").map(_.toLong)

    val (p, q) = (m + l - r, m + r - l)

    (l to r).view.map(a => (q / a, a)).collectFirst {
      case (n, a) if n > 0 && n * a >= p && n * a <= q =>
        (a, l + m - n * a, l)
    } match {
      case Some((a, b, c)) => println(s"$a $b $c")
      case None            => throw new Error("unexpeted exception")
    }
  }
}


import scala.collection.mutable

object B extends App {
  val Array(n) = scala.io.StdIn.readLine().split(" ").map(_.toInt)

  val a = mutable.HashMap.empty[String, Int]
  (1 to n).foreach { i =>
    a += scala.io.StdIn.readLine() -> i
  }

  a.toSeq.sortBy(-_._2).foreach(q => println(q._1))
}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = (1 to n).map(_ => in.next()).reverse.distinct
  println(data.mkString("\n"))
}

/**
 * Created by AngrySCV on 18.03.16.
 * https://github.com/angrySCV
 * https://vk.com/angrySCV
 */

import scala.collection.mutable

object B extends App {
  val count = Console.in.readLine().toInt

  var hranilishe = mutable.HashMap[String, Int]()
  var globalCounter = 0
  (1 to count).foreach(item => {
    hranilishe.update(Console.in.readLine(), globalCounter)
    globalCounter += 1
  })
  hranilishe.toSeq.sortWith(_._2 > _._2).map(_._1).foreach(println)

}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.io.Codec

/**
  * @author itegulov
  */
object B extends App {

  import scala.collection.mutable.{Map => MMap}

  val in: Scanner = new Scanner(System.in)
  val out: PrintWriter = new PrintWriter(System.out)

  val n = in.nextInt()
  val map: MMap[String, Int] = MMap()

  for (i <- 1 to n) map(in.next()) = i

  val answer: List[String] = map.map(_.swap).toList.sortWith((a, b) => a._1 > b._1).map(_._2)

  for (name <- answer) {
    out.println(name)
  }

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine())
      .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

import java.io._
import java.nio.file._
import java.util.StringTokenizer

import scala.io.Codec

/**
  * @author itegulov
  */
object B extends App {

  import scala.collection.mutable.{Map => MMap}

  val in: Scanner = new Scanner(System.in)
  val out: PrintWriter = new PrintWriter(System.out)

  val n = in.nextInt()
  val map: MMap[String, Int] = MMap()

  for (i <- 1 to n) map(in.next()) = i

  map.map(_.swap).toList.sortWith((a, b) => a._1 > b._1).map(_._2).foreach(out.println)

  in.close()
  out.close()

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
    def this(reader: BufferedReader) = this(new LineNumberReader(reader))

    def this(reader: Reader) = this(new BufferedReader(reader))

    def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))

    def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))

    def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)

    def this(str: String) = this(new StringReader(str))

    private[this] val tokenizers = Iterator.continually(reader.readLine())
      .takeWhile(_ != null).map(new StringTokenizer(_)).filter(_.hasMoreTokens)
    private[this] var current: Option[StringTokenizer] = None

    @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
      current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
      current
    }

    /**
      * Unlike Java's scanner which returns till end of current line, this actually returns the next line
      *
      * @see line() if you want the Java behaviour
      */
    def nextLine(): String = {
      current = None // reset
      reader.readLine()
    }

    def lineNumber: Int = reader.getLineNumber

    def line(): String = tokenizer().get.nextToken("\n\r")

    def nextString(): String = next()

    def nextChar(): Char = next().ensuring(_.length == 1).head

    def nextBoolean(): Boolean = next().toBoolean

    def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)

    def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)

    def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)

    def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)

    def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)

    def nextFloat(): Float = next().toFloat

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

    def nextBigDecimal(): BigDecimal = BigDecimal(next())

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

    override def hasNext = tokenizer().nonEmpty

    override def close() = reader.close()
  }

}

/**
 * Created by AngrySCV on 18.03.16.
 * https://github.com/angrySCV
 * https://vk.com/angrySCV
 */

import scala.collection.mutable

object B extends App {
  val count = Console.in.readLine()
  val name = Console.in.readLine().split(" ")
  var hranilishe = mutable.HashMap[String, Int]()
  var globalCounter = 0
  name.foreach(item => {
    hranilishe.update(item, globalCounter)
    globalCounter += 1
  })
  hranilishe.toSeq.sortWith(_._2 > _._2).map(_._1).foreach(println)

}


//package codeforces.contest1244

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

      val total = io.StdIn.readInt()
      val stairs = io.StdIn.readLine()

      val leftmost = stairs.indexOf('1')
      val rightmost = stairs.lastIndexOf('1')

      println {
        if (leftmost != -1 && rightmost != -1)
          ((rightmost + 1) * 2) max (total - rightmost) * 2 max total max ((leftmost + 1) * 2) max (total - leftmost) * 2
        else total
      }
    }
  }

}

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

  val t = nextInt

  for (_ <- 1 to t) {
    val n = nextInt
    val s = nextLine
    val l = s.indexWhere(_ == '1')
    val r = s.lastIndexWhere(_ == '1')
    val res = if (l == -1) n
    else {
      val d = math.max(r + 1, n - l)
      val a = 2 * d
      val b = n + s.count(_ == '1')
      math.max(a, b)
    }
    out.println(res)
  }
  out.flush()

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


import scala.io.StdIn

object Main extends App {
  val t = StdIn.readLine().toInt
  for (_ <- 0 until t) {
    StdIn.readLine().toInt
    val a_max:Int = StdIn.readLine().split(" ").map(_.toInt).max
    StdIn.readLine().toInt
    val b_max:Int = StdIn.readLine().split(" ").map(_.toInt).max
    println(if (a_max >= b_max) "Alice" else "Bob")
    println(if (b_max >= a_max) "Bob" else "Alice")
  }
}

/*
https://codeforces.com/contest/1681/problem/A
 */
//package round_129

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

object task_A extends App {
    def solving(x: Array[Int], y: Array[Int]) = {
        val max_x = x.max
        val max_y = y.max
        if (max_x > max_y) {
            1
        }
        else if (max_x < max_y) {
            -1
        }
        else {
            0
        }
    }

    var sb = new StringBuilder()
    val t = StdIn.readLine().toInt
    for (i <- 0 until(t)) {
        val n = StdIn.readLine().toInt
        val a = StdIn.readLine().split(" ").map(_.toInt)
//        val a = Array(n)
//        for (ii <- 0 until(n)) a(ii) = StdIn.readLine().split(" ").toInt
        val m = StdIn.readLine().toInt
        val b = StdIn.readLine().split(" ").map(_.toInt)
//        val b = Array(m)
//        for (ii <- 0 until(m)) b(ii) = StdIn.readLine().toInt
        val ans = solving(a, b)
        if (ans == 1) {
//            println("Alice")
//            println("Alice")

            sb.append("Alice").append("\n").append("Alice").append("\n")
        }
        else if (ans == -1) {
//            println("Bob")
//            println("Bob")

            sb.append("Bob").append("\n").append("Bob").append("\n")
        }
        else {
//            println("Alice")
//            println("Bob")

            sb.append("Alice").append("\n").append("Bob").append("\n")

        }
    }

    print(sb)
}

/*
https://codeforces.com/contest/1681/problem/A
 */
//package round_129

import scala.io.StdIn

object task_A extends App {
    def solving(x: Array[Int], y: Array[Int]) = {
        val max_x = x.max
        val max_y = y.max
        if (max_x > max_y) {
            1
        }
        else if (max_x < max_y) {
            -1
        }
        else {
            0
        }
    }

    val t = StdIn.readLine().toInt
    for (i <- 0 until(t)) {
        val n = StdIn.readLine().toInt
        val a = StdIn.readLine().split(" ").map(_.toInt)
//        val a = Array(n)
//        for (ii <- 0 until(n)) a(ii) = StdIn.readLine().split(" ").toInt
        val m = StdIn.readLine().toInt
        val b = StdIn.readLine().split(" ").map(_.toInt)
//        val b = Array(m)
//        for (ii <- 0 until(m)) b(ii) = StdIn.readLine().toInt
        val ans = solving(a, b)
        if (ans == 1) {
            println("Alice")
            println("Alice")
        }
        else if (ans == -1) {
            println("Bob")
            println("Bob")
        }
        else {
            println("Alice")
            println("Bob")
        }

    }
}


object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    var rest = k
    for(i <- 1 to 2 * n by 2) {
      if (rest != 0 && a(i) - 1 > a(i - 1) && a(i) - 1 > a(i + 1)) {
        a(i) -= 1
        rest-= 1
      }
    }
    println(a.mkString(" "))
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val  temp = readLine.split(" ")
    val n = temp(0).toInt
    var k = temp(1).toInt
    val a = readLine.split(' ') map (_.toInt)
    assert(a.length == 2 * n + 1)

    for(i <- 0 to 2 * n) {
        if(k != 0 && i % 2 == 1 && a(i)-a(i-1) > 1 && a(i) - a(i+1) > 1) {
            a(i) -=1
            k -= 1
        }
        print(a(i) + " ")
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, k) = readLine().split(" ").map(_.toInt)
    val a = readLine().split(" ").map(_.toInt)
    var rest = k
    val tr = a.map{ i =>
      if (i > 0 && rest != 0) { rest -= 1; i - 1}
      else i
    }
    println(tr.mkString(" "))
  }
}


object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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
  }
}

object Workspace {
  import Main._
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val n = ni()
      val Ps = Array.fill[ArrayBuffer[Int]](n)(ArrayBuffer())
      REP(n) { _ =>
        val m, p = ni()
        Ps(m) += p
      }
      var pref = n
      var cnt = 0
      var ans = 0L
      val q = new java.util.PriorityQueue[Int]
      REP_r(n) { i =>
        pref -= Ps(i).length
        REP(Ps(i).length) { j =>
          q.add(Ps(i)(j))
        }
        val need = i - pref
        while(cnt < need) {
          cnt += 1
          ans += q.poll()
        }
      }
      out.println(ans)
    }
  }
}

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

  class InputReader(val stream: InputStream) {
    private[this] val reader = new BufferedReader(new InputStreamReader(stream), 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
  }
}

object Workspace {
  import Main._

  case class Voter(p: Int, m: Int)

  def sort(a: Array[Int]): Array[Int] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    java.util.Arrays.sort(a)
    a
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      import java.util.Comparator
      val n = ni()
      val V = Array.ofDim[Voter](n)
      REP(n) { i =>
        val m, p = ni()
        V(i) = Voter(p, m)
      }
      sort(V, new Comparator[Voter] {
        override def compare(o1: Voter, o2: Voter): Int = Integer.compare(o1.m, o2.m)
      })
      val inf = 1e18.toLong
      var cur, next = Array.ofDim[Long](n)
      var s = 0
      def process(i: Int): Unit = {
        debug(s"process($i)")
        import java.util
        util.Arrays.fill(next, inf)

        val len = i - s + 1
        val p = Array.ofDim[Int](len)
        REP(len) { j =>
          p(j) = V(s + j).p
        }
        Workspace.sort(p)
        val cum = cumSum(p)
        REP(len + 1) { j =>
          var k = 0
          while(k < n) {
            if (j == len || s + j + k >= V(i).m) {
              if (k + j < n) next(k) = min(next(k), cur(k + j) + cum(j))
            }
            k += 1
          }
        }

        debug(next)

        val t = cur
        cur = next
        next = t
        s = i + 1
      }

      REP(n) { i =>
        if (i > 0 && V(i).m != V(i - 1).m) {
          process(i - 1)
        }
      }
      process(n - 1)
      out.println(cur(0))
    }
  }
}