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.BufferedReader;
          import java.io.FileInputStream;
          import java.io.FileNotFoundException;
          import java.io.IOException;
          import java.io.InputStreamReader;
          import java.util.*;
          import java.io.PrintStream;
  
                      //import java.util.*;
  
                              public class Solution {
  
                                  public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
  
                                  static class FastScanner {
  
                                          BufferedReader br;
                                          StringTokenizer st ;
  
                                          FastScanner(){
                                              br =  new BufferedReader(new InputStreamReader(System.in));
                                              st = new StringTokenizer("");
                                          }
  
                                          FastScanner(String file) {
  
                                              try {
                                                  br =  new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                                                  st = new StringTokenizer("");
                                              } catch (FileNotFoundException e) {
                                                  // TODO Auto-generated catch block
                                                  System.out.println("file not found");
                                                  e.printStackTrace();
                                              }
                                              
                                          }
                                          
  
                                          String next() {
                                              while (!st.hasMoreTokens())
                                                  try {
                                                      st = new StringTokenizer(br.readLine());
                                                  } catch (IOException e) {
                                                  }
                                              return st.nextToken();
                                          }
  
                                          int nextInt() {
                                              return Integer.parseInt(next());
                                          }
  
                                          long nextLong() {
                                              return Long.parseLong(next());
                                          }
                                          String readLine() throws IOException{
                                              return br.readLine();
                                          }
                                      }
                                                          
                                  static class Pair<T,X>{
                                      T first;
                                      X second;
                                      Pair(T first,X second){
                                          this.first = first;
                                          this.second = second;
                                      }
  
                                      @Override
                                      public int hashCode(){
                                          return Objects.hash(first,second);
                                      }
  
                                      @Override
                                      public boolean equals(Object obj){
                                          return obj.hashCode() == this.hashCode();
                                      }
  
                                  }
  
                              
                              static PrintStream debug = null;
                              
                              public static void main(String[] args) throws Exception {
                                  
                                  FastScanner s = new FastScanner();
  
                                  
                                  if(LOCAL){
                                      s = new FastScanner("src/input.txt");
                                      PrintStream o = new PrintStream("src/sampleout.txt");
                                      debug = new PrintStream("src/debug.txt");
                                      System.setOut(o);
                                  }
  
                                  
                                  long mod = 1000000007;
  
                              
                                  int tcr = s.nextInt();                  
                                  
                                  StringBuilder sb = new StringBuilder();
  
                                  for(int tc=0;tc<tcr;tc++){
                                      
                                      int n = s.nextInt();
  
                                      int m = s.nextInt();
  
                                      long ans = 0l;
  
                                      long arr[] = new long[n*m];
  
                                      TreeMap<Long,List<Integer>> map = new TreeMap<>();
  
                                      for(int i=0;i<n*m;i++){
                                          arr[i] = s.nextLong();
                                          List<Integer> list = map.getOrDefault(arr[i],new ArrayList<>());
                                          list.add(i);
                                          map.put(arr[i],list);
                                      }
  
                                      List<Integer> list = new ArrayList<>();
                                      
                                      int rows[] = new int[n*m];
                                      int row_no = 0;
                                      int cnt_ = 0;
                                      for(long key : map.keySet()){
                                          
                                          List<Integer> pos = map.get(key);
  
                                          for(int i=0;i<pos.size();i++){
                                              rows[pos.get(i)] = row_no;
                                              cnt_++;
                                              if(cnt_ == m){
                                                  cnt_ = 0;
                                                  row_no++;
                                              }
                                          }
  
                                          if(cnt_ == m){
                                              cnt_ = 0;
                                              row_no++;
                                          }
  
                                      }
  
                                      List<List<Long>> rows_num = new ArrayList<>();
  
                                      for(int i=0;i<n;i++){
                                          rows_num.add(new ArrayList<>());
                                      }
  
                                      for(int i=0;i<n*m;i++){
                                          List<Long> l = rows_num.get(rows[i]);
                                          for(int j=0;j<l.size();j++){
                                              if((l.get(j) < arr[i])){
                                                  ans++;
                                              }
                                          }
                                          rows_num.get(rows[i]).add(arr[i]);
                                      }
  
                                      // dbg(debug,dp);
  
                                      sb.append(ans+"\n");
  
                                  }
  
                                  print(sb.toString());
  
                              }
  
                              public static long solve(int index,Long dp[],String str,String str1,int pos0[],int pos1[]){
  
                                  if(index >= dp.length){
                                      return 0l;
                                  }
  
                                  if(dp[index] != null){
                                      return dp[index];
                                  }
  
                                  int n = dp.length;
  
                                  int i = index;
                                  
                                  long ans = 0;
  
                                  int c1 = str.charAt(i) - '0';
                                  int c2 = str1.charAt(i) - '0';
  
                                  if(c1 == 0 && c2 == 0){
                                      
                                      long temp = 1 + solve(index+1,dp,str,str1,pos0,pos1);
                                     
                                      i = pos1[i];
  
                                      long temp1 = 0;
                                      
                                      if(i != -1){
                                          temp1 = 2 + solve(i+1,dp,str,str1,pos0,pos1);
                                      }
  
                                      ans = Math.max(temp,temp1);
                                      
                                  }else if(c1 == 1 && c2 == 1){
                                      
                                      long temp = solve(index+1,dp,str,str1,pos0,pos1);
  
                                      i = pos0[i];
  
                                      long temp1 = 0;
                                      if(i != -1){
                                          temp1 = 2 + solve(i+1,dp,str,str1,pos0,pos1);
                                      }
  
                                      ans = Math.max(temp,temp1);
                                      
                                  }else{
                                      ans = 2 + solve(index+1,dp,str,str1,pos0,pos1);
                                  }
  
                                  dp[index] = ans;
                                  
                                  return ans;
                                  
                              }
  
                             
                              
                              static int len(long num){
                                  return Long.toString(num).length();
                              }
  
                              static long mulmod(long a, long b,long mod)
                              {
                                  long ans = 0l;
                                  
                                  while(b > 0){
                                      long curr = (b & 1l);
                                      if(curr == 1l){
                                          ans = ((ans % mod) + a) % mod;
                                      }
                                      
                                      a = (a + a) % mod;
  
                                      b = b >> 1;
                                  }
  
                                  return ans;
                              }
  
  
                              public static void dbg(PrintStream ps,Object... o) throws Exception{
                                  if(ps == null){
                                      return;
                                  }
                                  Debug.dbg(ps,o);
                              }
  
                              public static long modpow(long num,long pow,long mod){
  
                                  long val = num;
                                  long ans = 1l;
  
                                  while(pow > 0l){
                                      
                                      long bit = pow & 1l;
  
                                      if(bit == 1){
                                          ans = (ans * (val%mod))%mod;
                                      }
  
                                      val = (val * val) % mod;
                                      pow = pow >> 1;
                                  }
  
                                  return ans;
  
                              }
  
                              public static char get(int n){
                                  return (char)('a' + n);
                              }
  
                              public static long[] sort(long arr[]){
                                  List<Long> list = new ArrayList<>();
                                  for(long n : arr){list.add(n);}
                                  Collections.sort(list);
                                  for(int i=0;i<arr.length;i++){
                                      arr[i] = list.get(i);
                                  }
                                  return arr;
                              }
  
                              public static int[] sort(int arr[]){
                                  List<Integer> list = new ArrayList<>();
                                  for(int n : arr){list.add(n);}
                                  Collections.sort(list);
                                  for(int i=0;i<arr.length;i++){
                                      arr[i] = list.get(i);
                                  }
                                  return arr;
                              }
  
                              // return the (index + 1)
                              // where index is the pos of just smaller element
                              // i.e count of elemets strictly less than num
                              public static int justSmaller(long arr[],long num){
                                  //  System.out.println(num+"@");
                                  int st = 0;
                                  int e = arr.length - 1;
                          
                                  int ans = -1;
                          
                                  while(st <= e){
                          
                                      int mid = (st + e)/2;
                          
                                      if(arr[mid] >= num){
                                          e = mid - 1;
                                      }else{
                                          ans = mid;
                                          st = mid + 1;
                                      }
                          
                                  }
                          
                          
                                  return ans + 1;
                          
                              }
                              public static int justSmaller(int arr[],int num){
                                  //  System.out.println(num+"@");
                                  int st = 0;
                                  int e = arr.length - 1;
                          
                                  int ans = -1;
                          
                                  while(st <= e){
                          
                                      int mid = (st + e)/2;
                          
                                      if(arr[mid] >= num){
                                          e = mid - 1;
                                      }else{
                                          ans = mid;
                                          st = mid + 1;
                                      }
                          
                                  }
                          
                          
                                  return ans + 1;
                          
                              }
                              
                              //return (index of just greater element)
                              //count of elements smaller than or equal to num
  
                              public static int justGreater(long arr[],long num){
                                  int st = 0;
                                  int e = arr.length - 1;
                          
                                  int ans = arr.length;
                          
                                  while(st <= e){
                                      
                                      int mid = (st + e)/2;
                          
                                      if(arr[mid] <= num){
                                          st = mid + 1;
                                      }else{
                                          ans = mid;
                                          e = mid - 1;
                                      }
                                  }
                          
                                  return ans;
                          
                              }
  
                              public static int justGreater(int arr[],int num){
                                  int st = 0;
                                  int e = arr.length - 1;
                          
                                  int ans = arr.length;
                          
                                  while(st <= e){
                                      
                                      int mid = (st + e)/2;
                          
                                      if(arr[mid] <= num){
                                          st = mid + 1;
                                      }else{
                                          ans = mid;
                                          e = mid - 1;
                                      }
                                  }
                          
                                  return ans;
                          
                              }
                          
                              
  
                              public static void println(Object obj){
                                  System.out.println(obj.toString());
                              }
  
                              public static void print(Object obj){
                                  System.out.print(obj.toString());
                              }
  
                              public static int gcd(int a,int b){
                                  if(b == 0){return a;}
                                  return gcd(b,a%b);
                              }
  
                              public static long gcd(long a,long b){
                                  if(b == 0l){
                                      return a;
                                  }
  
                                  return gcd(b,a%b);
                              }
  
                              public static int find(int parent[],int v){
                                  if(parent[v] == v){
                                      return v;
                                  }
                                  
                                  return parent[v] = find(parent, parent[v]);
                              }
  
                          
  
                              public static List<Integer> sieve(){
                              
                                      List<Integer> prime = new ArrayList<>();
  
                                      int arr[] = new int[100001];
  
                                  Arrays.fill(arr,1);
  
                                  arr[1] = 0;
                                  arr[2] = 1;
  
                                  for(int i=2;i<=100000;i++){
                                      
                                      if(arr[i] == 1){
                                          
                                          prime.add(i);
  
                                          for(long j = (i*1l*i);j<100001;j+=i){
                                              arr[(int)j] = 0;
                                          }
                                      }
                                  }
  
                                  return prime;
                              }
  
                              static boolean isPower(long n,long a){
                                  
                                  long log = (long)(Math.log(n)/Math.log(a));
  
                                  long power = (long)Math.pow(a,log);
  
                                  if(power == n){return true;}
  
                                  return false;
                              }
  
  
                              private static int mergeAndCount(int[] arr, int l,int m, int r)
                              {
  
                                  // Left subarray
                                  int[] left =  Arrays.copyOfRange(arr, l, m + 1);
  
                                  // Right subarray
                                  int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);
  
                                  int i = 0, j = 0, k = l, swaps = 0;
  
                                  while (i < left.length && j < right.length) {
                                      if (left[i] <= right[j])
                                          arr[k++] = left[i++];
                                      else {
                                          arr[k++] = right[j++];
                                          swaps += (m + 1) - (l + i);
                                      }
                                  }
                                  while (i < left.length)
                                      arr[k++] = left[i++];
                                  while (j < right.length)
                                      arr[k++] = right[j++];
                                  return swaps;
                              }
  
                              // Merge sort function
                              private static int mergeSortAndCount(int[] arr, int l,int r)
                              {
  
                                  // Keeps track of the inversion count at a
                                  // particular node of the recursion tree
                                  int count = 0;
  
                                  if (l < r) {
                                      int m = (l + r) / 2;
  
                                      // Total inversion count = left subarray count
                                      // + right subarray count + merge count
  
                                      // Left subarray count
                                      count += mergeSortAndCount(arr, l, m);
  
                                      // Right subarray count
                                      count += mergeSortAndCount(arr, m + 1, r);
  
                                      // Merge count
                                      count += mergeAndCount(arr, l, m, r);
                                  }
  
                                  return count;
                              }
  
                              static class Debug{
                                  //change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces
                                  public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
  
                                  
  
                                  private static <T> String ts(T t) {
                                      if(t==null) {
                                          return "null";
                                      }
                                      try {
                                          return ts((Iterable) t);
                                      }catch(ClassCastException e) {
                                          if(t instanceof int[]) {
                                              String s = Arrays.toString((int[]) t);
                                              return "{"+s.substring(1, s.length()-1)+"}\n";
                                          }else if(t instanceof long[]) {
                                              String s = Arrays.toString((long[]) t);
                                              return "{"+s.substring(1, s.length()-1)+"}\n";
                                          }else if(t instanceof char[]) {
                                              String s = Arrays.toString((char[]) t);
                                              return "{"+s.substring(1, s.length()-1)+"}\n";
                                          }else if(t instanceof double[]) {
                                              String s = Arrays.toString((double[]) t);
                                              return "{"+s.substring(1, s.length()-1)+"}\n";
                                          }else if(t instanceof boolean[]) {
                                              String s = Arrays.toString((boolean[]) t);
                                              return "{"+s.substring(1, s.length()-1)+"}\n";
                                          }
                                          try {
                                              return ts((Object[]) t);
                                          }catch(ClassCastException e1) {
                                              return t.toString();
                                          }
                                      }
                                  }
                                  private static <T> String ts(T[] arr) {
                                      StringBuilder ret = new StringBuilder();
                                      ret.append("{");
                                      boolean first = true;
                                      for(T t: arr) {
                                          if(!first) {
                                              ret.append(", ");
                                          }
                                          first = false;
                                          ret.append(ts(t));
                                      }
                                      ret.append("}");
                                      return ret.toString();
                                  }
                                  private static <T> String ts(Iterable<T> iter) {
                                      StringBuilder ret = new StringBuilder();
                                      ret.append("{");
                                      boolean first = true;
                                      for(T t: iter) {
                                          if(!first) {
                                              ret.append(", ");
                                          }
                                          first = false;
                                          ret.append(ts(t));
                                      }
                                      ret.append("}");
                                      return ret.toString();
                                  }
                                  public static void dbg(PrintStream ps,Object... o) throws Exception {
                                      if(LOCAL) {
                                          System.setErr(ps);
                                          System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
                                          for(int i = 0; i<o.length; i++) {
                                              if(i!=0) {
                                                  System.err.print(", ");
                                              }
                                              System.err.print(ts(o[i]));
                                          }
                                          System.err.println("]");
                                      }
                                  }
                              }
  
                      }