#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long long modx = 998244353;
int d4x[4] = {1, 0, -1, 0};
int d4y[4] = {0, 1, 0, -1};
int d8x[8] = {0, 1, 1, 1, 0, -1, -1, -1};
int d8y[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const long long oo = 1e18;
void solve() {
  long long n, i, j, k, m;
  cin >> n >> m;
  vector<vector<long long> > a;
  for (long long i = 0; i < n * m; i++) {
    cin >> k;
    a.push_back({k, i});
  }
  sort((a).begin(), (a).end(), [](vector<long long> a1, vector<long long> b) {
    if (a1[0] == b[0])
      return a1[1] < b[1];
    else
      return a1[0] < b[0];
  });
  long long ans = 0;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      long long z = i * m + j;
      for (int k = 0; k < j; k++) {
        if (a[i * m + k][1] < a[z][1] && a[i * m + k][0] != a[z][0]) {
          ans++;
        }
      }
    }
  }
  cout << ans << "\n";
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int tc;
  cin >> tc;
  while (tc--) {
    solve();
  }
}
