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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val from, to = Array.ofDim[Int](N - 1)
    REP(N - 1) { i =>
      from(i) = ni() - 1
      to(i) = i + 1
    }
    val S = na(N)
    val g = packUGraph(N, from, to)
    val (depth, parent, queue) = traceBfs(g)

    val INF = 1e6.toInt

    REP_r(N) { i =>
      val v = queue(i)
      if (depth(v) % 2 == 1) {
        // Sが決まっていない
        assert(S(v) == -1)

        // Sが決まっていない場合は、子供の中で一番小さいものに合わせる
        var ms = INF
        REP(g(v).length) { j =>
          val u = g(v)(j)
          if (parent(v) != u && S(u) != -1) {
            ms = min(ms, S(u))
          }
        }
        S(v) = if (ms == INF) -1 else ms
      }
    }

    val A = Array.ofDim[Int](N)
    REP(N) { i =>
      val v = queue(i)

      //登って行くときに未決定だったSをparentのものにする
      if (depth(v) % 2 == 1 && S(v) == -1) {
        S(v) = S(parent(v))
      }
      if (v == 0) A(v) = S(v)
      else A(v) = S(v) - S(parent(v))
    }

    if (A.exists(_ < 0)) {
      out.println(-1)
    } else {
      val ans = sumL(A)
      out.println(ans)
    }
  }

  /**
    * @param n ノード数
    */
  def packUGraph(n: Int, from: Array[Int], to: Array[Int]): Array[Array[Int]] = {
    val t = new Array[Array[Int]](n)
    val p = new Array[Int](n)
    val m = from.length
    REP(m)(i => p(from(i)) += 1)
    REP(m)(i => p(to(i)) += 1)
    REP(n)(i => t(i) = new Array(p(i)))
    REP(m) { i =>
      p(from(i)) -= 1
      t(from(i))(p(from(i))) = to(i)
      p(to(i)) -= 1
      t(to(i))(p(to(i))) = from(i)
    }
    t
  }

  /**
    * @return (depth, parent, queue)
    */
  def traceBfs(g: Array[Array[Int]], rt: Int = 0): (Array[Int], Array[Int], Array[Int]) = {
    val n = g.length
    val INF = 1e9.toInt + 10
    val q, p = Array.ofDim[Int](n)
    q(0) = rt
    p(rt) = -1
    val d = Array.fill[Int](n)(INF)
    d(rt) = 0
    var cur = 0
    var last = 1
    while (cur < last) {
      val v = q(cur)
      REP(g(v).length) { i =>
        val u = g(v)(i)
        if (d(u) == INF) {
          d(u) = d(v) + 1
          p(u) = v
          q(last) = u
          last += 1
        }
      }
      cur += 1
    }
    (d, p, q)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

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

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

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.t6)
    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
//        ver.vv = 0
        val vv = if (ver.children != Nil) ver.children.map(_.sum).min - sum else 0
        if (vv < 0 ) possible = false
        ver.vv = vv
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Long = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(x => debug(x+""))

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Long) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""

val t6 = """
5
1 2 2 3
1 -1 2 3 -1
""" //3
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    runTest(Test.t6)
    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
//        ver.vv = 0
        val vv = if (ver.children != Nil) ver.children.map(_.sum).min - sum else 0
        if (vv < 0 ) possible = false
        ver.vv = vv
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Int = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(x => debug(x+""))

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""

val t6 = """
5
1 2 2 3
1 -1 2 3 -1
""" //3
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
//    runTest(Test.sa1)
//    debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
        ver.vv = 0
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Int = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(x => debug(x+""))

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""
}

}

import java.util.ArrayList
import java.util.StringTokenizer
//import scala.reflect.io.File
import java.io.BufferedReader
import java.io.BufferedInputStream
import java.io.InputStreamReader
import java.io.ByteArrayInputStream
import java.io.InputStream

object CF_530_D {   var br = createBufferedReader(); var debugV = false

    //COMMENT ME !
    //runTest(Test.sa1)
    //debugV = true
//    runFromFile("""C:\work\git\ap-codeforces\Codeforces\src\fb\aprokh\fb2018r2\jacks_candy_shop_2.txt""")

