This is a harder version of the problem. The difference is only in constraints.You are given a rectangular $$$n \times m$$$ matrix $$$a$$$. In one move you can choose any column and cyclically shift elements in this column. You can perform this operation as many times as you want (possibly zero). You can perform this operation to a column multiple times.After you are done with cyclical shifts, you compute for every row the maximal value in it. Suppose that for $$$i$$$-th row it is equal $$$r_i$$$. What is the maximal possible value of $$$r_1+r_2+\ldots+r_n$$$?

The first line contains an integer $$$t$$$ ($$$1 \le t \le 40$$$), the number of test cases in the input. The first line of each test case contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 12$$$, $$$1 \le m \le 2000$$$) — the number of rows and the number of columns in the given matrix $$$a$$$.  Each of the following $$$n$$$ lines contains $$$m$$$ integers, the elements of $$$a$$$ ($$$1 \le a_{i, j} \le 10^5$$$).

Print $$$t$$$ integers: answers for all test cases in the order they are given in the input.

NoteIn the first test case you can shift the third column down by one, this way there will be $$$r_1 = 5$$$ and $$$r_2 = 7$$$.In the second case you can don't rotate anything at all, this way there will be $$$r_1 = r_2 = 10$$$ and $$$r_3 = 9$$$.

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


Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows the content of a read letter nothing happens). In one click he can do any of the following operations: Move from the list of letters to the content of any single letter. Return to the list of letters from single letter viewing mode. In single letter viewing mode, move to the next or to the previous letter in the list. You cannot move from the first letter to the previous one or from the last letter to the next one.The program cannot delete the letters from the list or rearrange them.Alexey wants to read all the unread letters and go watch football. Now he is viewing the list of all letters and for each letter he can see if it is read or unread. What minimum number of operations does Alexey need to perform to read all unread letters?

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of letters in the mailbox. The second line contains n space-separated integers (zeros and ones) — the state of the letter list. The i-th number equals either 1, if the i-th number is unread, or 0, if the i-th letter is read.

Print a single number — the minimum number of operations needed to make all the letters read.

NoteIn the first sample Alexey needs three operations to cope with the task: open the second letter, move to the third one, move to the fourth one.In the second sample the action plan: open the first letter, move to the second letter, return to the list, open the fifth letter.In the third sample all letters are already read.

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

}

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)

}


Numbers $$$1, 2, 3, \dots n$$$ (each integer from $$$1$$$ to $$$n$$$ once) are written on a board. In one operation you can erase any two numbers $$$a$$$ and $$$b$$$ from the board and write one integer $$$\frac{a + b}{2}$$$ rounded up instead.You should perform the given operation $$$n - 1$$$ times and make the resulting number that will be left on the board as small as possible. For example, if $$$n = 4$$$, the following course of action is optimal:  choose $$$a = 4$$$ and $$$b = 2$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3, 3]$$$;  choose $$$a = 3$$$ and $$$b = 3$$$, so the new number is $$$3$$$, and the whiteboard contains $$$[1, 3]$$$;  choose $$$a = 1$$$ and $$$b = 3$$$, so the new number is $$$2$$$, and the whiteboard contains $$$[2]$$$. It's easy to see that after $$$n - 1$$$ operations, there will be left only one number. Your goal is to minimize it.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The only line of each test case contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of integers written on the board initially. It's guaranteed that the total sum of $$$n$$$ over test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, in the first line, print the minimum possible number left on the board after $$$n - 1$$$ operations. Each of the next $$$n - 1$$$ lines should contain two integers — numbers $$$a$$$ and $$$b$$$ chosen and erased in each operation.

