#include <bits/stdc++.h>
using namespace std;
int main() {
  int t;
  cin >> t;
  for (int l = 0; l < t; l++) {
    int n, m;
    cin >> n >> m;
    long long A[n * m];
    long long B[n][m];
    set<long long> S;
    unordered_map<long long, vector<int>> M;
    vector<pair<long long, long long>> V;
    for (int i = 0; i < n * m; i++) {
      cin >> A[i];
      B[i / m][i % m] = 0;
      S.insert(A[i]);
      M[A[i]].push_back(i + 1);
    }
    long long cnt = 0, cur = 0;
    for (auto s : S) {
      int passed = 0;
      sort(M[s].begin(), M[s].end());
      int amount = M[s].size();
      while (amount) {
        if (amount >= m - cur % m) {
          for (int i = cur; i < cur + m - cur % m; i++) {
            B[i / m][i % m] = M[s][passed + (m - 1 - cur % m) - (i - cur)];
          }
          passed += m - cur % m;
          amount -= m - cur % m;
          cur += m - cur % m;
        } else {
          for (int i = cur; i < cur + amount; i++) {
            B[i / m][i % m] = M[s][passed + amount - 1 - (i - cur)];
          }
          passed += amount;
          cur += amount;
          amount = 0;
        }
      }
    }
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        for (int k = j + 1; k < m; k++) {
          if (B[i][j] < B[i][k]) {
            cnt++;
          }
        }
      }
    }
    cout << cnt << endl;
  }
  return 0;
}
