#include <bits/stdc++.h>
using namespace std;
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  for (long long i = 0; i < v.size(); ++i) {
    os << v[i] << " ";
  }
  return os;
}
template <typename T>
ostream &operator<<(ostream &os, const vector<vector<T>> &v) {
  for (long long i = 0; i < v.size(); ++i) {
    for (long long j = 0; j < v[i].size(); j++) os << v[i][j] << " ";
    cout << "\n";
  }
  return os;
}
template <typename T>
ostream &operator<<(ostream &os, const vector<pair<T, T>> &v) {
  for (long long i = 0; i < v.size(); ++i) {
    os << v[i].first << " " << v[i].second << "\n";
  }
  return os;
}
void solve() {
  long long n, m;
  cin >> n >> m;
  vector<pair<long long, long long>> v;
  vector<pair<long long, long long>> v1;
  for (long long i = 0; i < n * m; i++) {
    long long x, y;
    cin >> x;
    v.push_back({x, i});
    v1.push_back({x, i});
  }
  sort(v.begin(), v.end());
  map<pair<long long, long long>, long long> mp;
  for (long long i = 0; i < m * n; i++) {
    mp[v[i]] = i;
  }
  vector<vector<long long>> vv(n);
  long long ans = 0;
  for (long long i = 0; i < n * m; i++) {
    long long vn = mp[v1[i]] / m;
    if (vv[vn].size() > 0) {
      long long x = lower_bound(vv[vn].begin(), vv[vn].end(), v1[i].first) -
                    vv[vn].begin();
      ans += x;
    }
    vv[vn].push_back(v1[i].first);
    sort(vv[vn].begin(), vv[vn].end());
  }
  cout << ans << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t = 1;
  cin >> t;
  for (long long x = 0; x < t; x++) {
    solve();
  }
  return 0;
}