import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println("2")
    printf(s"$n ${n-1}\n");
    for (i <- n to 3 by -1) {
      printf(s"$i ${i - 2}\n")
    }
  }
}

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val res = new StringBuilder
      val even, odd = mutable.PriorityQueue.empty[Int]
      for (i <- 1 to n) {
        if (i % 2 == 0) even.enqueue(i)
        else odd.enqueue(i)
      }

      while (even.size > 1 || odd.size > 1) {
        if (even.size > 1 && odd.size > 1) {
          val aE, bE = even.dequeue()
          val cE = (aE + bE) / 2
          val aO, bO = odd.dequeue()
          val cO = (aO + bO) / 2
          val c = if (cO > bE) {
            res.append(s"$aO $bO\n")
            even.enqueue(aE, bE)
            cO
          } else {
            res.append(s"$aE $bE\n")
            odd.enqueue(aO, bO)
            cE
          }
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (odd.size > 1) {
          val a, b = odd.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (even.size > 1) {
          val a, b = even.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        }
      }

      if (even.size == 1 && odd.size == 1) {
        val a = even.dequeue()
        val b = odd.dequeue()
        res.append(s"$a $b\n")
        val c = (a + b + 1) / 2
        if (c % 2 == 0) even.enqueue(c)
        else odd.enqueue(c)
      }

      val x = if (even.nonEmpty) even.dequeue() else odd.dequeue()

      out.println(x)
      out.print(res.toString())
    }

    out.flush()
  }

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

import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println(2)
    for (i <- n to 3 by -1) {
      println(s"$i ${i - 2}")
      println(s"${i-1} ${i - 1}")
    }
  }
}

import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println("2")
    for (i <- n to 3 by -1) {
      if (i > 3) printf(s"$i ${i - 2}\n${i-1} ${i - 1}\n")
      else printf(s"$i ${i - 2}\n")
    }
  }
}

import scala.io.StdIn.readLine

object task extends App {
  val t: Int = readLine.toInt
  (1 to t).foreach { _ =>
    val n = readLine.toLong
    println("2")
    for (i <- n to 3 by -1) {
      if (i > 3) println(s"$i ${i - 2}\n${i-1} ${i - 1}")
      else println(s"$i ${i - 2}")
    }
  }
}

import scala.collection.mutable

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val res = new StringBuilder
      val even, odd = mutable.PriorityQueue.empty[Int]
      for (i <- 1 to n) {
        if (i % 2 == 0) even.enqueue(i)
        else odd.enqueue(i)
      }

      while (even.size > 1 || odd.size > 1) {
        if (even.size > 1 && odd.size > 1) {
          val aE, bE = even.dequeue()
          val cE = (aE + bE) / 2
          val aO, bO = odd.dequeue()
          val cO = (aO + bO) / 2
          val c = if (cO > aE) {
            res.append(s"$aO $bO\n")
            even.enqueue(aE, bE)
            cO
          } else {
            res.append(s"$aE $bE\n")
            odd.enqueue(aO, bO)
            cE
          }
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (odd.size > 1) {
          val a, b = odd.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        } else if (even.size > 1) {
          val a, b = even.dequeue()
          res.append(s"$a $b\n")
          val c = (a + b) / 2
          if (c % 2 == 0) even.enqueue(c)
          else odd.enqueue(c)
        }
      }

      if (even.size == 1 && odd.size == 1) {
        val a = even.dequeue()
        val b = odd.dequeue()
        res.append(s"$a $b\n")
        val c = (a + b + 1) / 2
        if (c % 2 == 0) even.enqueue(c)
        else odd.enqueue(c)
      }

      val x = if (even.nonEmpty) even.dequeue() else odd.dequeue()

      out.println(x)
      out.print(res.toString())
    }

    out.flush()
  }

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


A penguin Rocher has $$$n$$$ sticks. He has exactly one stick with length $$$i$$$ for all $$$1 \le i \le n$$$.He can connect some sticks. If he connects two sticks that have lengths $$$a$$$ and $$$b$$$, he gets one stick with length $$$a + b$$$. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his set and can be used for the next connections.He wants to create the maximum number of sticks that have the same length. It is not necessary to make all sticks have the same length, some sticks can have the other length. How many sticks with the equal length he can create?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain descriptions of test cases. For each test case, the only line contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print a single integer  — the answer to the problem.

NoteIn the third case, he can connect two sticks with lengths $$$1$$$ and $$$2$$$ and he will get one stick with length $$$3$$$. So, he will have two sticks with lengths $$$3$$$.In the fourth case, he can connect two sticks with lengths $$$1$$$ and $$$3$$$ and he will get one stick with length $$$4$$$. After that, he will have three sticks with lengths $$$\{2, 4, 4\}$$$, so two sticks have the same length, and one stick has the other length.

import scala.io.StdIn._

object A extends App {

