#include <bits/stdc++.h>
using namespace std;
template <class T>
bool chmax(T &a, const T &b) {
  return (a < b) ? (a = b, 1) : 0;
}
template <class T>
bool chmin(T &a, const T &b) {
  return (b < a) ? (a = b, 1) : 0;
}
using ll = long long;
using R = long double;
const R EPS = 1e-9L;
inline int sgn(const R &r) { return (r > EPS) - (r < -EPS); }
inline R sq(R x) { return sqrt(max(x, 0.0L)); }
const int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
const pid_t pid = getpid();
template <class S, S (*op)(S, S), S (*e)()>
struct segtree {
 public:
  segtree() : segtree(0) {}
  explicit segtree(int n) : segtree(std::vector<S>(n, e())) {}
  explicit segtree(const std::vector<S> &value) : n(int(value.size())) {
    log = 32 - __builtin_clz(n);
    size = 1 << log;
    data = std::vector<S>(2 * size, e());
    for (int i = 0; i < n; i++) {
      data[size + i] = value[i];
    }
    for (int i = size - 1; i >= 1; i--) {
      update(i);
    }
  }
  void set(int p, S x) {
    p += size;
    data[p] = x;
    for (int i = 1; i <= log; i++) {
      update(p >> i);
    }
  }
  S get(int p) { return data[p + size]; }
  S prod(int l, int r) {
    S sml = e(), smr = e();
    for (l += size, r += size; l < r; l >>= 1, r >>= 1) {
      if (l & 1) {
        sml = op(sml, data[l++]);
      }
      if (r & 1) {
        smr = op(data[--r], smr);
      }
    }
    return op(sml, smr);
  }
  S all_prod() { return data[1]; }

 private:
  int n, size, log;
  std::vector<S> data;
  void update(int k) { data[k] = op(data[2 * k], data[2 * k + 1]); }
};
int op(int a, int b) { return a + b; }
int e() { return 0; }
int main(void) {
  int t;
  cin >> t;
  for (int loop = int(0); loop < int(t); ++loop) {
    int n, m;
    cin >> n >> m;
    vector<int> a(n * m);
    for (int i = int(0); i < int(n * m); ++i) {
      cin >> a[i];
    }
    vector<int> aidx = a;
    sort(begin(aidx), end(aidx));
    aidx.erase(unique(begin(aidx), end(aidx)), end(aidx));
    segtree<int, op, e> segtree(n * m);
    const int k = aidx.size();
    using pii = pair<int, int>;
    vector<vector<pii>> ary(k);
    vector<int> pos(k);
    vector<int> asort = a;
    sort(begin(asort), end(asort));
    for (int i = int(0); i < int(n); ++i)
      for (int j = int(0); j < int(m); ++j) {
        const int idx = m * i + j;
        const int key =
            lower_bound(begin(aidx), end(aidx), asort[idx]) - begin(aidx);
        ary[key].push_back(pii(i, -j));
      }
    for (int key = int(0); key < int(k); ++key) {
      sort(begin(ary[key]), end(ary[key]));
    }
    ll ans = 0LL;
    for (int i = int(0); i < int(n * m); ++i) {
      const int key = lower_bound(begin(aidx), end(aidx), a[i]) - begin(aidx);
      const int row = ary[key][pos[key]].first;
      const int col = -ary[key][pos[key]].second;
      pos[key]++;
      const int idx = row * m + col;
      ans += segtree.prod(row * m, idx);
      segtree.set(idx, 1);
    }
    cout << ans << endl;
  }
  return 0;
}
