#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("O3")
#pragma GCC target("avx")
using namespace std;
void solve() {
  long long n, m, x, y, z, ans = 0;
  cin >> n >> m;
  long long arr[n][m];
  vector<long long> v1, v2;
  for (long long i = 0; i < n * m; i++) {
    cin >> x;
    v1.push_back(x);
    v2.push_back(x);
  }
  sort(v2.rbegin(), v2.rend());
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < m; j++) {
      x = v2.back();
      v2.pop_back();
      arr[i][j] = x;
    }
  }
  map<long long, vector<pair<long long, long long>>> map;
  for (long long i = n - 1; i >= 0; i--) {
    for (long long j = 0; j < m; j++) map[arr[i][j]].push_back({i, j});
  }
  memset(arr, 0, sizeof(arr));
  for (long long i : v1) {
    x = map[i].back().first;
    y = map[i].back().second;
    map[i].pop_back();
    for (long long i = 0; i < y; i++) {
      if (arr[x][i]) ans++;
    }
    arr[x][y] = 1;
  }
  cout << ans << '\n';
  return;
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) solve();
  return 0;
}