  def main(args: Array[String]): Unit = {
    //---------------------------- parameters reading
    val n = readLine.int
    class Vert(val ind: Int) {
      var vv = -1
      var sum = -1
      var children = List[Vert]()
      var parent = -1
      override def toString() = s"$ind, $vv, $sum, p=$parent"
    }
    val verts = new Array[Vert](n+1)
    val pLine = readLine
    verts(1) = new Vert(1)
    for (i <- 2 to n) {
      verts(i) = new Vert(i)
      verts(i).parent = pLine.int
    }
    val sLine = readLine
    for (i <- 1 to n) {
      if (verts(i).parent > 0)
        verts(verts(i).parent).children ::= verts(i)
      verts(i).sum = sLine.int
    }

    var possible = true
    def mark(ver: Vert, sum: Int): Unit = {
      if (ver.sum == -1) {
        ver.vv = 0
      } else {
        if (ver.sum < sum) possible = false
        ver.vv = ver.sum - sum
      }
      ver.children.foreach(ch => mark(ch, sum + ver.vv))
    }
    mark(verts(1), 0)

    def sum(ver: Vert): Int = {
      ver.vv + ver.children.map(sum(_)).sum
    }

    val res = if (possible) sum(verts(1)) else -1

    verts.foreach(println)

    debug("n = " + n)

    //---------------------------- parameters reading :end

    outLn(res)

    debug("================= RESULT ================== ")
    finish
  }

  //============================ service code ======================

//  var file:File = null
  val resultStr = new StringBuilder
  def outLn(str:String) = resultStr.append(str).append("\n")
  def outLn(number:Integer) = resultStr.append(number+"").append("\n")
  def finish() {
//    if (file == null || !devEnv) {
      println(resultStr.toString())
      Console.flush()
//    } else {
//      file.writeAll(resultStr.toString())
//    }
  }

  def readLine() = new Line
  class Line {
    val fullLine = br.readLine()
    val tok = new StringTokenizer(fullLine, " ")
    def int = tok.nextToken().toInt
    def long = tok.nextToken().toLong
    def double = tok.nextToken().toDouble
    def string = tok.nextToken()
  }

  def createBufferedReader(inst:InputStream = System.in): BufferedReader = {
    val bis = if (inst == null) new BufferedInputStream(System.in) else new BufferedInputStream(inst);
    new BufferedReader(new InputStreamReader(bis));
  }

  def runTest(str:String) = if (devEnv) {
    br = createBufferedReader(new ByteArrayInputStream(str.trim.getBytes("ISO-8859-1")))
  }

//  def runFromFile(fileName: String) = if (devEnv) {
//    br = createBufferedReader(new FileInputStream(fileName))
//  }

  def debug(x: => String) = if (debugV && devEnv) println(x) // nullary function

  lazy val devEnv = this.getClass.getCanonicalName.contains(".")

//============================================================================================
object Test {

val sa1 = """
5
1 1 1 1
1 -1 -1 -1 -1
"""

val sa2 = """
5
1 2 3 1
1 -1 2 -1 -1
"""

val sa3 = """
3
1 2
2 -1 1
"""
}

}


import scala.collection.mutable

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  //val counts = Array.fill(bs.max + 1) { 0 }
  //for (b <- bs) counts(b) += 1
  val counts = bs.groupBy(identity).map {
    case (k, v) => k -> v.length
  }

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

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

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    val C = Array.ofDim[Int](N + 1)
    REP(N) { i =>
      C(A(i)) += 1
    }

    def validate: Option[Array[mutable.Queue[Int]]] = {
      var id = 1
      val res = Array.fill[mutable.Queue[Int]](N)(mutable.Queue())

      REP(N + 1) { i =>
        if (C(i) > 0) {
          val cnt = N - i
          if (C(i) < cnt || cnt == 0) return None
          else {
            REP(C(i) / cnt) { d =>
              REP(cnt) { _ => res(i) += id }
              id += 1
            }
          }
        }
      }
      Some(res)
    }

    def mkAns(groups: Array[mutable.Queue[Int]]): Option[Array[Int]] = {
      val ans = Array.ofDim[Int](N)
      REP(N) { i =>
        if (groups(A(i)).isEmpty) return None
        else ans(i) = groups(A(i)).dequeue()
      }
      Some(ans)
    }

    validate match {
      case None => out.println("Impossible")
      case Some(groups) =>
        mkAns(groups) match {
          case None =>
            out.println("Impossible")

          case Some(ans) =>
            out.println("Possible")
            out.println(ans.mkString(" "))
        }
    }
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

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

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

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

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

