#include <bits/stdc++.h>
using namespace std;
const int siz1 = 9e4, siz2 = 3e5, siz3 = 1e6;
int t, n, m, bit[siz1 + 5], sts[siz1 + 5];
pair<int, int> arr[siz1 + 5];
int sum(int r) {
  int ret = 0;
  for (; r >= 0; r = (r & (r + 1)) - 1) ret += bit[r];
  return ret;
}
int sum(int l, int r) { return sum(r) - sum(l - 1); }
void add(int idx, int delta) {
  for (; idx <= n * m; idx = idx | (idx + 1)) bit[idx] += delta;
}
void clear() {
  for (int i = 0; i <= n * m; ++i) {
    bit[i] = 0;
  }
}
int main() {
  scanf("%d", &t);
  while (t--) {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n * m; ++i) {
      scanf("%d", &arr[i].first);
      arr[i].second = i;
    }
    sort(arr + 1, arr + n * m + 1);
    for (int i = 1; i <= n; ++i) {
      for (int j = m * (i - 1) + 1; j <= m * i; ++j) {
        int end = j;
        while (end <= m * i && arr[end].first == arr[j].first) {
          arr[end].second = -arr[end].second;
          ++end;
        }
        --end;
        sort(arr + j, arr + end + 1);
        j = end;
      }
    }
    for (int i = 1; i <= n * m; ++i) {
      sts[-arr[i].second] = i;
    }
    long long ans = 0;
    for (int i = 1; i <= n * m; ++i) {
      int row = sts[i] / m;
      if (sts[i] % m) {
        ++row;
      }
      ans += sum((row - 1) * m + 1, sts[i]);
      add(sts[i], 1);
    }
    printf("%I64d\n", ans);
    clear();
  }
  return 0;
}
