#include <bits/stdc++.h>
using namespace std;
void die(string S) {
  puts(S.c_str());
  exit(0);
}
int number[333][333];
int cnt[100100];
vector<int> V[100100];
int grid[333][333];
int main() {
  int t;
  cin >> t;
  while (t--) {
    int n, m;
    cin >> n >> m;
    vector<int> v;
    for (int i = 0; i < n * m; i++) {
      int x;
      cin >> x;
      v.push_back(x);
      number[i / m][i % m] = x;
      cnt[i] = 0;
      V[i].clear();
    }
    sort((v).begin(), (v).end());
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++) {
        number[i][j] =
            lower_bound((v).begin(), (v).end(), number[i][j]) - v.begin();
        cnt[number[i][j]]++;
        V[number[i][j]].push_back(i * m + j);
      }
    int pos = 0;
    for (int i = 0; i < n * m; i++)
      if (cnt[i]) {
        int endp = (pos + cnt[i] - 1);
        if (endp / m == pos / m) {
          sort((V[i]).rbegin(), (V[i]).rend());
          for (int j = 0; j < cnt[i]; j++)
            grid[(pos + j) / m][(pos + j) % m] = V[i][j];
        } else {
          sort((V[i]).begin(), (V[i]).end());
          int x = m - pos % m;
          for (int j = x - 1; j >= 0; j--)
            grid[(pos + x - j - 1) / m][(pos + x - j - 1) % m] = V[i][j];
          x = endp % m + 1;
          for (int j = cnt[i] - 1; j >= cnt[i] - x; j--)
            grid[(endp / m * m + cnt[i] - j - 1) / m]
                [(endp / m * m + cnt[i] - j - 1) % m] = V[i][j];
          for (int j = m - pos % m; j < cnt[i] - x; j++)
            grid[(pos + j) / m][(pos + j) % m] = V[i][j];
          for (int j = pos / m + 1; j < endp / m; j++)
            reverse(grid[j], grid[j] + m);
        }
        pos += cnt[i];
      }
    int ans = 0;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < m; j++)
        for (int k = j + 1; k < m; k++)
          if (grid[i][j] < grid[i][k]) ans++;
    cout << ans << endl;
  }
  return 0;
}