import scala.collection.mutable

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  //val counts = Array.fill(bs.max + 1) { 0 }
  //for (b <- bs) counts(b) += 1
  val counts = new mutable.ArrayOps.ofInt(bs).groupBy(identity).map {
    case (k, v) => k -> v.length
  }

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

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

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}

import scala.collection.mutable.ArrayBuffer

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  val counts = bs.groupBy(identity).map {
    case (k, v) => k -> v.size
  }

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

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

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}

object B extends App {

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

  val Array(n) = readInts(1)
  val as0 = readInts(n)
  val as = as0.zipWithIndex.sortBy(_._1)
  val bs = Array.fill(n)(0)

  var h = 1
  var i = 0
  var bad = false
  while (i < n) {
    val add = n - as(i)._1
    var added = 0
    while (added < add && i < n) {
      bs(as(i)._2) = h
      if (n - as(i)._1 != add) bad = true
      added += 1
      i += 1
    }
    h += 1
  }

  if (bs.contains(0)) bad = true

  val counts = Array.fill(bs.max + 1) { 0 }
  for (b <- bs) counts(b) += 1

  for (i <- bs.indices) {
    if (as0(i) != n - counts(bs(i))) bad = true
  }

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

  if (bad) println("Impossible")
  else {
    println("Possible")
    println(bs.mkString(" "))
  }

  Console.flush
}


object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

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

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

  Console.flush
}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  Console.setOut(new java.io.PrintStream(Console.out, false))

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

  Console.flush
}

object Solution extends App {

  val in = scala.io.Source.stdin.getLines()
  val Array(n, m) = in.next().split(' ').map(_.toInt)
  val a: Array[Long] = in.next().split(' ').map(_.toLong)
  var y = 0l
  val result = (1 to m).foldLeft(List.empty[Long]) {
    case (list, _) =>
    val data = in.next().split(' ').map(_.toInt).toList
    data match {
      case (1 :: v :: x :: Nil) =>
        a(v - 1) = x - y
        list
      case (2 :: y1 :: Nil) =>
        y += y1
        list
      case (3 :: v :: Nil) =>
        (a(v - 1) + y) :: list
    }
  }
  println(result.reverse.mkString("\n"))
}

import java.util.Scanner
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.PrintWriter
import java.lang.Long.bitCount
import java.nio.CharBuffer
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
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 Stub extends App {
  // val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  object Input {
    import java.lang.Character._

    lazy val in = new BufferedReader(new InputStreamReader(java.lang.System.in))
    var buf: Array[Char] = Array()
    var pos: Int = 0

    def next(): String = {
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      while (isWhitespace(buf(pos))) {
        pos += 1
      }
      while (pos == buf.length) {
        buf = in.readLine.toArray
        pos = 0
      }
      val s = pos
      while (pos < buf.length && !isWhitespace(buf(pos))) {
        pos += 1
      }
      new java.lang.String(buf, s, pos - s)
    }

    def nextInt(): Int = next.toInt

    def nextLong(): Long = next.toLong

    def nextFloat(): Float = next.toFloat

    def nextDouble(): Double = next.toDouble

    val nextString: () => String = next _
  }

  import Input._

  def solve(): Unit = {
    val N, M = nextInt
    val A: Array[Long] = Array.fill(N)(nextLong)

    var sumY = 0L
    var i = 0
    while (i < M) {
      (nextInt: @switch) match {
        case 1 =>
          val v = nextInt - 1
          val x = nextLong - sumY
          A(v) = x
        case 2 =>
          val y = nextLong
          sumY += y
        case 3 =>
          val q = nextInt - 1
          out.println(A(q) + sumY)
      }
      i += 1
    }
  }

  solve
  out.flush
}