  val t = readInt()
  1 to t foreach { _ =>
    val i = readInt()
    println((i - 1) / 2 + 1)
  }

}

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 n = in.nextInt()

    n.times {
      val m = in.nextInt()
      println(math.ceil(m / 2d).toInt)
    }
  }

  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 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 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 n = in.nextInt()

    n.times {
      val m = in.nextInt()
      if (m == 1 || m == 2) println(1) else println(2)
    }
  }

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


You went to the store, selling $$$n$$$ types of chocolates. There are $$$a_i$$$ chocolates of type $$$i$$$ in stock.You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy $$$x_i$$$ chocolates of type $$$i$$$ (clearly, $$$0 \le x_i \le a_i$$$), then for all $$$1 \le j < i$$$ at least one of the following must hold:  $$$x_j = 0$$$ (you bought zero chocolates of type $$$j$$$) $$$x_j < x_i$$$ (you bought less chocolates of type $$$j$$$ than of type $$$i$$$) For example, the array $$$x = [0, 0, 1, 2, 10]$$$ satisfies the requirement above (assuming that all $$$a_i \ge x_i$$$), while arrays $$$x = [0, 1, 0]$$$, $$$x = [5, 5]$$$ and $$$x = [3, 2]$$$ don't.Calculate the maximum number of chocolates you can buy.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$), denoting the number of types of chocolate. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$1 \le a_i \le 10^9$$$), denoting the number of chocolates of each type.

Print the maximum number of chocolates you can buy.

NoteIn the first example, it is optimal to buy: $$$0 + 0 + 1 + 3 + 6$$$ chocolates.In the second example, it is optimal to buy: $$$1 + 2 + 3 + 4 + 10$$$ chocolates.In the third example, it is optimal to buy: $$$0 + 0 + 0 + 1$$$ chocolates.

//package codeforces.contest1139

object Chocolates {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)

    println(arr.foldRight((Int.MaxValue, 0l)) { case (current, (maximum: Int, sum: Long)) =>
      val chocolates = (current min (maximum - 1)) max 0
      (chocolates, sum + chocolates)
    }._2)
  }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val A = na(N)
    var ans = 0L

    var next = 1e9.toInt + 1
    REP_r(N) { i =>
      next = if (A(i) < next) {
        A(i)
      } else {
        max(0, next - 1)
      }
      debug(s"next:$next")
      ans += next
    }

    out.println(ans)
  }

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

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

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

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

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

  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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

import scala.io.StdIn

object Chocolate_1139B {
  // https://codeforces.com/problemset/problem/1139/B
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    val cTypes = StdIn.readLine().split(" ").map(_.toInt)

    val (_, res) = cTypes.foldRight((Int.MaxValue, 0L)) {
      case (curr: Int, (prev: Int, sum: Long)) =>
        if (curr <= 0 || prev <= 0) {
          (0, sum)
        } else if (prev > curr) {
          (curr, sum + curr)
        } else {
          // prev <= curr && prev != 0
          (prev - 1, sum + prev - 1)
        }
    }

    println(res)
  }

}

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong).reverse
    val cal = (a: Long,b: Long) => math.max(math.min(b , a-1), 0)
    var ans = array(0)
    for (i <- 1 until n){
      array(i) = cal(array(i-1), array(i))
      ans = ans + array(i)
    }
    println(ans)
  }
}

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong)
    var sum = 0L
    sum += array(n-1)
    for (i <- 1 until n){
      val temp = math.max(math.min(array(n-i-1) , array(n-i)-1), 0)
      sum += temp
      array(n-i-1) = temp
    }
    println(sum)
  }
}

//package codeforces.contest1139

object Chocolates {
  def main(args: Array[String]): Unit = {
    val n = io.StdIn.readInt()
    val arr = io.StdIn.readLine().split(" ").map(_.toInt)

    println(arr.foldRight((Int.MaxValue, 0)) { case (current, (maximum: Int, sum: Int)) =>
      val chocolates = (current min (maximum - 1)) max 0
      (chocolates, sum + chocolates)
    }._2)
  }
}

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong).reverse
    val temp = (a: Long,b: Long) => math.max(math.min(b , a-1), 0)
    var ans = 0L
    for (i <- 1 until n){
      ans = ans + temp(array(i-1), array(i))
    }
    println(ans)
  }
}

