#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 1;
long long a[N], b[N];
void solve() {
  long long i, j, n, m;
  cin >> n >> m;
  for (i = 0; i < n * m; i++) {
    cin >> a[i];
    b[i] = a[i];
  }
  sort(b, b + n * m);
  map<long long, stack<long long>> ma;
  for (i = 0; i < n * m; i++) ma[b[i]].push(i);
  vector<set<long long>> rows(n);
  long long incon = 0;
  for (i = 0; i < n * m; i++) {
    long long seatNo = ma[a[i]].top();
    ma[a[i]].pop();
    long long rowNo = seatNo / m;
    incon += distance(rows[rowNo].begin(), rows[rowNo].lower_bound(seatNo));
    rows[rowNo].insert(seatNo);
  }
  cout << incon;
  cout << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t = 1;
  cin >> t;
  while (t--) solve();
  return 0;
}