object Main {
  def readLineOfNums(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  val result = new StringBuilder()
  def performCommand(array: Array[Long], sum: Long) = {
    val cmd = readLineOfNumsI()
    cmd(0) match {
      case 1 =>
        array(cmd(1)-1) = cmd(2) - sum
        sum
      case 2 =>
        sum + cmd(1)
      case 3 =>
        result.append(array(cmd(1)-1) + sum).append("\n")
        sum
    }
  }
  def main(args: Array[String]) = {
    val Array(n, m) = readLineOfNumsI()
    val array = readLineOfNums()
    var sum: Long = 0
    for (i <- 1 to m)
      sum = performCommand(array, sum)
    print(result)
  }
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val Array(n, m) = readInts
  val as = readInts
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val op = readInts
    op(0) match {
      case 1 => as(op(1) - 1) = op(2) - delta
      case 2 => delta += op(1)
      case 3 => println(as(op(1) - 1) + delta)
    }
  }

}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  Console.withOut(new java.io.BufferedOutputStream(Console.out)) {
  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }
Console.flush
}
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)
  def readLongs = readString.split(" ").map(_.toLong)

  val Array(n, m) = readInts
  val as = readLongs
  var delta = 0L

  var t = 0
  while (t < m) {
    t += 1
    val op = readInts
    op(0) match {
      case 1 => as(op(1) - 1) = op(2) - delta
      case 2 => delta += op(1)
      case 3 => println(as(op(1) - 1) + delta)
    }
  }

}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  def buffered(thunk: => Unit) =
    Console.withOut(new java.io.BufferedOutputStream(Console.out)) {
      thunk
	  Console.flush
    }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  buffered {
  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }
  }
}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

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

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

  Console.flush
}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  Console.withOut(new java.io.BufferedOutputStream(Console.out)) {
  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(i - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }
}
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.annotation.unchecked
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 P315B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // N integers
  // array A = A_1, ..., A_n
  // M operations
  // * A_(V_i) = X_i
  // * Increase each A_i by Y_i ... A_i = A_i + Y_i
  // * A_(Q_i)

  def solve(): Unit = {
    val N, M = sc.nextInt
    val A: Array[Long] = Array.fill(N)(sc.nextLong)

    var sumY = 0
    0 until M foreach { i =>
      sc.nextInt match {
        case 1 =>
          val v, x = sc.nextInt
          A(v - 1) = x
        case 2 =>
          sumY += sc.nextInt
        case 3 =>
          out.println(A(sc.nextInt  - 1) + sumY)
      }
    }
  }

  solve
  out.close
}

object B extends App {

  val scan = new java.util.Scanner(Console.in)

  val (n, m) = (scan.nextInt, scan.nextInt)
  val as = Array.fill(n)(scan.nextInt)
  var delta = 0
println(util.Properties.versionString)
  var t = 0
  while (t < m) {
    t += 1
    scan.nextInt match {
      case 1 => as(scan.nextInt - 1) = scan.nextInt - delta
      case 2 => delta += scan.nextInt
      case 3 => println(as(scan.nextInt - 1) + delta)
    }
  }

}

object B extends App {

  def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val Array(n, m) = readInts(2)
  val as = readInts(n)
  var delta = 0

  var t = 0
  while (t < m) {
    t += 1
    val st = tokenizeLine
    st.nextToken.toInt match {
      case 1 => val i = st.nextToken.toInt; as(t - 1) = st.nextToken.toInt - delta
      case 2 => delta += st.nextToken.toInt
      case 3 => println(as(st.nextToken.toInt - 1) + delta)
    }
  }

}


import scala.collection.mutable.ArrayBuffer

object A extends App {
  import java.io._
  import java.nio.file.{Files, Path}
  import java.util.StringTokenizer
  import scala.io.Source
  import scala.io.Codec

