description: It is the hard version of the problem. The only difference is that in this version 1 ≤ n ≤ 300.
  
  In the cinema seats can be represented as the table with n rows and m columns. The rows are numbered with integers from 1 to n. The seats in each row are numbered with consecutive integers from left to right: in the k-th row from m (k - 1) + 1 to m k for all rows 1 ≤ k ≤ n.
  
  1| 2| ⋅⋅⋅| m - 1| m  
  ---|---|---|---|---  
  m + 1| m + 2| ⋅⋅⋅| 2 m - 1| 2 m  
  2m + 1| 2m + 2| ⋅⋅⋅| 3 m - 1| 3 m  
  \vdots| \vdots| \ddots| \vdots| \vdots  
  m (n - 1) + 1| m (n - 1) + 2| ⋅⋅⋅| n m - 1| n m  
  The table with seats indices
  
  There are nm people who want to go to the cinema to watch a new film. They are numbered with integers from 1 to nm. You should give exactly one seat to each person.
  
  It is known, that in this cinema as lower seat index you have as better you can see everything happening on the screen. i-th person has the level of sight a_i. Let's define s_i as the seat index, that will be given to i-th person. You want to give better places for people with lower sight levels, so for any two people i, j such that a_i < a_j it should be satisfied that s_i < s_j.
  
  After you will give seats to all people they will start coming to their seats. In the order from 1 to nm, each person will enter the hall and sit in their seat. To get to their place, the person will go to their seat's row and start moving from the first seat in this row to theirs from left to right. While moving some places will be free, some will be occupied with people already seated. The inconvenience of the person is equal to the number of occupied seats he or she will go through.
  
  Let's consider an example: m = 5, the person has the seat 4 in the first row, the seats 1, 3, 5 in the first row are already occupied, the seats 2 and 4 are free. The inconvenience of this person will be 2, because he will go through occupied seats 1 and 3.
  
  Find the minimal total inconvenience (the sum of inconveniences of all people), that is possible to have by giving places for all people (all conditions should be satisfied).
  
  Input
  
  The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Description of the test cases follows.
  
  The first line of each test case contains two integers n and m (1 ≤ n, m ≤ 300) — the number of rows and places in each row respectively.
  
  The second line of each test case contains n ⋅ m integers a_1, a_2, …, a_{n ⋅ m} (1 ≤ a_i ≤ 10^9), where a_i is the sight level of i-th person.
  
  It's guaranteed that the sum of n ⋅ m over all test cases does not exceed 10^5.
  
  Output
  
  For each test case print a single integer — the minimal total inconvenience that can be achieved.
  
  Example
  
  Input
  
  
  7
  1 2
  1 2
  3 2
  1 1 2 2 3 3
  3 3
  3 4 4 1 1 1 1 1 2
  2 2
  1 1 2 1
  4 2
  50 50 50 50 3 50 50 50
  4 2
  6 6 6 6 2 2 9 6
  2 9
  1 3 3 3 3 3 1 1 3 1 3 1 1 3 3 1 1 3
  
  
  Output
  
  
  1
  0
  4
  0
  0
  0
  1
  
  Note
  
  In the first test case, there is a single way to give seats: the first person sits in the first place and the second person — in the second. The total inconvenience is 1.
  
  In the second test case the optimal seating looks like this: 
  
  <image>
  
  In the third test case the optimal seating looks like this: 
  
  <image>
  
  The number in a cell is the person's index that sits on this place.
