#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5;
int N, M;
int A[MAXN];
int S[MAXN];
int f_max[400][400];
int f_sum[400][400];
void reset_fenwick() {
  for (int i = 0; i < N; ++i) {
    memset(f_max[i], 0, sizeof(int) * M);
    memset(f_sum[i], 0, sizeof(int) * M);
  }
}
void add(int row, int pos, int ai) {
  while (pos < M) {
    ++f_sum[row][pos];
    f_max[row][pos] = max(f_max[row][pos], ai);
    pos |= (pos + 1);
  }
}
int maxpos(int row, int ai, int maxpos) {
  int ans = 0;
  if (f_max[row][0] >= ai) {
    return -1;
  }
  for (int i = (1 << 9); i > 0; i >>= 1) {
    if ((ans | i) > maxpos) {
      continue;
    }
    if (f_max[row][ans | i] < ai) {
      ans |= i;
    }
  }
  return ans;
}
int sum(int row, int pos) {
  int res = 0;
  while (pos > 0) {
    res += f_sum[row][pos];
    pos = (pos & (pos + 1)) - 1;
  }
  return res;
}
void run_once() {
  cin >> N >> M;
  for (int i = 0; i < N * M; ++i) {
    cin >> A[i];
    S[i] = A[i];
  }
  sort(S, S + N * M);
  for (int i = 0; i < N; ++i) {
    reset_fenwick();
  }
  int ans = 0;
  for (int p = 0; p < N * M; ++p) {
    int lb = lower_bound(S, S + N * M, A[p]) - S;
    int ub = upper_bound(S, S + N * M, A[p]) - S - 1;
    int best_ans = 1e9;
    int best_row = 0;
    int best_pos = 0;
    for (int i = lb / M; i <= ub / M; ++i) {
      int maxpos_limit = (i == ub / M) ? (ub % M) : (M - 1);
      int maxpos_i = maxpos(i, A[p], maxpos_limit);
      if (maxpos_i == -1 || (i == lb / M && maxpos_i < lb % M)) {
        continue;
      }
      int curans = (M - maxpos_i - 1) + sum(i, maxpos_i) - sum(i, M - 1);
      if (curans < best_ans) {
        best_ans = curans;
        best_row = i;
        best_pos = maxpos_i;
      }
    }
    add(best_row, best_pos, A[p]);
    ans += best_ans;
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t;
  cin >> t;
  while (t--) {
    run_once();
  }
  return 0;
}
