#include <bits/stdc++.h>
using namespace std;
template <class T>
bool umin(T& a, const T& b) {
  return b < a ? a = b, 1 : 0;
}
template <class T>
bool umax(T& a, const T& b) {
  return a < b ? a = b, 1 : 0;
}
string to_string(bool b) { return b ? "true" : "false"; }
string to_string(char c) { return string(1, c); }
string to_string(const char* second) { return string(second); }
string to_string(string second) { return second; }
template <class T>
string to_string(T v) {
  bool first = 1;
  string res;
  for (auto& x : v) {
    if (!first) res += ' ';
    first = 0;
    res += to_string(x);
  }
  return res;
}
template <class A>
void write(A x) {
  cout << to_string(x);
}
void print() { write("\n"); }
template <class H, class... T>
void print(const H& h, const T&... t) {
  write(h);
  if (sizeof...(t)) write(' ');
  print(t...);
}
template <typename A, typename B>
istream& operator>>(istream& cin, pair<A, B>& p) {
  cin >> p.first;
  return cin >> p.second;
}
const long long mod = 998244353;
const long long maxsize = 3e5 + 10;
void solve() {
  long long n, m;
  cin >> n >> m;
  vector<long long> a(n * m);
  for (int ele = 0; ele < n * m; ele++) cin >> a[ele];
  ;
  map<long long, queue<pair<long long, long long>>> mp;
  vector<long long> p(a.begin(), a.end());
  sort(p.begin(), p.end());
  vector<vector<long long>> matrix(n, vector<long long>(m));
  ;
  for (int i = (0); (1) > 0 ? i < (n) : i > (n); i += (1)) {
    ;
    for (int j = (0); (1) > 0 ? j < (m) : j > (m); j += (1)) {
      matrix[i][j] = p[i * m + j];
      mp[matrix[i][j]].emplace(i, j);
    }
  }
  vector<vector<long long>> vis(n, vector<long long>(m, 0));
  long long ans = 0;
  ;
  for (int i = (0); (1) > 0 ? i < (n * m) : i > (n * m); i += (1)) {
    pair<long long, long long> pos = mp[a[i]].front();
    mp[a[i]].pop();
    bool found = false;
    ;
    for (int k = (0); (1) > 0 ? k < (m) : k > (m); k += (1)) {
      if (matrix[pos.first][k] == a[i]) found = true;
      if (vis[pos.first][k] && !found) ans++;
    }
    vis[pos.first][pos.second] = 1;
  }
  print(ans);
}
int main() {
  { ios_base::sync_with_stdio(false); }
  {
    cin.tie(NULL);
    cout.tie(NULL);
  }
  int tc = 1;
  cin >> tc;
  while (tc--) solve();
  return 0;
}