object B1139 {
  def main(args: Array[String]): Unit = {
    val stdin = scala.io.StdIn
    val n = stdin.readInt()
    val array = stdin.readLine.trim.split(" ").map(_.toLong).reverse
    val ans = array.foldLeft(0L)((a,b) => math.max(math.min(b , a-1), 0))
    println(ans)
  }
}


Little town Nsk consists of n junctions connected by m bidirectional roads. Each road connects two distinct junctions and no two roads connect the same pair of junctions. It is possible to get from any junction to any other junction by these roads. The distance between two junctions is equal to the minimum possible number of roads on a path between them.In order to improve the transportation system, the city council asks mayor to build one new road. The problem is that the mayor has just bought a wonderful new car and he really enjoys a ride from his home, located near junction s to work located near junction t. Thus, he wants to build a new road in such a way that the distance between these two junctions won't decrease. You are assigned a task to compute the number of pairs of junctions that are not connected by the road, such that if the new road between these two junctions is built the distance between s and t won't decrease.

The firt line of the input contains integers n, m, s and t (2 ≤ n ≤ 1000, 1 ≤ m ≤ 1000, 1 ≤ s, t ≤ n, s ≠ t) — the number of junctions and the number of roads in Nsk, as well as the indices of junctions where mayors home and work are located respectively. The i-th of the following m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), meaning that this road connects junctions ui and vi directly. It is guaranteed that there is a path between any two junctions and no two roads connect the same pair of junctions.

Print one integer — the number of pairs of junctions not connected by a direct road, such that building a road between these two junctions won't decrease the distance between junctions s and t.

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

import scala.collection.mutable
import java.util.TreeSet
import scala.collection.mutable.ListBuffer
import scala.io.StdIn

object Main2 extends App {

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7

  val n = in.nextInt
  val m = in.nextInt
  val s = in.nextInt - 1
  val t = in.nextInt - 1

  val g = Array.ofDim[Boolean](n, n)

  for (_ <- 0 to m-1) {
    val x = in.nextInt - 1
    val y = in.nextInt - 1
    g(x)(y) = true
    g(y)(x) = true
  }

  val d1 = bfs(s, g)
  val d2 = bfs(t, g)

  var cnt = 0

  for {
    i <- 0 until n
    j <- i + 1 until n
    if !g(i)(j) && d1(i) + d2(j) + 1 >= d1(t) && d1(j) + d2(i) + 1 >= d1(t)
  } cnt += 1

  out.println(cnt)
  out.flush()
  out.close()

  def bfs(s: Int, g: Array[Array[Boolean]]): Array[Int] = {
    val queue = scala.collection.mutable.Queue[Int]()
    val dist = new Array[Int](1000).map(_ => Int.MaxValue)
    queue += s
    dist(s) = 0

    while (queue.length > 0) {
      val v = queue.dequeue()
      for (u <- 0 to n-1)
        if (g(v)(u) && dist(u) > dist(v) + 1) {
          dist(u) = dist(v) + 1
          queue += u
        }
    }

    dist
  }

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

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

import scala.collection.mutable
import java.util.TreeSet
import scala.collection.mutable.ListBuffer
import scala.io.StdIn

object Main2 extends App {

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7

  val n = in.nextInt
  val m = in.nextInt
  val s = in.nextInt - 1
  val t = in.nextInt - 1

  val g = Array.ofDim[Boolean](n, n)

  for (_ <- 0 to m-1) {
    val x = in.nextInt - 1
    val y = in.nextInt - 1
    g(x)(y) = true
    g(y)(x) = true
  }

  val d1 = bfs(s, g)
  val d2 = bfs(t, g)

  var cnt = 0

  for {
    i <- 0 until n
    j <- i + 1 until n
    if !g(i)(j) && d1(i) + d2(j) + 1 >= d1(t)
  } cnt += 1

  out.println(cnt)
  out.flush()
  out.close()

  def bfs(s: Int, g: Array[Array[Boolean]]): Array[Int] = {
    val queue = scala.collection.mutable.Queue[Int]()
    val dist = new Array[Int](1000).map(_ => Int.MaxValue)
    queue += s
    dist(s) = 0

    while (queue.length > 0) {
      val v = queue.dequeue()
      for (u <- 0 to n-1)
        if (g(v)(u) && dist(u) > dist(v) + 1) {
          dist(u) = dist(v) + 1
          queue += u
        }
    }

    dist
  }

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}