  /* Implicit methods */
  implicit def intWithTimes(n: Int) = {
    new {
      def times(f: => Unit): Unit = 1.to(n).foreach { _ => f }
    }
  }
  /* Implicit methods */

  //  val in = new CustomScanner(Source.fromResource("input.txt").mkString)
  val in  = new CustomScanner(System.in)
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val inputLines = in.nextInt()

    inputLines.times {
      val a = in.nextInt()
      val b = in.nextInt()
      val r = math.abs(a - b)

      if (r % 10 == 0) {
        println(r / 10)
      } else {
        println(1 + (r / 10))
      }
    }
  }

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

  /**
    * Util methods
    */

  def printArr[T](in: Array[T]) = {
    in.foreach(print)
    println()
  }

  /**
    * Scala implementation of a faster java.util.Scanner
    * See: http://codeforces.com/blog/entry/7018
    */
  class CustomScanner(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 nextLineInt(n: Int): ArrayBuffer[Int] = {
      var data = ArrayBuffer[Int]()
      n.times({
        data += nextInt()
      })
      data
    }

    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(): String = tokenizer().get.nextToken()

    override def hasNext: Boolean = tokenizer().nonEmpty

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

object CodeforcesRound667a {

  import java.io.{BufferedReader, PrintStream}

  import scala.io.Source

  def main(args: Array[String]): Unit = {
    exec(Source.stdin.bufferedReader, System.out)
  }

  def exec(implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val t: Int = rl_int
    (1 to t).foreach(_ => test())
  }

  def test()
          (implicit
           reader: BufferedReader,
           writer: PrintStream): Unit = {
    val Array(a, b) = rll_int
    val diff = Math.abs(b - a)
    val res = diff / 10 + (if (diff % 10 > 0) 1 else 0)
    writer.println(res)
  }

  def sqr(a: Long): Long = a * a

  def rl(implicit reader: BufferedReader): String = reader.readLine
  def rll(implicit reader: BufferedReader): Array[String] = reader.readLine.split(' ')

  def rl_bool(implicit reader: BufferedReader): Boolean = rl.toBoolean
  def rl_byte(implicit reader: BufferedReader): Byte = rl.toByte
  def rl_short(implicit reader: BufferedReader): Short = rl.toShort
  def rl_int(implicit reader: BufferedReader): Int = rl.toInt
  def rl_long(implicit reader: BufferedReader): Long = rl.toLong
  def rl_float(implicit reader: BufferedReader): Float = rl.toFloat
  def rl_double(implicit reader: BufferedReader): Double = rl.toDouble

  def rll_bool(implicit reader: BufferedReader): Array[Boolean] = rll.map(_.toBoolean)
  def rll_byte(implicit reader: BufferedReader): Array[Byte] = rll.map(_.toByte)
  def rll_short(implicit reader: BufferedReader): Array[Short] = rll.map(_.toShort)
  def rll_int(implicit reader: BufferedReader): Array[Int] = rll.map(_.toInt)
  def rll_long(implicit reader: BufferedReader): Array[Long] = rll.map(_.toLong)
  def rll_float(implicit reader: BufferedReader): Array[Float] = rll.map(_.toFloat)
  def rll_double(implicit reader: BufferedReader): Array[Double] = rll.map(_.toDouble)

}

//package codeforces.contests._1409

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

      val Array(a, b) = io.StdIn.readLine.split(" ").map(_.toInt)
      println {
        val d = (a - b).abs

        if (d % 10 == 0) d / 10 else d / 10 + 1
      }
    }
  }
}

/**
 * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
 */
import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    // Write your solution here
    /*
    int t;
    cin >> t;
    while (t--) {
      int a, b;
      cin >> a >> b;
      cout << (abs(a - b) + 9) / 10 << endl;
    }

    return 0;
    */
    val t = readInt

    for (_ <- 0 until t) {
      val splitLine = readLine.split(" ")
      val a = splitLine(0).toInt
      val b = splitLine(1).toInt

      println((math.abs(a - b) + 9) / 10)
    }
  }
}

/**
 * Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
 */
import scala.io.StdIn._