solution: import java.io.BufferedWriter;
  import java.io.DataInputStream;
  import java.io.FileInputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.io.OutputStreamWriter;
  import java.io.PrintWriter;
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.Collections;
  import java.util.List;
  import java.util.Objects;
  import java.util.PriorityQueue;
  import java.util.Random;
  
  /**
   * Main
   */
  public class Main {
      public static void main(String[] args) {
          try {
              long startTime = System.currentTimeMillis();
  
              final FastPrinter fp = new FastPrinter(System.out);
              final FastReader fr = new FastReader(System.in);
  
              Solution solver = new Solution(fp, fr);
  
              boolean multipleTC = true;
              int test = multipleTC ? fr.nextInt() : 1;
  
              while (test-- > 0) {
                  // Write code..
                  solver.solve();
              }
  
              solver.printAns();
  
              long endTime = System.currentTimeMillis();
              if (System.getProperty("ONLINE_JUDGE") == null) {
                  // fp.println("Time: " + (endTime - startTime) + " ms");
              }
  
              fp.close();
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }
  
  /**
   * Solution
   */
  class Solution {
  
      private final FastPrinter fPrinter;
      private final FastReader fReader;
  
      private final StringBuilder ans;
  
      private final long mod = (long) 1e9 + 7;
  
      public Solution(FastPrinter _fPrinter, FastReader _fReader) {
          fReader = _fReader;
          fPrinter = _fPrinter;
          ans = new StringBuilder();
          // initializeSieve();
      }
  
      @SuppressWarnings("unchecked")
      public void solve() throws IOException {
          int n = fReader.nextInt();
          int m = fReader.nextInt();
          Pair<Integer, Integer>[] arr = new Pair[n * m];
          // PriorityQueue<Pair<Integer, Integer>> pq = new PriorityQueue<>();
          for (int i = 0; i < n * m; i++) {
              arr[i] = new Pair<>(fReader.nextInt(), i);
              // arr[i].first = fReader.nextInt();
              // arr[i].second = i;
              // pq.add(new Pair<>(arr[i], i));
          }
          Arrays.sort(arr);
          for (int i = 0; i < n * m; i++)
              arr[i].second = -arr[i].second;
          int res = 0;
          // int[] seats = new int[m];
          Pair<Integer, Integer>[][] seats = new Pair[n][m];
          // ArrayList<Pair<Integer, Integer>> seats = new ArrayList<>();
          // Arrays.fill(seats, -1);
          // for (int i = 0; i < m; i++)
          // seats.add(new Pair<>(-1, -1));
          for (Pair<Integer, Integer>[] p : seats)
              Arrays.fill(p, null);
          for (int i = 0; i < n; i++) {
              Arrays.sort(arr, i * m, i * m + m);
              for (int j = 0; j < m; j++) {
                  // Pair<Integer, Integer> person = pq.poll();
                  seats[i][j] = arr[i * m + j];
                  for (int k = 0; k < j; k++) {
                      if (seats[i][k] != null && Math.abs(seats[i][k].second) < Math.abs(arr[i * m + j].second))
                          res++;
                  }
              }
          }
          // for (Pair<Integer, Integer>[] seat : seats) {
          // for (Pair<Integer, Integer> p : seat)
          // fPrinter.print(p.toString() + ", ");
          // fPrinter.println();
          // }
  
          ans.append(res).append('\n');
      }
  
      // public void solve() throws IOException {
      // int n = fReader.nextInt();
      // long[] x = fReader.nextLongArray(n);
      // long[] y = fReader.nextLongArray(n);
      // ArrayList<Pair<Long, Long>> points = new ArrayList<>();
      // // fPrinter.println("n: " + n);
      // for (int i = 0; i < n; i++) {
      // points.add(new Pair<>(x[i], y[i]));
      // // fPrinter.println(points.get(i).toString());
      // }
      // // Collections.sort(points);
      // long res = Integer.MAX_VALUE;
      // for (int i = 0; i < n; i++) {
      // long rest = 0;
      // for (int j = 0; j < n; j++) {
      // if (j == i)
      // continue;
      // long dx = Math.abs(points.get(i).first - points.get(j).first);
      // long dy = Math.abs(points.get(i).second - points.get(j).second);
      // // long dx = points.get(i).first - points.get(j).first;
      // // long dy = points.get(i).second - points.get(j).second;
      // if (dx == 0 && dy == 0) {
  
      // } else if (dx == 0 || dy == 0) {
      // rest++;
      // } else {
      // // long k = gcd(dx, dy);
      // if (dx == dy) {
      // rest++;
      // } else {
      // rest += 2;
      // }
      // // rest += Math.min(2, Math.max(dx / k, dy / k));
      // }
      // fPrinter.println(points.get(i).toString());
      // fPrinter.println(points.get(j).toString());
      // fPrinter.println(dx + " " + dy);
      // fPrinter.println(rest);
      // }
      // res = Math.min(res, rest);
      // }
      // ans.append(res).append('\n');
      // }
  
      // public void solve() throws IOException {
      // int n = fReader.nextInt();
      // int l = fReader.nextInt();
      // int r = fReader.nextInt();
      // if (n < l) {
      // ans.append(l).append('\n');
      // } else if (n >= l && n <= r) {
      // long res = Integer.MAX_VALUE;
      // int resk = 0;
  
      // for (int i = l; i <= n; i++) {
      // long m = n;
      // long s = 0;
      // while (m > 0) {
      // s += m % i;
      // m /= i;
      // }
      // if (res > s) {
      // res = s;
      // resk = i;
      // }
      // }
      // ans.append(resk).append('\n');
      // } else {
      // long res = Integer.MAX_VALUE;
      // int resk = 0;
  
      // for (int i = l; i <= r; i++) {
      // long m = n;
      // long s = 0;
      // while (m > 0) {
      // s += m % i;
      // m /= i;
      // }
      // if (res > s) {
      // res = s;
      // resk = i;
      // }
      // }
      // ans.append(resk).append('\n');
      // }
      // }
  
      char[][] rotate(char[][] grid, int n) {
          char[][] res = new char[n][n];
          for (int i = 0; i < n; i++) {
              for (int j = 0; j < n; j++) {
                  res[j][n - i - 1] = grid[i][j];
              }
          }
          return res;
      }
  
      private List<Integer> primeFactors(int num) {
          List<Integer> primes = new ArrayList<>();
          for (int i = 2; i * i <= num; i++) {
              while (num % i == 0) {
                  num /= i;
                  primes.add(i);
              }
          }
          if (num != 1) {
              primes.add(num);
          }
          return primes;
      }
  
      private boolean nextPermutation(int[] arr) {
          for (int a = arr.length - 2; a >= 0; a--) {
              if (arr[a] < arr[a + 1]) {
                  for (int b = arr.length - 1;; b--) {
                      if (arr[b] > arr[a]) {
                          int t = arr[a];
                          arr[a] = arr[b];
                          arr[b] = t;
                          for (++a, b = arr.length - 1; a < b; ++a, --b) {
                              t = arr[a];
                              arr[a] = arr[b];
                              arr[b] = t;
                          }
                          return true;
                      }
                  }
              }
          }
          return false;
      }
  
      private boolean nextPermutation(char[] arr) {
          for (int a = arr.length - 2; a >= 0; a--) {
              if (arr[a] < arr[a + 1]) {
                  for (int b = arr.length - 1;; b--) {
                      if (arr[b] > arr[a]) {
                          char t = arr[a];
                          arr[a] = arr[b];
                          arr[b] = t;
                          for (++a, b = arr.length - 1; a < b; ++a, --b) {
                              t = arr[a];
                              arr[a] = arr[b];
                              arr[b] = t;
                          }
                          return true;
                      }
                  }
              }
          }
          return false;
      }
  
      public int kthLeftMostBti(long n) {
          n |= n >> 1;
          n |= n >> 2;
          n |= n >> 4;
          n |= n >> 8;
          n |= n >> 16;
          n |= n >> 32;
          n++;
          n = n >> 1;
          for (int i = 63; i >= 0; i--) {
              if (pow(2, i) == n) {
                  return i;
              }
          }
          return 0;
      }
  
      public long pow(long a, long b) {
          long res = 1;
          while (b > 0) {
              if ((b & 1) == 0) {
                  a *= a;
                  b = b >> 1;
              } else {
                  res *= a;
                  b--;
              }
          }
          return res;
      }
  
      public long ways(long n, long r) {
          if (n < 0 || r < 0)
              return 0;
          if (n == 0 || r == 0)
              return 1;
          double res = 1;
          for (int i = 1; i <= r; i++) {
              res = res * (n - r + i) / i;
          }
          return (long) res;
      }
  
      private static boolean[] sieve = new boolean[1_000_000];
  
      private static void initializeSieve() {
          Arrays.fill(sieve, true);
          for (int i = 2; i * i < sieve.length; i++) {
              if (sieve[i]) {
                  for (int j = i * i; j < sieve.length; j += i) {
                      sieve[j] = false;
                  }
              }
          }
      }
  
      private long getSumArray(long[] arr, int n) {
          long sum = 0;
          for (long num : arr)
              sum += num;
          return sum;
      }
  
      private int gcd(int a, int b) {
          if (a == 0)
              return b;
          return gcd(b % a, a);
      }
  
      private long gcd(long a, long b) {
          if (a == 0)
              return b;
          return gcd(b % a, a);
      }
  
      private void sortArray(String[] arr, int s, int n) {
          Random r = new Random();
          for (int i = s; i < n; i++) {
              int idx = r.nextInt(n);
              String temp = arr[i];
              arr[i] = arr[idx];
              arr[idx] = temp;
          }
  
          Arrays.sort(arr, s, n);
      }
  
      private void sortArray(char[] arr, int s, int n) {
          Random r = new Random();
          for (int i = s; i < n; i++) {
              int idx = r.nextInt(n);
              char temp = arr[i];
              arr[i] = arr[idx];
              arr[idx] = temp;
          }
  
          Arrays.sort(arr, s, n);
      }
  
      private void sortArray(long[] arr, int s, int n) {
          Random r = new Random();
          for (int i = s; i < n; i++) {
              int idx = r.nextInt(n);
              long temp = arr[i];
              arr[i] = arr[idx];
              arr[idx] = temp;
          }
  
          Arrays.sort(arr, s, n);
      }
  
      private void sortArray(int[] arr, int s, int n) {
          Random r = new Random();
          for (int i = s; i < n; i++) {
              int idx = r.nextInt(n);
              int temp = arr[i];
              arr[i] = arr[idx];
              arr[idx] = temp;
          }
  
          Arrays.sort(arr, s, n);
      }
  
      public void printAns() {
          fPrinter.println(ans);
      }
  }
  
  class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T, U>> {
      T first;
      U second;
  
      Pair(T f, U s) {
          first = f;
          second = s;
      }
  
      @Override
      public boolean equals(Object obj) {
          if (!(obj instanceof Pair))
              return false;
          Pair<?, ?> p = (Pair<?, ?>) obj;
          return Objects.equals(p.first, first) && Objects.equals(p.second, second);
      }
  
      @Override
      public int hashCode() {
          return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
      }
  
      @Override
      public String toString() {
          StringBuilder sb = new StringBuilder();
          sb.append("[").append(first.toString());
          sb.append(", ").append(second.toString());
          sb.append("]");
          return sb.toString();
      }
  
      @Override
      public int compareTo(Pair<T, U> o) {
          int c;
          if ((c = this.first.compareTo(o.first)) == 0)
              return this.second.compareTo(o.second);
          // return o.second.compareTo(this.second);
          return c;
          // return this.first.compareTo(o.first);
      }
  }
  
  class DSU {
      int size;
      int[] parent;
      int[] rank;
  
      public DSU(int n) {
          size = n + 1;
          parent = new int[n + 1];
          rank = new int[n + 1];
          for (int i = 0; i <= n; i++)
              parent[i] = i;
          Arrays.fill(rank, 1);
      }
  
      int getParent(int v) {
          if (parent[v] == v) {
              return v;
          }
          return parent[v] = getParent(parent[v]);
      }
  
      void union(int x, int y) {
          x = getParent(x);
          y = getParent(y);
          if (rank[x] < rank[y]) {
              parent[x] = y;
          } else if (rank[x] > rank[y]) {
              parent[y] = x;
          } else {
              parent[x] = y;
              rank[y]++;
          }
      }
  }
  
  class SegmentTree {
      int[] tree;
      int size;
  
      public SegmentTree(int n) {
          size = n;
          tree = new int[4 * size];
      }
  
      // private void build(int[] arr, int v, int l, int r) {
      // if (l == r) {
      // tree[v] = arr[l];
      // } else {
      // int m = l + ((r - l) >> 1);
      // build(arr, v * 2, l, m);
      // build(arr, v * 2 + 1, m + 1, r);
      // tree[v] = tree[v * 2]
      // }
      // }
  }
  
  class FastPrinter {
      private final PrintWriter out;
  
      FastPrinter(OutputStream out) {
          this.out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
      }
  
      public void printlnArray(int[] arr) {
          for (int i : arr) {
              out.println(i);
          }
      }
  
      public void printlnArray(long[] arr) {
          for (long i : arr) {
              out.println(i);
          }
      }
  
      public void printArray(int[] arr) {
          for (int i : arr) {
              out.print(i + " ");
          }
          out.println();
      }
  
      public void printArray(long[] arr) {
          for (long i : arr) {
              out.print(i + " ");
          }
          out.println();
      }
  
      public void println() {
          out.println();
      }
  
      public void println(String s) {
          out.println(s);
      }
  
      public void println(int s) {
          out.println(s);
      }
  
      public void println(long s) {
          out.println(s);
      }
  
      public void println(double s) {
          out.println(s);
      }
  
      public void println(Object o) {
          out.println(o);
      }
  
      public void print(String s) {
          out.print(s);
      }
  
      public void print(Object a) {
          out.print(a);
      }
  
      public void flush() {
          out.flush();
      }
  
      public void close() {
          out.close();
      }
  }
  
  class FastReader {
      private static final int BUFFER_SIZE = 1 << 17;
      private DataInputStream din;
      private byte[] buffer;
      private int bufferPointer;
      private int bytesRead;
  
      public FastReader(InputStream in) {
          din = new DataInputStream(in);
          buffer = new byte[BUFFER_SIZE];
          bufferPointer = bytesRead = 0;
      }
  
      public FastReader(String file_name) throws IOException {
          din = new DataInputStream(new FileInputStream(file_name));
          buffer = new byte[BUFFER_SIZE];
          bufferPointer = bytesRead = 0;
      }
  
      public char next() throws IOException {
          byte c = read();
          return c == -1 ? '\0' : (char) c;
      }
  
      public String nextLine() throws IOException {
          StringBuilder sb = new StringBuilder();
          byte c = read();
          while (c != '\r' && c != '\n' && c != -1) {
              sb.append((char) c);
              c = read();
          }
          return sb.toString();
      }
  
      public int nextInt() throws IOException {
          int ret = 0;
          byte c = read();
  
          while (c <= ' ')
              c = read();
          boolean neg = (c == '-');
  
          if (neg)
              c = read();
  
          do {
              ret = ret * 10 + c - '0';
          } while ((c = read()) >= '0' && c <= '9');
  
          if (neg)
              return -ret;
          return ret;
      }
  
      public long nextLong() throws IOException {
          long ret = 0;
          byte c = read();
          while (c <= ' ')
              c = read();
          boolean neg = (c == '-');
          if (neg)
              c = read();
          do {
              ret = ret * 10 + c - '0';
          } while ((c = read()) >= '0' && c <= '9');
          if (neg)
              return -ret;
          return ret;
      }
  
      public double nextDouble() throws IOException {
          double ret = 0, div = 1;
          byte c = read();
          while (c <= ' ')
              c = read();
          boolean neg = (c == '-');
          if (neg)
              c = read();
  
          do {
              ret = ret * 10 + c - '0';
          } while ((c = read()) >= '0' && c <= '9');
  
          if (c == '.') {
              while ((c = read()) >= '0' && c <= '9') {
                  ret += (c - '0') / (div *= 10);
              }
          }
  
          if (neg)
              return -ret;
          return ret;
      }
  
      public int[] nextIntArray(int size) throws IOException {
          int[] arr = new int[size];
          for (int i = 0; i < size; i++) {
              arr[i] = nextInt();
          }
          return arr;
      }
  
      public int[] nextIntArray(int size, int pos) throws IOException {
          int[] arr = new int[size + pos];
          for (int i = pos; i < size + pos; i++) {
              arr[i] = nextInt();
          }
          return arr;
      }
  
      public long[] nextLongArray(int size) throws IOException {
          long[] arr = new long[size];
          for (int i = 0; i < size; i++) {
              arr[i] = nextLong();
          }
          return arr;
      }
  
      public long[] nextLongArray(int size, int pos) throws IOException {
          long[] arr = new long[size + pos];
          for (int i = pos; i < size + pos; i++) {
              arr[i] = nextLong();
          }
          return arr;
      }
  
      public int[][] nextIntMatrix(int n, int m) throws IOException {
          int[][] arr = new int[n][m];
          for (int i = 0; i < n; i++) {
              arr[i] = nextIntArray(m);
          }
          return arr;
      }
  
      public long[][] nextLongMatrix(int n, int m) throws IOException {
          long[][] arr = new long[n][m];
          for (int i = 0; i < n; i++) {
              arr[i] = nextLongArray(m);
          }
          return arr;
      }
  
      public ArrayList<Integer> nextIntList(int size) throws IOException {
          ArrayList<Integer> arrayList = new ArrayList<>(size);
          for (int i = 0; i < size; i++) {
              arrayList.add(nextInt());
          }
          return arrayList;
      }
  
      public ArrayList<Long> nextLongList(int size) throws IOException {
          ArrayList<Long> arrayList = new ArrayList<>(size);
          for (int i = 0; i < size; i++) {
              arrayList.add(nextLong());
          }
          return arrayList;
      }
  
      private void fillBuffer() throws IOException {
          bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
          if (bytesRead == -1)
              buffer[0] = -1;
      }
  
      private byte read() throws IOException {
          if (bufferPointer == bytesRead)
              fillBuffer();
          return buffer[bufferPointer++];
      }
  
      public void close() throws IOException {
          if (din == null)
              return;
          din.close();
      }
  }