#include <bits/stdc++.h>
using namespace std;
struct Range {
  int row;
  int s, t;
};
pair<int, int> nums[100000];
int seats[100000];
int sas[100000];
int main() {
  int T;
  cin >> T;
  while (T--) {
    int n, m;
    scanf("%d %d", &n, &m);
    int k = n * m;
    for (int i = 0; i < k; i++) {
      int a;
      scanf("%d", &a);
      nums[i] = {a, i};
    }
    sort(nums, nums + k);
    nums[k] = {nums[k - 1].first + 1, k};
    int row = 0;
    int start = 0;
    int first = 0;
    vector<Range> ranges;
    for (int i = 1; i <= k; i++) {
      if (nums[i].first != nums[first].first) {
        ranges.clear();
        int cnt = i - first;
        while (cnt > 0) {
          if (cnt < m - start) {
            int end = start + cnt;
            ranges.push_back({row, start, end});
            cnt = 0;
            start = end;
          } else {
            int end = m;
            ranges.push_back({row, start, end});
            cnt -= end - start;
            ++row;
            start = 0;
          }
        }
        for (int j = first; j < i; j++) {
          int tr = -1;
          int tc = -1;
          for (auto &range : ranges) {
            if (range.s != range.t && (tr == -1 || (tc < range.t))) {
              tr = range.row;
              tc = range.t;
            }
          }
          for (auto &range : ranges) {
            if (tr == range.row && tc == range.t) {
              --range.t;
              --tc;
            }
          }
          seats[tr * m + tc] = nums[j].second;
          sas[tr * m + tc] = nums[j].first;
        }
        first = i;
      }
    }
    long long ans = 0;
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        for (int k = 0; k < j; k++) {
          ans += seats[i * m + k] < seats[i * m + j];
        }
      }
    }
    cout << ans << endl;
  }
}
