#include <bits/stdc++.h>
using namespace std;
inline int read() {
  int x = 0, f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + ch - 48;
    ch = getchar();
  }
  return x * f;
}
const int N = 2e5 + 5;
int n, m;
struct node {
  int w, id;
} a[N];
bool cmp(node a, node b) {
  if (a.w != b.w)
    return a.w > b.w;
  else
    return a.id > b.id;
}
void solve() {
  int ans = 0;
  n = read(), m = read();
  for (int i = (1); i <= (n * m); ++i) a[i] = {read(), i};
  sort(a + 1, a + n * m + 1, cmp);
  for (int i = (1); i <= (n); ++i) {
    for (int j = (1); j <= (m); ++j)
      for (int k = (j + 1); k <= (m); ++k) {
        int id1 = m * (i - 1) + j, id2 = m * (i - 1) + k;
        if (a[id1].id > a[id2].id && a[id1].w != a[id2].w) ans++;
      }
  }
  cout << ans << endl;
}
int main() {
  int T = read();
  while (T--) solve();
  return 0;
}
