#include <bits/stdc++.h>
using namespace std;
const double pi = 3.14159265358979323846;
const long long int INF = 1e15;
const long long int MOD = 1e9 + 7;
long long int rootn(long long int x, long long int y) {
  return ceil(log(x) / log(y));
}
bool sortbysec(pair<long long int, long long int> &a,
               pair<long long int, long long int> &b) {
  return a.second < b.second;
}
bool sortbyfirstdesc(pair<long long int, long long int> &a,
                     pair<long long int, long long int> &b) {
  return a.first > b.first;
}
bool sortbysecdesc(pair<long long int, long long int> &a,
                   pair<long long int, long long int> &b) {
  return a.second > b.second;
}
long long int power(long long int x, long long int y) {
  if (y == 0) return 1;
  if (y % 2 == 0)
    return power(x, y / 2) * power(x, y / 2);
  else
    return x * power(x, y / 2) * power(x, y / 2);
}
long long int inversemod(long long int n, long long int mod) {
  return power(n, mod - 2) % MOD;
}
const long long int maxl = 2e5 + 5;
bool isprime[maxl];
long long int fact[maxl];
void sieve() {
  memset(isprime, true, sizeof(isprime));
  isprime[0] = isprime[1] = false;
  for (long long int i = 2; i * i < maxl; i++) {
    if (isprime[i]) {
      for (long long int j = i * i; j < maxl; j += i) isprime[j] = false;
    }
  }
}
void inifact() {
  fact[0] = 1;
  fact[1] = 1;
  for (long long int i = 2; i < maxl; i++) {
    fact[i] = i * fact[i - 1];
    fact[i] %= MOD;
  }
}
bool comp(const pair<long long int, long long int> &a,
          const pair<long long int, long long int> &b) {
  if (a.first == b.first) return a.second > b.second;
  return a.first < b.first;
}
void solve() {
  long long int n, m;
  cin >> n >> m;
  vector<pair<long long int, long long int>> v;
  for (long long int i = 0; i < n * m; i++) {
    long long int x;
    cin >> x;
    v.push_back({x, i + 1});
  }
  sort(v.begin(), v.end());
  vector<vector<pair<long long int, long long int>>> an;
  long long int cntidx = 0;
  for (long long int i = 0; i < n; i++) {
    vector<pair<long long int, long long int>> loc;
    for (long long int j = 0; j < m; j++) {
      loc.push_back(v[cntidx]);
      cntidx++;
    }
    an.push_back(loc);
  }
  for (long long int i = 0; i < n; i++) {
    sort(an[i].begin(), an[i].end(), comp);
  }
  long long int ans = 0;
  for (long long int i = 0; i < n; i++) {
    vector<pair<long long int, long long int>> loc = an[i];
    for (long long int j = 1; j < m; j++) {
      for (long long int k = 0; k < j; k++) {
        if (loc[j].second > loc[k].second) ans++;
      }
    }
  }
  cout << ans << "\n";
}
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  ;
  long long int t = 1;
  cin >> t;
  while (t--) solve();
}