object Main {
  def main(args: Array[String]): Unit = {
    // Write your solution here
    val t = readInt

    for (_ <- 0 until t) {
      val splitLine = readLine.split(" ").map(_.toInt)
      val a = splitLine(0)
      val b = splitLine(1)

      println((math.abs(a - b) + 9) / 10)
    }
  }
}

object Solution {
  def main(args: Array[String]): Unit = {
    import scala.io.StdIn
    val t = StdIn.readLine.toInt
    for (_ <- 0 until t) {
      val arr = StdIn.readLine.split(" ").map(_.toInt)
      val res = ((arr.max - arr.min).abs + 9) / 10
      println(res)

    }
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val Array(a, b) = readLine().split(" ").map(_.toInt)
    val c           = (a - b).abs

    val ans = c / 10 + (if (c % 10 == 0) 0 else 1)

    println(ans)
  }
}


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

object Main {
    def main(args: Array[String]) = {
        val cin = new BufferedReader(new InputStreamReader(System.in))
        val T = cin.readLine.toInt
        for (t <- 1 to T) {
            val n::k::Nil = cin.readLine.split(" ").map(_.toInt).toList
            val l = (k+1)/2
            println(n-l)
            for (x <- l to n)
			    if (x != k)
				    print(x+" ")
	        println() } } }

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

