#include <bits/stdc++.h>
using namespace std;
int main() {
  int tc;
  cin >> tc;
  while (tc--) {
    int n, m;
    cin >> n >> m;
    int ar[n + 1][m + 1], ad[n + 1][m + 1];
    vector<int> ve;
    map<int, int> mp;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        ad[i][j] = 0;
        cin >> ar[i][j];
        ve.push_back(ar[i][j]);
      }
    }
    sort(ve.begin(), ve.end());
    for (int i = 0; i < ve.size(); i++) {
      if (mp[ve[i]] == 0) mp[ve[i]] = i + 1;
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
      for (int j = 1; j <= m; j++) {
        int col = mp[ar[i][j]] % m;
        if (col == 0) col = m;
        int row = mp[ar[i][j]] / m;
        if (mp[ar[i][j]] % m != 0) ++row;
        ++mp[ar[i][j]];
        for (int k = 1; k < col; k++) {
          if (ad[row][k] > 0 and ad[row][k] < ar[i][j]) ++ans;
        }
        ad[row][col] = ar[i][j];
      }
    }
    cout << ans << endl;
  }
  return 0;
}