object AAntiKnapsack {
  def solve(n: Int, k: Int): (Int, String) = {
    val higher = (1 to n).dropWhile(_ <= k)
    val res = (Math.ceil(k.toFloat / 2).toInt until k) ++ higher
    (res.length, res.mkString("", " ", ""))
  }

  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//    "3\n3 2\n5 3\n1 1".getBytes)))
    //              "1\n3\n0 0 3".getBytes)))
    val inputs = file.readLine.toInt
    var i = 0
    while (i < inputs) {
      val n::k::Nil = file.readLine.split(" ").map(_.toInt).toList
      solve(n, k).productIterator.foreach(println)
      i += 1
    }
  }
}


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 private final 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[Long]]): 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 private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

  @inline private final 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 }
  }
  @inline private final def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  @inline private final def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならfinalはずせ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    val dp = Array.ofDim[Int](2, 1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val c = cols(i)
      val x = i&1
      Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)
      REP(n) { roll =>
        Array.copy(dp(x), 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j + roll) % n
          var s = 0
          while(s < tmp.length) {
            if ((s >> j & 1) == 0) {
              val ns = 1 << j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))
            }
            s += 1
          }
        }
        REP(tmp.length) { s =>
          dp(x^1)(s) = max(dp(x^1)(s), tmp(s))
        }
      }
    }

    val ans = dp(cols.length&1)((1<<n) - 1)
    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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    val dp = Array.ofDim[Int](2, 1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val c = cols(i)
      val x = i&1
      Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)
      REP(n) { roll =>
        Array.copy(dp(x), 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j+roll) % n
          REP(1 << n) { s =>
            if ((s>>j&1) == 0) {
              val ns = 1<<j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))
            }
          }
        }
        REP(tmp.length) { s =>
          dp(x^1)(s) = max(dp(x^1)(s), tmp(s))
        }
      }
    }

    val ans = dp(cols.length&1)((1<<n) - 1)
    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 def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline private def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private 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 private def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

    @inline private[this] 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))
  }

  @inline private def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならfinalはずせ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    val dp = Array.ofDim[Int](2, 1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val c = cols(i)
      val x = i&1
      Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)
      REP(n) { roll =>
        Array.copy(dp(x), 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j + roll) % n
          REP(tmp.length) { s =>
            if ((s >> j & 1) == 0) {
              val ns = 1 << j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))
            }
          }
        }
        REP(tmp.length) { s =>
          dp(x^1)(s) = max(dp(x^1)(s), tmp(s))
        }
      }
    }

    val ans = dp(cols.length&1)((1<<n) - 1)
    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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    var cur, next = Array.ofDim[Int](1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      Array.copy(cur, 0, next, 0, cur.length)
      REP(n) { roll =>
        Array.copy(cur, 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j+roll) % n
          REP(1 << n) { s =>
            if ((s>>j&1) == 0) {
              val ns = 1<<j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(cols(i)))
              next(ns) = max(next(ns), tmp(ns))
            }
          }
        }
      }
      val t = cur
      cur = next
      next = t
    }

    val ans = cur((1<<n) - 1)
    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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    val dp = Array.ofDim[Int](2, 1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val c = cols(i)
      val x = i&1
      Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)
      REP(n) { roll =>
        Array.copy(dp(x), 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j+roll) % n
          var s =0
          while(s < tmp.length) {
            if ((s>>j&1) == 0) {
              val ns = 1<<j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))
            }
            s += 1
          }
        }
        REP(tmp.length) { s =>
          dp(x^1)(s) = max(dp(x^1)(s), tmp(s))
        }
      }
    }

    val ans = dp(cols.length&1)((1<<n) - 1)
    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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    var cur, next = Array.ofDim[Int](1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val c = cols(i)
      Array.copy(cur, 0, next, 0, cur.length)
      REP(n) { roll =>
        Array.copy(cur, 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j+roll) % n
          REP(1 << n) { s =>
            if ((s>>j&1) == 0) {
              val ns = 1<<j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))
            }
          }
        }
        REP(tmp.length) { s =>
          next(s) = max(next(s), tmp(s))
        }
      }
      val t = cur
      cur = next
      next = t
    }

    val ans = cur((1<<n) - 1)
    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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    var cur, next = Array.ofDim[Int](1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      Array.copy(cur, 0, next, 0, cur.length)
      REP(n) { roll =>
        Array.copy(cur, 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j+roll) % n
          REP(1 << n) { s =>
            if ((s>>j&1) == 0) {
              val ns = 1<<j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(cols(i)))
            }
          }
        }
        REP(tmp.length) { s =>
          next(s) = max(next(s), tmp(s))
        }
      }
      val t = cur
      cur = next
      next = t
    }

    val ans = cur((1<<n) - 1)
    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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    val dp = Array.ofDim[Int](2, 1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val c = cols(i)
      val x = i&1
      Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)
      REP(n) { roll =>
        Array.copy(dp(x), 0, tmp, 0, tmp.length)
        var j = 0
        while(j < n) {
          val pos = (j+roll) % n
          REP(1 << n) { s =>
            if ((s>>j&1) == 0) {
              val ns = 1<<j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))
            }
          }
          j += 1
        }
        REP(tmp.length) { s =>
          dp(x^1)(s) = max(dp(x^1)(s), tmp(s))
        }
      }
    }

    val ans = dp(cols.length&1)((1<<n) - 1)
    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 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 private final 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[Long]]): 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 private final def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

  @inline private final 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 }
  }
  @inline private final def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  @inline private final def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならfinalはずせ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    val dp = Array.ofDim[Int](2, 1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val c = cols(i)
      val x = i&1
      Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)
      REP(n) { roll =>
        Array.copy(dp(x), 0, tmp, 0, tmp.length)
        REP(n) { j =>
          val pos = (j + roll) % n
          REP(tmp.length) { s =>
            if ((s >> j & 1) == 0) {
              val ns = 1 << j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g(pos)(c))
            }
          }
        }
        REP(tmp.length) { s =>
          dp(x^1)(s) = max(dp(x^1)(s), tmp(s))
        }
      }
    }

    val ans = dp(cols.length&1)((1<<n) - 1)
    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 val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from) { i =>
      f(i)
    }
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

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

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

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      solve2()
    }
  }

  def solve2(): Unit = {
    val n, m = ni()
    val g = nm(n, m)
    val colMx = Array.ofDim[Int](m)
    REP(n) { i =>
      REP(m) { j =>
        colMx(j) = max(colMx(j), g(i)(j))
      }
    }
    val cols = colMx.zipWithIndex.sortBy(_._1).takeRight(n).map(_._2)
    debug(cols)
    val dp = Array.ofDim[Int](2, 1 << n)
    val tmp = Array.ofDim[Int](1 << n)
    REP(cols.length) { i =>
      val x = i&1
      Array.copy(dp(x), 0, dp(x^1), 0, dp(x).length)
      REP(n) { roll =>
        Array.copy(dp(x), 0, tmp, 0, tmp.length)
        REP(n) { j =>
          REP(1 << n) { s =>
            if ((s>>j&1) == 0) {
              val ns = 1<<j | s
              tmp(ns) = max(tmp(ns), tmp(s) + g((j+roll)%n)(cols(i)))
              dp(x^1)(ns) = max(dp(x^1)(ns), tmp(ns))
            }
          }
        }
      }
      debug(dp(x^1))
    }

    val ans = dp(n&1)((1<<n) - 1)
    out.println(ans)
  }
}


object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(in.next().split(" ").zipWithIndex.foldLeft((0, 0)) {
    case(acc, ("0", i)) => acc
    case((0, 0), ("1", i)) => (1, i)
    case((count, previous), ("1", i)) if i - previous == 1 => (count + 1, i)
    case((count, previoius), ("1", i)) => (count + 2, i)
  }._1)

}

import scala.io.StdIn

/** B. Inbox (100500)
  * http://codeforces.com/problemset/problem/465/B
  * @author Yuichiroh Matsubayashi
  *         Created on 15/01/19.
  */
object P465B extends App{
  val n = StdIn.readInt()
  val read = StdIn.readLine().split("0").map(_.filter(_ == '1')).filter(_ != "")

  def solution = (read.map(sec => sec.size + 1).sum - 1) max 0

  println(solution)

}

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

/**
 * Created by arseny on 07.09.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 = nextInt
    val es = Array.fill(n)(0)
    for(i <- 0 until n) {
      es(i) = nextInt
    }
    def nClicks(es: Array[Int]): List[Int] = {
      if(es.length == 0) {
        Nil
      } else {
        val (first, rest) = es.dropWhile(_ == 0).span(_ == 1)
        first.length :: nClicks(rest)
      }
    }
    val ones = nClicks(es).filterNot(_ == 0)
    out.print(math.max(ones.sum + ones.length - 1, 0))
  }

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

import java.util.StringTokenizer

object _465B 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)

  def doit(i: Int, pre: Int, acc: Int): Int = {
    if (i == n) acc
    else if (a(i) == 0) doit(i + 1, pre, acc)
    else {
      if (pre == -1) doit(i + 1, i, acc + 1)
      else {
        if (pre + 1 == i) doit(i + 1, i, acc + 1)
        else doit(i + 1, i, acc + 2)
      }
    }
  }

  println(doit(0, -1, 0))
}

object B465 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n).zipWithIndex.filter(_._1 == 1).map(_._2)
    var res = if(in.isEmpty) 0 else 1
    for(i <- 1 until in.length) {
      if(in(i-1)+1 == in(i)) {
        res +=1
      } else {
        res += 2
      }
    }
    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.io.InputStreamReader
import java.io.BufferedReader

/**
 * @author pvasilyev
 * @since 19 May 2016
 */
object B465 extends App {

  def solve(): Any = {
    val reader = new BufferedReader(new InputStreamReader(System.in))
    val n = reader.readLine().toInt
    val seq = reader.readLine().split(" ").map(_.toInt)
    val index = seq.lastIndexWhere(_ != 0)
    println(seq.take(index + 1).foldLeft((0, 0))((y: (Int, Int), x: Int) => {
      if (y._2 == 0 && x == 0) {
        // do nothing
        y
      } else if (y._2 == 0 && x == 1) {
        (y._1 + 1, 1)
      } else if (y._2 == 1 && x == 0) {
        (y._1 + 1, 0)
      } else {
        (y._1 + 1, 1)
      }
    })._1)
  }

  solve()

}

import scala.io.StdIn

/** B. Inbox (100500)
  * http://codeforces.com/problemset/problem/465/B
  * @author Yuichiroh Matsubayashi
  *         Created on 15/01/19.
  */
object P465B extends App{
  val n = StdIn.readInt()
  val read = StdIn.readLine().split("0").map(_.filter(_ == '1')).filter(_ != "")

  println(read.toSeq)
  def solution = (read.map(sec => sec.size + 1).sum - 1) max 0

  println(solution)

}